<?php
// db/live-business-monitor.php

ob_start();

$skip_auth_check = true; 

// CARGA MAESTRA (La corrección que pediste)
require_once __DIR__ . '/../core/api.php'; 

ob_clean(); 
header('Content-Type: application/json');

try {
    if (empty($_SESSION['user_id'])) {
        throw new Exception('Sesión no válida o expirada');
    }

    $user_id = $_SESSION['user_id'];

    if (!isset($_SESSION['monitor_state'])) {
        $_SESSION['monitor_state'] = [
            'pending_appts' => -1,
            'active_leads' => -1, 
            'staff_online' => -1,
            'last_verification' => '2000-01-01 00:00:00'
        ];
    }
    $last_state = $_SESSION['monitor_state'];

    // ---------------------------------------------------------
    // CONSULTAS OPTIMIZADAS
    // ---------------------------------------------------------

    // 1. Citas Pendientes
    $stmt1 = $pdo->prepare("SELECT COUNT(*) FROM unique_appointments WHERE user_id = ? AND status = 'pending'");
    $stmt1->execute([$user_id]);
    $current_pending = (int)$stmt1->fetchColumn();

    // 2. Leads Activos (Excluyendo los finalizados)
    $stmt2 = $pdo->prepare("
        SELECT COUNT(*) FROM leads 
        WHERE user_id = ? 
        AND status NOT IN ('Contactado', 'Convertido', 'Lead Archivado')
    ");
    $stmt2->execute([$user_id]);
    $current_leads = (int)$stmt2->fetchColumn();

    // 3. Empleados Online
    $stmt3 = $pdo->prepare("
        SELECT COUNT(DISTINCT staff_id) 
        FROM work_logs 
        WHERE clock_out IS NULL 
        AND staff_id IN (SELECT id FROM staff WHERE user_id = ?)
    ");
    $stmt3->execute([$user_id]);
    $current_staff_online = (int)$stmt3->fetchColumn();

    // 4. Última Verificación (Para reseñas/notificaciones)
    $stmt4 = $pdo->prepare("
        SELECT MAX(verified_at) 
        FROM unique_appointments 
        WHERE user_id = ? AND verified_at IS NOT NULL
    ");
    $stmt4->execute([$user_id]);
    $latest_verification = $stmt4->fetchColumn() ?? '2000-01-01 00:00:00';

    // ---------------------------------------------------------
    // DETECCIÓN DE CAMBIOS
    // ---------------------------------------------------------
    $has_changes = false;
    $change_type = [];

    if ($current_pending !== $last_state['pending_appts']) $has_changes = true;
    if ($current_leads !== $last_state['active_leads']) $has_changes = true;
    if ($current_staff_online !== $last_state['staff_online']) $has_changes = true;
    if ($latest_verification > $last_state['last_verification']) $has_changes = true;

    // ---------------------------------------------------------
    // ACTUALIZACIÓN Y OPTIMIZACIÓN DE SESIÓN
    // ---------------------------------------------------------
    if ($has_changes) {
        $_SESSION['monitor_state'] = [
            'pending_appts' => $current_pending,
            'active_leads' => $current_leads,
            'staff_online' => $current_staff_online,
            'last_verification' => $latest_verification
        ];
    }

    session_write_close();

    echo json_encode([
        'success' => true,
        'has_changes' => $has_changes,
        'changes' => $has_changes ? ['update_detected'] : [] 
    ]);

} catch (Exception $e) {
    http_response_code(500);
    error_log("Monitor Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Error de monitoreo']);
}
?>