<?php
// db/live-monitor-data.php
header('Content-Type: application/json');
require_once __DIR__ . '/../core/api.php';

$timezone_db = 'America/Los_Angeles'; 
date_default_timezone_set($timezone_db);

try {
    $stmtStaff = $pdo->query("SELECT id, first_name, last_name, job_title, profile_photo_url, phone FROM staff WHERE status='active' ORDER BY first_name ASC");
    $staffList = $stmtStaff->fetchAll(PDO::FETCH_ASSOC);

    $monitorData = [];

    foreach ($staffList as $staff) {
        $staffId = $staff['id'];
        
        // A. Verificar si está CLOCKED IN (En turno)
        $stmtClock = $pdo->prepare("SELECT clock_in, TIMESTAMPDIFF(HOUR, clock_in, NOW()) as hours_working FROM work_logs WHERE staff_id = ? AND clock_out IS NULL ORDER BY id DESC LIMIT 1");
        $stmtClock->execute([$staffId]);
        $clockData = $stmtClock->fetch(PDO::FETCH_ASSOC);
        
        $isOnline = (bool)$clockData;
        $status = $isOnline ? 'online' : 'offline';
        
        // B. Buscar Actividad Actual (Cita de Hoy)
        
        $today = date('Y-m-d');
        
        $sqlAppt = "SELECT ua.*, 
                           c.first_name as c_fname, c.last_name as c_lname, c.street_address, c.city,
                           s.name as service_name
                    FROM unique_appointments ua
                    JOIN clients c ON ua.client_id = c.id
                    LEFT JOIN services s ON ua.service_id = s.id
                    WHERE ua.staff_id = ? AND ua.appointment_date = ?
                    ORDER BY 
                        CASE WHEN ua.status = 'completed' THEN 1 ELSE 2 END, 
                        ua.appointment_time ASC";
                        
        $stmtAppt = $pdo->prepare($sqlAppt);
        $stmtAppt->execute([$staffId, $today]);
        $appointments = $stmtAppt->fetchAll(PDO::FETCH_ASSOC);
        
        $currentActivity = null;
        
        if (!empty($appointments)) {
            foreach ($appointments as $appt) {
                $apptTime = strtotime($today . ' ' . $appt['appointment_time']);
                $now = time();
                $diffMin = ($now - $apptTime) / 60;
                
                if ($appt['status'] === 'completed') {
                    $currentActivity = [
                        'type' => 'completed',
                        'client' => $appt['c_fname'] . ' ' . $appt['c_lname'],
                        'address' => $appt['street_address'],
                        'service' => $appt['service_name'] ?? 'Servicio General',
                        'time' => date('h:i A', strtotime($appt['appointment_time'])),
                        'rating' => $appt['client_rating'],
                        'verified_at' => $appt['verified_at'] ? date('h:i A', strtotime($appt['verified_at'])) : 'Recién',
                        'feedback' => $appt['client_feedback']
                    ];
                    if ($diffMin < 120) break; 
                }
                
                if ($appt['status'] === 'confirmed' || $appt['status'] === 'pending') {
                    $currentActivity = [
                        'type' => 'working',
                        'client' => $appt['c_fname'] . ' ' . $appt['c_lname'],
                        'address' => $appt['street_address'],
                        'service' => $appt['service_name'] ?? 'Servicio Estándar',
                        'time' => date('h:i A', strtotime($appt['appointment_time'])),
                        'is_late' => ($diffMin > 30) 
                    ];
                    break; 
                }
            }
        }

        $monitorData[] = [
            'id' => $staff['id'],
            'name' => $staff['first_name'] . ' ' . $staff['last_name'],
            'role' => $staff['job_title'],
            'photo' => !empty($staff['profile_photo_url']) ? $staff['profile_photo_url'] : 'img/default-avatar.png',
            'status' => $status,
            'clock_in_time' => $isOnline ? date('h:i A', strtotime($clockData['clock_in'])) : null,
            'activity' => $currentActivity
        ];
    }

    echo json_encode(['success' => true, 'data' => $monitorData, 'timestamp' => date('H:i:s')]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>