<?php

declare(strict_types=1);

namespace Admin\Controllers;

use App\Core\Controller;

/**
 * Admin Auth Controller
 *
 * Handles admin login and logout with CSRF protection
 * and secure password verification. Extends the base
 * Controller directly (not AdminController) since
 * login page must be accessible without authentication.
 */
class AdminAuthController extends Controller
{
    /**
     * Display the admin login form.
     *
     * Redirects to dashboard if already logged in as admin.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function loginForm(array $params = []): void
    {
        // If already admin, redirect to dashboard
        if (isAdmin()) {
            redirect(BASE_PATH . '/admin/dashboard');
        }

        $flash_error   = flash('error');
        $flash_success = flash('success');
        $csrfToken     = generateCsrfToken();
        $title         = 'Admin Login';

        $viewFile = APP_ROOT . '/admin/Views/login.php';

        if (!file_exists($viewFile)) {
            http_response_code(500);
            echo "Error: Admin login view could not be found.";
            exit;
        }

        require $viewFile;
        exit;
    }

    /**
     * Process admin login attempt.
     *
     * Validates CSRF token, looks up the user by email,
     * verifies the password, and checks the admin role.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function login(array $params = []): void
    {
        $this->validateCsrf();

        $email    = sanitize($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';

        if (empty($email) || empty($password)) {
            flash('error', 'Please enter both email and password.');
            redirect(BASE_PATH . '/admin/login');
        }

        // Look up user by email
        $stmt = $this->db->prepare(
            'SELECT * FROM `users` WHERE `email` = :email AND `is_active` = 1 LIMIT 1'
        );
        $stmt->execute([':email' => $email]);
        $user = $stmt->fetch() ?: null;

        if ($user === null) {
            flash('error', 'Invalid email or password.');
            redirect(BASE_PATH . '/admin/login');
        }

        // Verify password
        if (!password_verify($password, $user['password'])) {
            flash('error', 'Invalid email or password.');
            redirect(BASE_PATH . '/admin/login');
        }

        // Check admin role (super_admin can also access the existing admin panel)
        if ($user['role'] !== 'admin' && $user['role'] !== 'staff' && $user['role'] !== 'super_admin') {
            flash('error', 'You do not have admin access.');
            redirect(BASE_PATH . '/admin/login');
        }

        // Log in the user
        \login([
            'id'     => $user['id'],
            'name'   => $user['name'],
            'email'  => $user['email'],
            'role'   => $user['role'],
            'avatar' => $user['photo'] ?? null,
        ]);

        flash('success', 'Welcome back, ' . htmlspecialchars($user['name'], ENT_QUOTES, 'UTF-8') . '!');
        redirect(BASE_PATH . '/admin/dashboard');
    }

    /**
     * Log out the admin user.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function logout(array $params = []): void
    {
        \logout();
    }
}
