<?php

namespace App\Controllers\Admin;

use App\Models\AdminModel;

class Auth extends AdminBaseController
{
    public function login()
    {
        if ($this->session->get('admin_logged_in')) {
            return redirect()->to('/admin/dashboard');
        }

        if ($this->request->getMethod() === 'POST') {
            $email = $this->request->getPost('email');
            $password = $this->request->getPost('password');

            $model = new AdminModel();
            $admin = $model->where('email', $email)->first();

            if ($admin && password_verify($password, $admin['password'])) {
                // Prevent Session Fixation
                $this->session->regenerate();
                
                $sessionData = [
                    'admin_id' => $admin['id'],
                    'admin_name' => $admin['name'],
                    'admin_email' => $admin['email'],
                    'admin_logged_in' => true,
                ];
                $this->session->set($sessionData);
                return redirect()->to('/admin/dashboard');
            } else {
                $this->session->setFlashdata('error', 'Invalid Email or Password');
                return redirect()->to('/admin/login')->withInput();
            }
        }

        return view('admin/login');
    }

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