<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Models\SekolahModel; // Tambahkan Model Sekolah

class Auth extends BaseController
{
    public function index()
    {
        if (session()->get('logged_in')) {
            if (session()->get('level') == 'admin') {
                return redirect()->to('/admin/dashboard');
            }
            return redirect()->to('/petugas/dashboard');
        }

        // Ambil data sekolah untuk ditampilkan di Login
        $sekolahModel = new SekolahModel();
        $sekolah = $sekolahModel->first();

        // Kirim data $sekolah ke view
        return view('auth/login', ['sekolah' => $sekolah]);
    }

    public function process()
    {
        $model = new UserModel();
        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');

        $user = $model->where('username', $username)->first();

        if ($user) {
            if (password_verify($password, $user['password'])) {
                $sessionData = [
                    'id'        => $user['id'],
                    'nama'      => $user['nama_lengkap'],
                    'username'  => $user['username'],
                    'level'     => $user['level'],
                    'foto'      => $user['foto'],
                    'logged_in' => true,
                ];
                session()->set($sessionData);

                if ($user['level'] == 'admin') {
                    return redirect()->to('/admin/dashboard');
                }
                return redirect()->to('/petugas/dashboard');
            } else {
                session()->setFlashdata('error', 'Password salah.');
                return redirect()->to('/');
            }
        } else {
            session()->setFlashdata('error', 'Username tidak ditemukan.');
            return redirect()->to('/');
        }
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/');
    }
}