<?php

namespace App\Controllers;

use App\Models\UserModel;

class Auth extends BaseController
{
    public function index()
    {
        // Jika sudah login, redirect ke dashboard
        if (session()->get('isLoggedIn')) {
            return redirect()->to('/');
        }

        $data = [
            'title' => 'Login | SIAKAD ITKA'
        ];
        
        // Pengecekan cookie remember me bisa di filter atau disini
        // Tapi kita akan tangani auth murni dengan session dulu

        return view('auth/login', $data);
    }

    public function loginSubmit()
    {
        $session = session();
        $userModel = new UserModel();

        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');
        $remember = $this->request->getPost('remember');

        $user = $userModel->getUserWithRole($username);

        if ($user) {
            // Cek status aktif
            if ($user['is_active'] == 0) {
                $session->setFlashdata('error', 'Akun Anda tidak aktif. Silakan hubungi administrator.');
                return redirect()->to('/login')->withInput();
            }

            $pass = $user['password_hash'];
            $authenticatePassword = password_verify($password, $pass);

            if ($authenticatePassword) {
                $ses_data = [
                    'id'         => $user['id'],
                    'username'   => $user['username'],
                    'role_id'    => $user['role_id'],
                    'nama_role'  => $user['nama_role'],
                    'email'      => $user['email'],
                    'isLoggedIn' => TRUE
                ];
                $session->set($ses_data);

                // Implementasi Remember Me (Cookie based)
                if ($remember) {
                    // Set cookie yang berlaku selama 30 hari
                    set_cookie('remember_username', $user['username'], 3600 * 24 * 30);
                } else {
                    delete_cookie('remember_username');
                }

                return redirect()->to('/');
            } else {
                $session->setFlashdata('error', 'Password salah.');
                return redirect()->to('/login')->withInput();
            }
        } else {
            $session->setFlashdata('error', 'Username tidak ditemukan.');
            return redirect()->to('/login')->withInput();
        }
    }

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