<?php

declare(strict_types=1);

namespace SuperAdmin\Controllers;

/**
 * Super Admin Authentication Controller
 *
 * Handles Super Admin login (via email + password) and logout.
 * Only users with role='super_admin' can log in here.
 *
 * NOTE: This is SEPARATE from Admin\Controllers\AdminAuthController which
 * handles the existing /admin/* panel for role='admin' users.
 */
class SuperAdminAuthController extends SuperAdminBaseController
{
    /**
     * Display the Super Admin login form.
     */
    public function loginForm(): void
    {
        // Already logged in as super admin? Go to dashboard.
        if (isSuperAdmin()) {
            redirect(BASE_PATH . '/super-admin/dashboard');
        }

        $this->loginView(['title' => 'Super Admin Login']);
    }

    /**
     * Process Super Admin login.
     */
    public function login(): void
    {
        $this->validateCsrf();

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

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

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

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

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

        // Check account status
        $status = $user['status'] ?? 'active';
        $isActive = (int) ($user['is_active'] ?? 1);
        if ($status !== 'active' || $isActive !== 1) {
            flash('error', 'Your account is not active. Please contact the system administrator.');
            redirect(BASE_PATH . '/super-admin/login');
        }

        // Set session via login() helper
        \login([
            'id'          => $user['id'],
            'name'        => $user['name'],
            'email'       => $user['email'],
            'role'        => $user['role'],
            'avatar'      => $user['photo'] ?? null,
            'branch_id'   => $user['branch_id'] ?? null,
            'branch_code' => $user['branch_code'] ?? null,
        ]);

        // Audit log
        $this->auditLog('super_admin_login', 'user', (int) $user['id'], 'Super Admin logged in');

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

    /**
     * Log out the Super Admin.
     */
    public function logout(): void
    {
        $this->auditLog('super_admin_logout', 'user', $_SESSION['user_id'] ?? null, 'Super Admin logged out');
        \logout();
    }
}
