<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\SettingModel;

class Login extends BaseController
{
    public function index()
    {
        // If already logged in, redirect to dashboard
        if ($this->session->get('admin_logged_in')) {
            return redirect()->to(site_url('admin/dashboard'));
        }

        $this->data['title'] = 'Admin Login';
        return view('admin/login', $this->data);
    }

    public function authenticate()
    {
        if ($this->request->getMethod() !== 'post') {
            return redirect()->to(site_url('admin/login'));
        }

        $validation = \Config\Services::validation();
        $validation->setRules([
            'username' => 'required',
            'password' => 'required'
        ]);

        if (!$validation->withRequest($this->request)->run()) {
            $this->session->setFlashdata('error', 'Please fill in all required fields correctly.');
            return redirect()->to(site_url('admin/login'));
        }

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

        // Check admin credentials from settings
        $admin_user = $this->data['setting']['admin_user'] ?? '';
        $admin_pass_hash = $this->data['setting']['admin_pass'] ?? '';

        if ($username !== $admin_user || !password_verify($password, $admin_pass_hash)) {
            $this->session->setFlashdata('error', 'Invalid username or password.');
            return redirect()->to(site_url('admin/login'));
        }

        // Set admin session
        $this->session->set([
            'admin_logged_in' => true,
            'admin_username' => $username
        ]);

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

    public function logout()
    {
        $this->session->destroy();
        return redirect()->to(site_url('admin/login'));
    }
}
