<?php

namespace App\Controllers;

use App\Models\User;
use App\Models\Mahasiswa;
use App\Models\Dosen;
use App\Models\Admin;
use App\Models\Maba;

class AuthController
{
    public function login()
    {
        // Tidak perlu session_start() jika sudah di public/index.php

        // Batasi brute force
        if (!isset($_SESSION['login_attempts'])) {
            $_SESSION['login_attempts'] = 0;
        }
        if ($_SESSION['login_attempts'] >= 5) {
            $_SESSION['error'] = 'Terlalu banyak percobaan login. Coba lagi nanti.';
            header('Location: /');
            exit;
        }

        // CSRF protection
        if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== ($_SESSION['csrf_token'] ?? '')) {
            $_SESSION['error'] = 'Permintaan tidak valid (CSRF).';
            header('Location: /');
            exit;
        }

        // Sanitize input secara aman
        $username = htmlspecialchars(trim($_POST['username'] ?? ''));
        $password = md5($_POST['password'] ?? '');

        $userModel = new User();
        $user = $userModel->findByUsername($username);

        if (!$user || $user['password'] !== $password) {
            $_SESSION['login_attempts']++;
            $_SESSION['error'] = 'Username atau password salah.';
            header('Location: /');
            exit;
        }

        // Reset percobaan login
        $_SESSION['login_attempts'] = 0;

        // Tambahan info pengguna sesuai level
        $level = strtolower($user['level']);

        if ($level === 'mahasiswa') {
            $mhs = (new Mahasiswa())->findByUsername($username);
            if ($mhs) {
                $user['nim'] = $mhs['nim'];
                $user['nama'] = $mhs['nama'];
            }
        } elseif ($level === 'maba') {
            $mabaModel = new Maba();
            $mhsPmb = $mabaModel->findByUsername($username);
        
            if ($mhsPmb) {
                // simpan identitas maba di session
                $user['username']    = $mhsPmb['nisn'];       // <-- tambahkan ini
                $user['nisn']        = $mhsPmb['nisn'];
                $user['nama_camaba'] = $mhsPmb['nama_camaba'];
        
                // pastikan ada record di tb_mahasiswa (auto insert saat login pertama)
                $mhsExist = $mabaModel->checkMahasiswa($mhsPmb['nisn']);
                if (!$mhsExist) {
                    $mabaModel->insertToMahasiswa($mhsPmb);
                }
        
                // --- alur wajib isi data ---
                if (!$mabaModel->isProfileComplete($mhsPmb['nisn'])) {
                    $_SESSION['flash'] = "Profile belum lengkap, silahkan lengkapi";
                    session_regenerate_id(true);
                    $_SESSION['user'] = $user;
                    header("Location: /dashboard/maba-profile");
                    exit;
                }
        
                if (!$mabaModel->isOrangTuaComplete($mhsPmb['nisn'])) {
                    $_SESSION['flash'] = "Profile orang tua belum lengkap";
                    session_regenerate_id(true);
                    $_SESSION['user'] = $user;
                    header("Location: /dashboard/maba-orangtua");
                    exit;
                }
        
                if (!$mabaModel->hasKelas($mhsPmb['nisn'])) {
                    $_SESSION['flash'] = "Silahkan pilih kelas terlebih dahulu";
                    session_regenerate_id(true);
                    $_SESSION['user'] = $user;
                    header("Location: /dashboard/maba-pilihkelas");
                    exit;
                }
            }
        } elseif (in_array($level, ['dosen', 'dosen/kaprodi'])) {
            $dosen = (new Dosen())->findByUsername($username);
            if ($dosen) {
                $user['niy'] = $dosen['niy'];
                $user['nama'] = $dosen['nama'];
            }
        } elseif (in_array($level, ['admin', 'pegawai'])) {
            $adm = (new Admin())->findByUsername($username);
            if ($adm) {
                $user['username'] = $adm['username'];
                $user['nama'] = $adm['nama'];
            }
        }

        // Amanin session
        session_regenerate_id(true);
        $_SESSION['user'] = $user;

        $redirect = [
            'admin'         => '/dashboard/admin',
            'pegawai'       => '/dashboard/pegawai',
            'staff'         => '/dashboard/staff',
            'pimpinan'      => '/dashboard/pimpinan',
            'humas'         => '/dashboard/humas',
            'mahasiswa'     => '/dashboard/mahasiswa',
            'maba'          => '/dashboard/maba',            
            'dosen'         => '/dashboard/dosen',
            'dosen/kaprodi' => '/dashboard/dosen',
        ];

        $target = $redirect[$level] ?? '/';
        header("Location: $target");
        exit;
    }

    public function isProfileComplete($nisn)
    {
        $data = $this->findMahasiswaByNim($nisn);
        return !empty($data['alamat']) && !empty($data['tgl_lahir']) && !empty($data['nik']);
    }
    
    public function isOrangTuaComplete($nisn)
    {
        $data = $this->findMahasiswaByNim($nisn);
        return !empty($data['nama_ayah']) && !empty($data['nama_ibu']);
    }
    
    public function hasKelas($nisn)
    {
        $data = $this->findMahasiswaByNim($nisn);
        return !empty($data['kelas']);
    }

    public function logout()
    {
        // Tidak perlu session_start() jika sudah global
        session_destroy();
        header('Location: /');
        exit;
    }
}
