<?php
// auth.php — manejo de sesión y autenticación

if (session_status() === PHP_SESSION_NONE) {
    session_start([
        'cookie_httponly' => true,
        'cookie_samesite' => 'Strict',
        'use_strict_mode' => true,
    ]);
}

require_once __DIR__ . '/db.php';

// ——— helpers ———

function dm_logged_in(): bool {
    return !empty($_SESSION['dm_user_id']);
}

function dm_is_admin(): bool {
    return ($_SESSION['dm_role'] ?? '') === 'admin';
}

function dm_user(): array {
    return [
        'id'    => $_SESSION['dm_user_id']   ?? 0,
        'name'  => $_SESSION['dm_name']      ?? '',
        'email' => $_SESSION['dm_email']     ?? '',
        'role'  => $_SESSION['dm_role']      ?? '',
        'color' => $_SESSION['dm_color']     ?? '#E8272A',
    ];
}

function dm_require_login(string $redirect = 'login.php'): void {
    if (!dm_logged_in()) {
        header('Location: ' . $redirect);
        exit;
    }
}

function dm_require_admin(string $redirect = 'index.php'): void {
    dm_require_login();
    if (!dm_is_admin()) {
        header('Location: ' . $redirect);
        exit;
    }
}

function dm_login(string $email, string $password): array {
    global $pdo;
    if (!$pdo) return ['ok' => false, 'error' => 'Sin conexión a base de datos. Configura primero en setup.php.'];

    $stmt = $pdo->prepare('SELECT * FROM dm_users WHERE email = ? AND active = 1 LIMIT 1');
    $stmt->execute([strtolower(trim($email))]);
    $user = $stmt->fetch();

    if (!$user || !password_verify($password, $user['password'])) {
        return ['ok' => false, 'error' => 'Email o contraseña incorrectos.'];
    }

    // Regenerar ID de sesión por seguridad
    session_regenerate_id(true);

    $_SESSION['dm_user_id'] = $user['id'];
    $_SESSION['dm_name']    = $user['name'];
    $_SESSION['dm_email']   = $user['email'];
    $_SESSION['dm_role']    = $user['role'];
    $_SESSION['dm_color']   = $user['avatar_color'];

    // Registrar último login
    $pdo->prepare('UPDATE dm_users SET last_login = NOW() WHERE id = ?')->execute([$user['id']]);

    // Log
    dm_log($user['id'], null, 'login', 'Inicio de sesión');

    return ['ok' => true, 'role' => $user['role']];
}

function dm_logout(): void {
    if (dm_logged_in()) dm_log($_SESSION['dm_user_id'], null, 'logout', 'Cierre de sesión');
    session_destroy();
    header('Location: login.php');
    exit;
}

function dm_log(int $user_id, ?int $client_id, string $action, string $detail = ''): void {
    global $pdo;
    if (!$pdo) return;
    try {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '';
        $pdo->prepare('INSERT INTO dm_activity (user_id,client_id,action,detail,ip) VALUES (?,?,?,?,?)')
            ->execute([$user_id, $client_id, $action, $detail, $ip]);
    } catch (Exception $e) { /* silencioso */ }
}

// ——— Obtener clientes accesibles para el usuario actual ———
function dm_get_clients(): array {
    global $pdo;
    if (!$pdo) return [];
    $user = dm_user();
    if ($user['role'] === 'admin') {
        return $pdo->query('SELECT * FROM dm_clients WHERE active=1 ORDER BY name')->fetchAll();
    }
    $stmt = $pdo->prepare(
        'SELECT c.* FROM dm_clients c
         JOIN dm_user_clients uc ON uc.client_id = c.id
         WHERE uc.user_id = ? AND c.active = 1
         ORDER BY c.name'
    );
    $stmt->execute([$user['id']]);
    return $stmt->fetchAll();
}
