<?php
// staff/staff-portal-read.php

// 1. Configuración de cabeceras y manejo de errores
header('Content-Type: application/json; charset=utf-8');
ini_set('display_errors', 0); // En producción no mostramos errores en el HTML
ini_set('log_errors', 1);
// Asegúrate de que esta ruta de log exista y tenga permisos
ini_set('error_log', __DIR__ . '/../logs/php_errors.log'); 

// Iniciamos buffer para capturar cualquier salida inesperada (warnings, notices)
ob_start();

try {
    session_start();

    // 2. Validación de Sesión Estricta
    if (!isset($_SESSION['staff_id'])) {
        throw new Exception("Sesión no válida o expirada.", 401);
    }

    // 3. Inclusión de la Conexión (Centralizada)
    // Usamos require_once apuntando directamente a la conexión PDO
    $db_path = __DIR__ . '/../db/db_connection.php';
    
    if (!file_exists($db_path)) {
        throw new Exception("Error crítico: Archivo de conexión no encontrado.");
    }
    require_once $db_path;

    // Verificamos que la variable $pdo exista tras el include
    if (!isset($pdo)) {
        throw new Exception("Error crítico: La conexión PDO no se inicializó correctamente.");
    }

    // 4. Lógica de Negocio
    $staff_id = (int)$_SESSION['staff_id'];
    $action = $_GET['action'] ?? '';
    $response = ['success' => true];

    // --- A. AGENDA (Citas futuras) ---
    if ($action === 'agenda') {
        // Optimizamos la query para traer solo lo necesario
        $stmt = $pdo->prepare("
            SELECT 
                ua.id, 
                ua.appointment_date, 
                TIME_FORMAT(ua.appointment_time, '%h:%i %p') as appointment_time, -- Formato legible
                ua.status, 
                c.first_name, 
                c.last_name, 
                c.street_address, 
                c.city
            FROM unique_appointments ua
            INNER JOIN clients c ON ua.client_id = c.id
            WHERE ua.staff_id = :staff_id
            AND ua.status IN ('pending', 'confirmed') 
            AND ua.appointment_date >= CURDATE()
            ORDER BY ua.appointment_date ASC, ua.appointment_time ASC
        ");
        $stmt->execute([':staff_id' => $staff_id]);
        $response['assigned_appointments'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // --- B. QUEJAS (Clientes asignados) ---
    elseif ($action === 'complaints') {
        $stmt = $pdo->prepare("
            SELECT 
                cp.id, cp.title, cp.description, cp.status, 
                DATE_FORMAT(cp.created_at, '%Y-%m-%d') as created_at,
                c.first_name, c.last_name
            FROM complaints cp
            INNER JOIN clients c ON cp.client_id = c.id
            WHERE c.staff_id = :staff_id
            AND cp.status != 'Archivado'
            ORDER BY cp.created_at DESC
        ");
        $stmt->execute([':staff_id' => $staff_id]);
        $response['complaints'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // --- C. ACADEMIA (Videos y Docs) ---
    elseif ($action === 'academy') {
        // Helper simple para YouTube
        function getYoutubeIdInternal($url) {
            preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i', $url, $matches);
            return $matches[1] ?? null;
        }

        // Videos (Globales o específicos)
        $stmtV = $pdo->prepare("
            SELECT id, title, youtube_url, created_at 
            FROM staff_academy 
            WHERE staff_id = :staff_id OR staff_id IS NULL 
            ORDER BY created_at DESC
        ");
        $stmtV->execute([':staff_id' => $staff_id]);
        $videos = $stmtV->fetchAll(PDO::FETCH_ASSOC);
        
        foreach($videos as &$v) { 
            $v['youtube_id'] = getYoutubeIdInternal($v['youtube_url']); 
        }
        $response['videos'] = $videos;

        // Documentos
        $stmtD = $pdo->prepare("
            SELECT id, file_name, file_path, uploaded_at 
            FROM staff_documents 
            WHERE staff_id = :staff_id OR staff_id IS NULL 
            ORDER BY uploaded_at DESC
        ");
        $stmtD->execute([':staff_id' => $staff_id]);
        $response['documents'] = $stmtD->fetchAll(PDO::FETCH_ASSOC);
    }
    else {
        throw new Exception("Acción no válida: " . htmlspecialchars($action));
    }

    // Limpiamos el buffer antes de enviar JSON limpio
    ob_clean();
    echo json_encode($response);

} catch (Exception $e) {
    // Captura de errores controlada
    ob_clean(); // Borramos cualquier salida HTML basura
    http_response_code($e->getCode() && is_int($e->getCode()) ? $e->getCode() : 500);
    echo json_encode([
        'success' => false, 
        'message' => $e->getMessage()
    ]);
}
exit;
?>