<?php

namespace App\Controllers\PPDB;

use App\Controllers\BaseController;
use App\Models\PpdbSiswaModel;

class Auth extends BaseController
{
    protected $siswa;

    public function __construct()
    {
        $this->siswa = new PpdbSiswaModel();
    }

    // =============================
    // FORM LOGIN
    // =============================
    public function login()
    {
        return view('ppdb/login');
    }

    // =============================
    // PROSES LOGIN
    // =============================
    public function process()
    {
        $email = $this->request->getPost('email');
        $password = $this->request->getPost('password');

        $user = $this->siswa
            ->where('email', $email)
            ->where('status', 1)
            ->first();

        if (!$user) {
            return redirect()->back()->with('error', 'Akun tidak ditemukan atau belum aktif');
        }

        if (!password_verify($password, $user['password'])) {
            return redirect()->back()->with('error', 'Password salah');
        }

        session()->set([
            'ppdb_logged_in' => true,
            'ppdb_id' => $user['id'],
            'ppdb_nama' => $user['nama_siswa'],
            'ppdb_email' => $user['email'],
        ]);

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

    // =============================
    // LOGOUT
    // =============================
    public function logout()
    {
        session()->remove([
            'ppdb_logged_in',
            'ppdb_id',
            'ppdb_nama',
            'ppdb_email',
        ]);

        return redirect()->to('/ppdb/login');
    }
}
