<?php
// schedule-search.php
// Objetivo: Buscador operativo (Citas, Tareas y Proyectos).

header('Content-Type: application/json; charset=utf-8');
ini_set('display_errors', 0);
error_reporting(E_ALL);

// 1. Seguridad
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// 2. Conexión BD Centralizada
require_once __DIR__ . '/../core/api.php';

$user_id = $_SESSION['user_id'] ?? null;
$q = isset($_GET['q']) ? trim($_GET['q']) : '';

if (!$user_id || strlen($q) < 1) {
    echo json_encode([]);
    exit;
}

// Verificar que $pdo esté disponible desde api.php
if (!isset($pdo)) {
    echo json_encode(['status' => 'error', 'message' => 'Error: Conexión a DB no disponible.']);
    exit;
}

try {
    $pdo->exec("SET NAMES 'utf8mb4'");
    $term = "%" . $q . "%";
    
    // NOTA: Usamos CONCAT para formatear fechas y horas en un solo string legible
    
    $sql = "
        /* 1. BUSCAR EN CITAS (unique_appointments) */
        (SELECT 
            ua.id, 
            'Cita' as type,
            /* Si hay nota, la usamos como título, si no, genérico */
            CASE 
                WHEN ua.notes IS NOT NULL AND ua.notes != '' THEN ua.notes 
                ELSE 'Cita Agendada' 
            END as title,
            /* Formatear Fecha y Hora */
            CONCAT(ua.appointment_date, ' ', ua.appointment_time) as date_val,
            ua.status,
            /* Obtener nombre de Cliente o Lead */
            COALESCE(
                CONCAT(c.first_name, ' ', c.last_name), 
                CONCAT(l.first_name, ' ', l.last_name),
                'Sin Asignar'
            ) as client_name
         FROM unique_appointments ua
         LEFT JOIN clients c ON ua.client_id = c.id
         LEFT JOIN leads l ON ua.lead_id = l.id
         WHERE ua.user_id = :uid1
         AND (
            ua.notes LIKE :term1 OR 
            c.first_name LIKE :term2 OR 
            l.first_name LIKE :term3
         )
         LIMIT 5)

        UNION ALL

        /* 2. BUSCAR EN TAREAS (Tasks) */
        (SELECT 
            t.id, 
            'Tarea' as type,
            t.title as title,
            CONCAT(t.due_date, ' (Vence)') as date_val,
            t.priority as status, /* En tareas mostramos prioridad como estado visual */
            COALESCE(
                CONCAT(c.first_name, ' ', c.last_name), 
                t.client_name, 
                'General'
            ) as client_name
         FROM tasks t
         LEFT JOIN clients c ON t.client_id = c.id
         WHERE t.user_id = :uid2
         AND (
            t.title LIKE :term4 OR 
            t.description LIKE :term5 OR
            c.first_name LIKE :term6
         )
         LIMIT 5)

        UNION ALL

        /* 3. BUSCAR EN PROYECTOS (Projects) */
        (SELECT 
            p.id, 
            'Proyecto' as type,
            p.name as title,
            CONCAT(p.start_date, ' - ', IFNULL(p.due_date, '?')) as date_val,
            p.status,
            CONCAT(c.first_name, ' ', c.last_name) as client_name
         FROM projects p
         LEFT JOIN clients c ON p.client_id = c.id
         WHERE p.user_id = :uid3
         AND (
            p.name LIKE :term7 OR 
            p.description LIKE :term8 OR
            c.first_name LIKE :term9
         )
         LIMIT 5)
         
         ORDER BY date_val DESC
    ";
    
    $stmt = $pdo->prepare($sql);
    
    $params = [
        // Params Citas
        ':uid1' => $user_id,
        ':term1' => $term, ':term2' => $term, ':term3' => $term,
        
        // Params Tareas
        ':uid2' => $user_id,
        ':term4' => $term, ':term5' => $term, ':term6' => $term,
        
        // Params Proyectos
        ':uid3' => $user_id,
        ':term7' => $term, ':term8' => $term, ':term9' => $term
    ];
    
    $stmt->execute($params);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Formateo FrontEnd
    $finalResponse = [];
    foreach($results as $row) {
        
        // URLs de destino (Ajusta según tus archivos reales)
        $url = '#';
        if ($row['type'] === 'Cita') $url = 'calendar.php?event_id=' . $row['id'];
        if ($row['type'] === 'Tarea') $url = 'tasks.php?task_id=' . $row['id'];
        if ($row['type'] === 'Proyecto') $url = 'project-details.php?id=' . $row['id'];

        // Colores de estado (Opcional, para CSS en frontend)
        $statusColor = 'gray';
        if (in_array($row['status'], ['completed', 'pagada', 'confirmed', 'approved', 'converted'])) $statusColor = 'green';
        if (in_array($row['status'], ['pending', 'Alta', 'Aprobado', 'sent', 'generada'])) $statusColor = 'orange';
        if (in_array($row['status'], ['cancelled', 'Baja', 'Archivado', 'rejected'])) $statusColor = 'red';

        $finalResponse[] = [
            'id' => $row['id'],
            'type' => $row['type'],         // Cita, Tarea, Proyecto
            'title' => $row['title'],       // "Llamar a Juan", "Diseño Web", etc.
            'date' => $row['date_val'],     // Fecha legible
            'status' => ucfirst($row['status']),
            'status_color' => $statusColor, // Ayuda al frontend a pintar bolitas de color
            'client' => $row['client_name'],
            'url' => $url
        ];
    }
    
    echo json_encode($finalResponse);

} catch (Exception $e) {
    error_log("General Error en schedule-search.php: " . $e->getMessage());
    echo json_encode([]);
}
?>