<?php
require_once __DIR__ . '/config.php';

const REMEMBER_COOKIE = 'agh_remember';
const REMEMBER_LIFETIME = 60 * 60 * 24 * 365 * 10; // 10 বছর

function is_https_request() {
    return (
        (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
        (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https')
    );
}

function set_login_session($user) {
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['full_name'] = $user['full_name'];
    $_SESSION['role'] = $user['role'];
}

function create_remember_token($user_id) {
    global $conn;

    $selector = bin2hex(random_bytes(16));
    $token = bin2hex(random_bytes(32));
    $token_hash = password_hash($token, PASSWORD_DEFAULT);
    $expires_at = date('Y-m-d H:i:s', time() + REMEMBER_LIFETIME);

    $stmt = $conn->prepare("
        INSERT INTO agh_remember_tokens (user_id, selector, token_hash, expires_at)
        VALUES (?, ?, ?, ?)
    ");
    $stmt->bind_param("isss", $user_id, $selector, $token_hash, $expires_at);
    $stmt->execute();
    $stmt->close();

    setcookie(REMEMBER_COOKIE, $selector . ':' . $token, [
        'expires' => time() + REMEMBER_LIFETIME,
        'path' => '/',
        'secure' => is_https_request(),
        'httponly' => true,
        'samesite' => 'Lax'
    ]);
}

function restore_login_from_cookie() {
    global $conn;

    if (isset($_SESSION['user_id'])) {
        return true;
    }

    if (empty($_COOKIE[REMEMBER_COOKIE])) {
        return false;
    }

    $parts = explode(':', $_COOKIE[REMEMBER_COOKIE], 2);
    if (count($parts) !== 2) {
        return false;
    }

    [$selector, $token] = $parts;

    $stmt = $conn->prepare("
        SELECT 
            rt.id AS token_id,
            rt.token_hash,
            rt.expires_at,
            u.id,
            u.username,
            u.full_name,
            u.role
        FROM agh_remember_tokens rt
        INNER JOIN agh_users u ON u.id = rt.user_id
        WHERE rt.selector = ?
        LIMIT 1
    ");
    $stmt->bind_param("s", $selector);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();

    if (!$row || strtotime($row['expires_at']) < time() || !password_verify($token, $row['token_hash'])) {
        clear_remember_cookie();
        return false;
    }

    session_regenerate_id(true);
    set_login_session($row);

    return true;
}

function clear_remember_cookie() {
    global $conn;

    if (!empty($_COOKIE[REMEMBER_COOKIE])) {
        $parts = explode(':', $_COOKIE[REMEMBER_COOKIE], 2);
        $selector = $parts[0] ?? '';

        if ($selector !== '') {
            $stmt = $conn->prepare("DELETE FROM agh_remember_tokens WHERE selector = ?");
            $stmt->bind_param("s", $selector);
            $stmt->execute();
            $stmt->close();
        }
    }

    setcookie(REMEMBER_COOKIE, '', [
        'expires' => time() - 3600,
        'path' => '/',
        'secure' => is_https_request(),
        'httponly' => true,
        'samesite' => 'Lax'
    ]);
}

function require_login() {
    if (!restore_login_from_cookie()) {
        header("Location: index.php");
        exit();
    }
}

function require_role($role) {
    restore_login_from_cookie();

    if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== $role) {
        header("Location: ../index.php");
        exit();
    }
}
