<?php

declare(strict_types=1);

namespace BranchAdmin\Controllers;

/**
 * Branch Admin Authentication Controller
 *
 * Handles branch admin login (via branch_code OR email + password) and logout.
 * Only users with role='branch_admin' can log in here.
 *
 * Login URL: /branch/login
 */
class BranchAuthController extends BranchBaseController
{
    /**
     * Display the Branch Admin login form.
     */
    public function loginForm(): void
    {
        // Already logged in as branch admin? Go to dashboard.
        if (isBranchAdmin()) {
            redirect(BASE_PATH . '/branch/dashboard');
        }

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

    /**
     * Process Branch Admin login.
     *
     * Accepts login via:
     *   1. Branch code (e.g. GMBR01) + password
     *   2. Email (e.g. branch@gmindinstitute.in) + password
     */
    public function login(): void
    {
        $this->validateCsrf();

        $loginId  = trim($_POST['login_id'] ?? ''); // branch_code OR email
        $password = $_POST['password'] ?? '';

        if (empty($loginId) || empty($password)) {
            flash('error', 'Please enter your Branch Code / Email and password.');
            redirect(BASE_PATH . '/branch/login');
        }

        // Determine if login_id is email or branch_code
        $isEmail = filter_var($loginId, FILTER_VALIDATE_EMAIL) !== false;

        if ($isEmail) {
            // Login by email
            $stmt = $this->db->prepare(
                "SELECT u.*, b.`branch_code`, b.`name` AS branch_name, b.`status` AS branch_status
                 FROM `users` u
                 INNER JOIN `branches` b ON u.`branch_id` = b.`id`
                 WHERE u.`email` = :email AND u.`role` = 'branch_admin'
                 LIMIT 1"
            );
            $stmt->execute([':email' => $loginId]);
        } else {
            // Login by branch_code — uppercase normalize
            $branchCodeInput = strtoupper($loginId);
            $stmt = $this->db->prepare(
                "SELECT u.*, b.`branch_code`, b.`name` AS branch_name, b.`status` AS branch_status
                 FROM `users` u
                 INNER JOIN `branches` b ON u.`branch_id` = b.`id`
                 WHERE b.`branch_code` = :branch_code AND u.`role` = 'branch_admin'
                 LIMIT 1"
            );
            $stmt->execute([':branch_code' => $branchCodeInput]);
        }

        $user = $stmt->fetch() ?: null;

        if (!$user) {
            flash('error', 'Invalid Branch Code/Email or password.');
            redirect(BASE_PATH . '/branch/login');
        }

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

        // Check user account status
        $userStatus = $user['status'] ?? 'active';
        $userIsActive = (int) ($user['is_active'] ?? 1);
        if ($userStatus !== 'active' || $userIsActive !== 1) {
            flash('error', 'Your account is not active. Please contact the Super Admin.');
            redirect(BASE_PATH . '/branch/login');
        }

        // Check branch status (must be 'active')
        $branchStatus = $user['branch_status'] ?? 'pending';
        if ($branchStatus !== 'active') {
            flash('error', "Your branch is currently '{$branchStatus}'. Please contact the Super Admin to activate.");
            redirect(BASE_PATH . '/branch/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'],
            'branch_code' => $user['branch_code'],
        ]);

        // Audit log
        $this->auditLog('branch_admin_login', 'user', (int) $user['id'], "Branch admin logged in ({$user['branch_code']})");

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

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