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

function sessionStart(): void {
    if (session_status() === PHP_SESSION_NONE) {
        ini_set('session.cookie_httponly', '1');
        ini_set('session.use_strict_mode', '1');
        session_set_cookie_params(['samesite' => 'Lax', 'secure' => isset($_SERVER['HTTPS'])]);
        session_start();
    }
}

function requireLogin(): void {
    sessionStart();
    if (empty($_SESSION['user_id'])) {
        header('Location: index.php');
        exit;
    }
    // Verificar expiración de sesión
    if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > SESSION_LIFETIME) {
        session_unset();
        session_destroy();
        header('Location: index.php?expired=1');
        exit;
    }
    $_SESSION['last_activity'] = time();
}

function requireAdmin(): void {
    requireLogin();
    if ($_SESSION['role'] !== 'admin') {
        header('Location: dashboard.php');
        exit;
    }
}

function currentUser(): array {
    return [
        'id'           => $_SESSION['user_id']      ?? 0,
        'username'     => $_SESSION['username']     ?? '',
        'display_name' => $_SESSION['display_name'] ?? '',
        'role'         => $_SESSION['role']          ?? 'client',
        'client_ids'   => $_SESSION['client_ids']   ?? [],
    ];
}

function login(string $username, string $password): bool {
    $pdo  = db();
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND active = 1");
    $stmt->execute([strtolower(trim($username))]);
    $user = $stmt->fetch();

    if (!$user || !password_verify($password, $user['password'])) {
        return false;
    }

    // Cargar client IDs asignados
    $mapStmt = $pdo->prepare("SELECT adguard_client_id FROM client_mapping WHERE user_id = ?");
    $mapStmt->execute([$user['id']]);
    $clientIds = $mapStmt->fetchAll(PDO::FETCH_COLUMN);

    session_regenerate_id(true);
    $_SESSION['user_id']      = $user['id'];
    $_SESSION['username']     = $user['username'];
    $_SESSION['display_name'] = $user['display_name'];
    $_SESSION['role']         = $user['role'];
    $_SESSION['client_ids']   = $clientIds;
    $_SESSION['last_activity']= time();

    $pdo->prepare("UPDATE users SET last_login = NOW() WHERE id = ?")->execute([$user['id']]);
    return true;
}

// Obtener placeholders PDO para array de client IDs
function clientIdPlaceholders(array $ids): string {
    return implode(',', array_fill(0, count($ids), '?'));
}
