<?php
declare(strict_types=1);

/**
 * Pure Chemical Admin Authentication
 *
 * File:
 * admin/includes/auth.php
 *
 * Purpose:
 * - Start and secure admin session
 * - Check admin login status
 * - Provide current admin information
 * - Protect admin pages
 * - Support login/logout
 *
 * Required session values:
 * $_SESSION['admin_id']
 * $_SESSION['admin_logged_in']
 * $_SESSION['admin_name']
 * $_SESSION['admin_email']
 */

if (session_status() !== PHP_SESSION_ACTIVE) {

    $isHttps = (
        (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || ((int)($_SERVER['SERVER_PORT'] ?? 0) === 443)
    );

    session_set_cookie_params([
        'lifetime' => 0,
        'path'     => '/',
        'domain'   => '',
        'secure'   => $isHttps,
        'httponly' => true,
        'samesite' => 'Lax',
    ]);

    session_start();
}


/*
|--------------------------------------------------------------------------
| Session Security
|--------------------------------------------------------------------------
*/

if (!isset($_SESSION['initiated'])) {
    session_regenerate_id(true);
    $_SESSION['initiated'] = true;
}


/*
|--------------------------------------------------------------------------
| Login Check
|--------------------------------------------------------------------------
*/

function isAdminLoggedIn(): bool
{
    if (
        empty($_SESSION['admin_logged_in'])
        || $_SESSION['admin_logged_in'] !== true
        || empty($_SESSION['admin_id'])
    ) {
        return false;
    }

    return true;
}


/*
|--------------------------------------------------------------------------
| Current Admin ID
|--------------------------------------------------------------------------
*/

function adminId(): ?int
{
    if (!isAdminLoggedIn()) {
        return null;
    }

    return (int) $_SESSION['admin_id'];
}


/*
|--------------------------------------------------------------------------
| Current Admin Name
|--------------------------------------------------------------------------
*/

function adminName(): string
{
    if (!isAdminLoggedIn()) {
        return 'Administrator';
    }

    return trim((string) ($_SESSION['admin_name'] ?? 'Administrator'));
}


/*
|--------------------------------------------------------------------------
| Current Admin Email
|--------------------------------------------------------------------------
*/

function adminEmail(): string
{
    if (!isAdminLoggedIn()) {
        return '';
    }

    return trim((string) ($_SESSION['admin_email'] ?? ''));
}


/*
|--------------------------------------------------------------------------
| Current Admin Role
|--------------------------------------------------------------------------
*/

function adminRoleId(): ?int
{
    if (!isAdminLoggedIn()) {
        return null;
    }

    if (
        !isset($_SESSION['admin_role_id'])
        || $_SESSION['admin_role_id'] === ''
    ) {
        return null;
    }

    return (int) $_SESSION['admin_role_id'];
}


/*
|--------------------------------------------------------------------------
| Require Admin Login
|--------------------------------------------------------------------------
|
| Use this at the top of every protected admin page:
|
| require_once __DIR__ . '/includes/auth.php';
| requireAdmin();
|
*/

function requireAdmin(): void
{
    if (isAdminLoggedIn()) {
        return;
    }

    $currentUrl = $_SERVER['REQUEST_URI'] ?? '/admin/index.php';

    /*
     * Prevent extremely long session values.
     */
    if (strlen($currentUrl) > 2000) {
        $currentUrl = '/admin/index.php';
    }

    $_SESSION['redirect_after_login'] = $currentUrl;

    header('Location: /admin/login.php');
    exit;
}


/*
|--------------------------------------------------------------------------
| Redirect If Already Logged In
|--------------------------------------------------------------------------
|
| Useful on login.php.
|
*/

function redirectIfAdminLoggedIn(): void
{
    if (!isAdminLoggedIn()) {
        return;
    }

    $redirect = $_SESSION['redirect_after_login'] ?? '/admin/index.php';

    unset($_SESSION['redirect_after_login']);

    /*
     * Only allow internal admin URLs.
     */
    if (
        !is_string($redirect)
        || $redirect === ''
        || strpos($redirect, '/') !== 0
        || strpos($redirect, '//') === 0
    ) {
        $redirect = '/admin/index.php';
    }

    header('Location: ' . $redirect);
    exit;
}


/*
|--------------------------------------------------------------------------
| Login Admin
|--------------------------------------------------------------------------
|
| This function verifies an admin password and creates the
| authenticated session.
|
| Usage:
|
| $admin = authenticateAdmin($pdo, $email, $password);
|
| if ($admin !== null) {
|     // Login successful
| }
|
*/

function authenticateAdmin(
    PDO $pdo,
    string $email,
    string $password
): ?array {

    $email = trim($email);

    if ($email === '' || $password === '') {
        return null;
    }

    $stmt = $pdo->prepare("
        SELECT
            id,
            name,
            email,
            password,
            role_id,
            status
        FROM admins
        WHERE email = :email
        LIMIT 1
    ");

    $stmt->execute([
        ':email' => $email,
    ]);

    $admin = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$admin) {
        return null;
    }


    /*
     * Support common status formats.
     */
    $status = $admin['status'] ?? 0;

    if (
        $status === 0
        || $status === '0'
        || $status === false
    ) {
        return null;
    }


    /*
     * Verify password using PHP password_hash/password_verify.
     */
    if (
        empty($admin['password'])
        || !password_verify($password, (string) $admin['password'])
    ) {
        return null;
    }


    /*
     * Prevent session fixation.
     */
    session_regenerate_id(true);


    /*
     * Store only required session information.
     */
    $_SESSION['admin_logged_in'] = true;
    $_SESSION['admin_id']        = (int) $admin['id'];
    $_SESSION['admin_name']      = trim((string) ($admin['name'] ?? 'Administrator'));
    $_SESSION['admin_email']     = trim((string) ($admin['email'] ?? ''));
    $_SESSION['admin_role_id']   = !empty($admin['role_id'])
        ? (int) $admin['role_id']
        : null;

    $_SESSION['login_time'] = time();


    /*
     * Optional password rehash.
     */
    if (password_needs_rehash(
        (string) $admin['password'],
        PASSWORD_DEFAULT
    )) {

        $newHash = password_hash(
            $password,
            PASSWORD_DEFAULT
        );

        $update = $pdo->prepare("
            UPDATE admins
            SET password = :password
            WHERE id = :id
            LIMIT 1
        ");

        $update->execute([
            ':password' => $newHash,
            ':id'       => (int) $admin['id'],
        ]);
    }


    /*
     * Never return the password hash.
     */
    unset($admin['password']);

    return $admin;
}


/*
|--------------------------------------------------------------------------
| Logout Admin
|--------------------------------------------------------------------------
*/

function logoutAdmin(): void
{
    /*
     * Remove all session variables.
     */
    $_SESSION = [];


    /*
     * Remove session cookie.
     */
    if (ini_get('session.use_cookies')) {

        $params = session_get_cookie_params();

        setcookie(
            session_name(),
            '',
            time() - 42000,
            $params['path'] ?? '/',
            $params['domain'] ?? '',
            (bool) ($params['secure'] ?? false),
            (bool) ($params['httponly'] ?? true)
        );
    }


    /*
     * Destroy current session.
     */
    session_destroy();
}


/*
|--------------------------------------------------------------------------
| Admin Session Timeout
|--------------------------------------------------------------------------
|
| 2 hours of inactivity.
|
*/

function checkAdminSessionTimeout(int $timeout = 7200): void
{
    if (!isAdminLoggedIn()) {
        return;
    }

    $lastActivity = (int) ($_SESSION['last_activity'] ?? time());

    if ((time() - $lastActivity) > $timeout) {

        logoutAdmin();

        header('Location: /admin/login.php?timeout=1');
        exit;
    }

    $_SESSION['last_activity'] = time();
}


/*
|--------------------------------------------------------------------------
| Apply Session Timeout
|--------------------------------------------------------------------------
*/

if (isAdminLoggedIn()) {
    checkAdminSessionTimeout();
}


/*
|--------------------------------------------------------------------------
| Get Full Current Admin
|--------------------------------------------------------------------------
|
| Returns the currently logged-in admin record.
|
*/

function currentAdmin(PDO $pdo): ?array
{
    $id = adminId();

    if ($id === null) {
        return null;
    }

    $stmt = $pdo->prepare("
        SELECT
            id,
            name,
            email,
            role_id,
            status,
            created_at,
            updated_at
        FROM admins
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([
        ':id' => $id,
    ]);

    $admin = $stmt->fetch(PDO::FETCH_ASSOC);

    return $admin ?: null;
}