<?php

namespace App\Controllers;

use App\Models\UserModel;

class Auth extends BaseController
{
    public function index()
    {
        return redirect()->to('/login');
    }

    public function login()
    {
        if (session()->get('logged_in')) {
            return redirect()->to('/dashboard');
        }
        return view('auth/login');
    }

    public function loginProcess()
    {
        $username = $this->request->getPost('username'); // name di form = username
        $password = $this->request->getPost('password');

        $model = new UserModel();
        $user  = $model->findByUsername($username);

        if (!$user || !password_verify($password, $user['password'])) {
            return redirect()->back()
                ->with('error', 'Username/NISN atau password salah!')
                ->withInput();
        }

        // Cek status siswa jika user adalah siswa
        if ($user['role'] === 'siswa' && !empty($user['student_id'])) {
            $studentModel = new \App\Models\StudentModel();
            $student = $studentModel->find($user['student_id']);
            if (!$student || $student['status'] !== 'Aktif') {
                $statusText = $student ? $student['status'] : 'Tidak Ditemukan';
                return redirect()->back()
                    ->with('error', 'Akun siswa tidak aktif (Status: ' . $statusText . ')')
                    ->withInput();
            }
        }

        session()->set([
            'logged_in'  => true,
            'user_id'    => $user['id'],
            'user_name'  => $user['name'],
            'user_role'  => $user['role'],
            'username'   => $user['username'],
            'student_id' => $user['student_id'] ?? null,
        ]);

        if ($user['role'] === 'siswa' && $user['is_password_reset'] == 1) {
            return redirect()->to('/siswa/change-password')->with('info', 'Harap ubah password bawaan Anda demi keamanan akun.');
        }

        if ($user['role'] === 'siswa') {
            return redirect()->to('/siswa/dashboard');
        }

        return redirect()->to('/dashboard');
    }

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