<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../core/api.php'; 

$user_id = $_SESSION['user_id'] ?? 1;
$id = $_GET['id'] ?? null;

if (!$id) { echo json_encode(['error' => 'No ID']); exit; }

$response = [];

try {
    $stmt = $pdo->prepare("SELECT * FROM staff WHERE id = ? AND user_id = ?");
    $stmt->execute([$id, $user_id]);
    $staff = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$staff) { throw new Exception("Empleado no encontrado"); }

    $horario = "No definido";
    if ($staff['schedule_config']) {
        $json = json_decode($staff['schedule_config'], true);
        if ($json) {
            foreach($json as $day => $h) {
                if(!empty($h['active']) && $h['active'] === true) {
                    $start = date("g:i A", strtotime($h['start']));
                    $end = date("g:i A", strtotime($h['end']));
                    $horario = "$start - $end";
                    break;
                }
            }
        }
    }

    $response['profile'] = [
        'full_name' => $staff['first_name'] . ' ' . $staff['last_name'],
        'job_title' => $staff['job_title'],
        'email' => $staff['email'],
        'phone' => $staff['phone'],
        'working_days' => $staff['working_days'] ?? 'Lunes - Viernes',
        'schedule' => $horario,
        'status' => $staff['status'],
        'access_code' => $staff['access_code'],
        'employee_code' => $staff['public_uid'],
        'hired_date' => $staff['hired_date'],
        'photo' => $staff['profile_photo_url']
    ];

    $stmtAwards = $pdo->prepare("SELECT COUNT(*) FROM staff_awards WHERE staff_id = ?");
    $stmtAwards->execute([$id]);
    $response['awards_count'] = $stmtAwards->fetchColumn();

    $stmtLogs = $pdo->prepare("SELECT SUM(total_hours) FROM work_logs WHERE staff_id = ?");
    $stmtLogs->execute([$id]);
    $totalHours = $stmtLogs->fetchColumn() ?? 0;
    $rate = $staff['hourly_rate'] ?? 0;
    
    $response['financials'] = [
        'salary' => number_format((float)$rate, 2),
        'hours_worked' => number_format((float)$totalHours, 2),
        'earnings' => number_format((float)$totalHours * $rate, 2)
    ];

    $stmtRoutes = $pdo->prepare("SELECT route_name, route_day FROM routes WHERE (staff_id = ? OR assigned_staff_id = ?) AND is_active = 1 LIMIT 1");
    $stmtRoutes->execute([$id, $id]);
    $response['route_info'] = $stmtRoutes->fetch(PDO::FETCH_ASSOC);

    $stmtClients = $pdo->prepare("SELECT first_name, last_name, company, street_address FROM clients WHERE staff_id = ? AND user_id = ?");
    $stmtClients->execute([$id, $user_id]);
    $response['clients'] = $stmtClients->fetchAll(PDO::FETCH_ASSOC);

    $stmtDocs = $pdo->prepare("SELECT file_name, uploaded_at FROM staff_documents WHERE staff_id = ? ORDER BY uploaded_at DESC");
    $stmtDocs->execute([$id]);
    $response['documents'] = $stmtDocs->fetchAll(PDO::FETCH_ASSOC);

    $stmtVids = $pdo->prepare("SELECT title, created_at FROM staff_academy WHERE staff_id = ? ORDER BY created_at DESC");
    $stmtVids->execute([$id]);
    $response['videos'] = $stmtVids->fetchAll(PDO::FETCH_ASSOC);

    $stmtAppt = $pdo->prepare("
        SELECT ua.appointment_date, ua.appointment_time, ua.status, ua.notes, 
               c.first_name, c.last_name, c.company
        FROM unique_appointments ua
        LEFT JOIN clients c ON ua.client_id = c.id
        WHERE ua.staff_id = ? 
        ORDER BY ua.appointment_date DESC LIMIT 15
    ");
    $stmtAppt->execute([$id]);
    $rawAppts = $stmtAppt->fetchAll(PDO::FETCH_ASSOC);
    $response['appointments'] = [];
    foreach($rawAppts as $a) {
        $name = trim(($a['first_name']??'') . ' ' . ($a['last_name']??''));
        if(empty($name)) $name = $a['company'] ?? 'Cliente sin nombre';
        $a['client_name'] = $name;
        $response['appointments'][] = $a;
    }

    $stmtReviews = $pdo->prepare("SELECT client_rating, client_feedback, appointment_date FROM unique_appointments WHERE staff_id = ? AND status = 'completed' AND client_rating > 0 ORDER BY appointment_date DESC");
    $stmtReviews->execute([$id]);
    $response['reviews'] = $stmtReviews->fetchAll(PDO::FETCH_ASSOC);

    $avg = 0;
    if (count($response['reviews']) > 0) {
        $avg = array_sum(array_column($response['reviews'], 'client_rating')) / count($response['reviews']);
    }
    $response['rating_avg'] = number_format($avg, 1);

    $response['complaints'] = [];
    $stmtClientIds = $pdo->prepare("SELECT id FROM clients WHERE staff_id = ?");
    $stmtClientIds->execute([$id]);
    $cIds = $stmtClientIds->fetchAll(PDO::FETCH_COLUMN);
    
    if (!empty($cIds)) {
        $placeholders = str_repeat('?,', count($cIds) - 1) . '?';
        $stmtComp = $pdo->prepare("SELECT title, status, created_at FROM complaints WHERE client_id IN ($placeholders) ORDER BY created_at DESC");
        $stmtComp->execute($cIds);
        $response['complaints'] = $stmtComp->fetchAll(PDO::FETCH_ASSOC);
    }

    echo json_encode($response);

} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>