<?php
// ─── AVI CRM — Autenticación ───────────────────────────────────
require_once __DIR__ . '/config.php';

ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);
ini_set('session.gc_maxlifetime', SESSION_LIFETIME);
session_name(SESSION_NAME);
if (session_status() === PHP_SESSION_NONE) session_start();

function isLoggedIn(): bool {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

function requireLogin(): void {
    if (!isLoggedIn()) {
        header('Location: ' . APP_URL . '/index.php');
        exit;
    }
}

function currentUser(): array {
    return [
        'id'     => $_SESSION['user_id']    ?? 0,
        'nombre' => $_SESSION['user_nombre'] ?? '',
        'email'  => $_SESSION['user_email']  ?? '',
        'rol'    => $_SESSION['user_rol']    ?? 'asesor',
    ];
}

function login(string $email, string $password): bool {
    $db   = getDB();
    $stmt = $db->prepare("SELECT * FROM dimark_usuarios WHERE email = ? AND activo = 1 LIMIT 1");
    $stmt->execute([trim($email)]);
    $user = $stmt->fetch();
    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id']     = $user['id'];
        $_SESSION['user_nombre'] = $user['nombre'];
        $_SESSION['user_email']  = $user['email'];
        $_SESSION['user_rol']    = $user['rol'];
        return true;
    }
    return false;
}

function logout(): void {
    session_unset();
    session_destroy();
    header('Location: ' . APP_URL . '/index.php');
    exit;
}

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

function csrf_token(): string {
    if (empty($_SESSION['_csrf'])) {
        $_SESSION['_csrf'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['_csrf'];
}

function csrf_check(): void {
    $t = $_POST['_csrf'] ?? '';
    if (!$t || !hash_equals($_SESSION['_csrf'] ?? '', $t)) {
        http_response_code(403);
        exit('Solicitud inválida. Recarga la página e intenta de nuevo.');
    }
}

function getMetas($db): array {
    static $cache = null;
    if ($cache !== null) return $cache;
    $defaults = [
        'rampa_2026_06' => 4,  'rampa_2026_07' => 5,  'rampa_2026_08' => 6,
        'rampa_2026_09' => 7,  'rampa_2026_10' => 8,
        'sector_ecommerce' => 6, 'sector_clinicas' => 5, 'sector_b2b' => 4,
        'sector_inmobiliarias' => 4, 'sector_hoteles' => 3,
        'sector_restaurantes' => 3, 'sector_educacion' => 3, 'sector_retail' => 2,
        'kpi_resp_rate' => 20, 'kpi_conv_demo' => 25,
        'kpi_demos_semana_min' => 3, 'kpi_demos_semana_max' => 5,
        'kpi_prospectos_dia' => 40,
        'sema_amarillo' => 80, 'meta_total' => 30, 'mrr_objetivo' => 37000,
    ];
    try {
        $rows = $db->query("SELECT clave, valor FROM dimark_config_metas")->fetchAll(PDO::FETCH_KEY_PAIR);
        $cache = array_merge($defaults, array_map('intval', $rows));
    } catch (Exception $e) {
        $cache = $defaults;
    }
    return $cache;
}
