<?php
require_once '../includes/config.php';
require_once '../includes/auth.php';

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

// Check if counselor ID is provided
$counselor_id = $_GET['counselor'] ?? null;
if (!$counselor_id) {
    http_response_code(400);
    echo json_encode(['error' => 'Counselor ID required']);
    exit();
}

try {
    // Get appointments for FullCalendar
    $stmt = $pdo->prepare("
        SELECT 
            a.id,
            CONCAT(s.first_name, ' ', s.last_name) AS title,
            a.scheduled_time AS start,
            DATE_ADD(a.scheduled_time, INTERVAL a.duration_minutes MINUTE) AS end,
            a.appointment_type,
            CASE 
                WHEN a.status = 'scheduled' THEN '#3788d8'
                WHEN a.status = 'completed' THEN '#28a745'
                ELSE '#ffc107'
            END AS color
        FROM appointments a
        JOIN students s ON a.student_id = s.id
        WHERE a.counselor_id = ?
        AND a.scheduled_time BETWEEN ? AND ?
    ");
    
    // Get start/end dates from FullCalendar request
    $start = $_GET['start'] ?? date('Y-m-01');
    $end = $_GET['end'] ?? date('Y-m-t');
    
    $stmt->execute([$counselor_id, $start, $end]);
    $appointments = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode($appointments);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
?>