<?php

namespace App\Controllers;

use App\Models\M_user;
use CodeIgniter\Controller;

class Auth extends Controller
{
    public function login()
    {
        return view('login');
    }

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

        $userModel = new M_user();
        $user = $userModel->where('username', $username)->first();

        if ($user && password_verify($password, $user['password'])) {

            // Jika role guru, pastikan id_guru valid
            if ($user['role'] === 'guru') {
                if (empty($user['id_guru'])) {
                    return redirect()->back()->with('error', 'Akun guru belum terhubung ke data guru.');
                }
            }

           // Data session (lengkap untuk keperluan profil)
        $sessionData = [
            'id'         => $user['id'],
            'username'   => $user['username'],
            'nama'       => $user['nama'] ?? null,
            'email'      => $user['email'] ?? null,
            'photo'      => $user['photo'] ?? null,
            'role'       => $user['role'],
            'isLoggedIn' => true,
        ];


            // Tambahkan id_guru hanya jika role guru
            if ($user['role'] === 'guru') {
                $sessionData['id_guru'] = $user['id_guru'];
            }

            // Simpan session 'login' dengan data user
            session()->set('login', $sessionData);

            // Redirect sesuai role
            switch ($user['role']) {
                case 'admin':
                    return redirect()->to('/dashboard/admin');
                case 'kepsek':
                    return redirect()->to('/dashboard/kepsek');
                case 'guru':
                    return redirect()->to('/dashboard/guru');
                default:
                    return redirect()->to('/login')->with('error', 'Role tidak dikenali.');
            }
        } else {
            return redirect()->back()->with('error', 'Username atau password salah.');
        }
    }

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