<?php
require_once __DIR__ . '/../../../Models/Admin.php';

class AuthController {
    public function login() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        if (isset($_SESSION['admin_id'])) {
            $basePath = defined('BASE_PATH') ? BASE_PATH : (str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])) === '/' ? '' : str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])));
            header('Location: ' . $basePath . '/admin?page=dashboard');
            exit;
        }

        $error = '';

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $email = $_POST['email'] ?? '';
            $password = $_POST['password'] ?? '';

            if (empty($email) || empty($password)) {
                $error = 'Email and password are required.';
            } else {
                $adminModel = new Admin();
                $admin = $adminModel->findByEmail($email);

                if ($admin && password_verify($password, $admin['password'])) {
                    if ($admin['status'] !== 'active') {
                        $error = 'Your account is inactive.';
                    } else {
                        $_SESSION['admin_id'] = $admin['id'];
                        $_SESSION['admin_name'] = $admin['name'];
                        $basePath = defined('BASE_PATH') ? BASE_PATH : (str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])) === '/' ? '' : str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])));
                        header('Location: ' . $basePath . '/admin?page=dashboard');
                        exit;
                    }
                } else {
                    $error = 'Invalid email or password.';
                }
            }
        }

        require __DIR__ . '/../../../../views/admin/login.php';
    }

    public function logout() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        unset($_SESSION['admin_id']);
        unset($_SESSION['admin_name']);
        $basePath = defined('BASE_PATH') ? BASE_PATH : (str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])) === '/' ? '' : str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])));
        header('Location: ' . $basePath . '/admin?page=login');
        exit;
    }
}
