<?php
session_start();
header('Content-Type: application/json');

include '../layouts/dbconn.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit();
}

$response = [];

try {
    // Get parameters
    $doctor_id = isset($_POST['doctor_id']) ? (int)$_POST['doctor_id'] : 0;
    $days = isset($_POST['days']) ? (int)$_POST['days'] : 14;
    
    // Validate doctor_id
    if (!$doctor_id) {
        throw new Exception('Doctor ID is required');
    }
    
    // Limit days to reasonable range
    $days = min(max($days, 7), 30);
    
    // Get doctor's max daily appointments
    $doctor_sql = "SELECT 
                      d.max_daily_appointments,
                      d.availability_schedule,
                      u.full_name
                   FROM doctors d
                   JOIN users u ON d.user_id = u.user_id
                   WHERE d.doctor_id = ? AND d.is_active = 1";
    
    $stmt = $conn->prepare($doctor_sql);
    if (!$stmt) {
        throw new Exception('Failed to prepare statement: ' . $conn->error);
    }
    
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $doctor_result = $stmt->get_result();
    $doctor = $doctor_result->fetch_assoc();
    
    if (!$doctor) {
        throw new Exception('Doctor not found or inactive');
    }
    
    $max_appointments = (int)$doctor['max_daily_appointments'];
    
    // Parse availability schedule (JSON format)
    $availability_schedule = json_decode($doctor['availability_schedule'], true);
    
    // Default schedule if not set (Monday to Saturday)
    if (!$availability_schedule) {
        $availability_schedule = [
            'Monday' => ['available' => true],
            'Tuesday' => ['available' => true],
            'Wednesday' => ['available' => true],
            'Thursday' => ['available' => true],
            'Friday' => ['available' => true],
            'Saturday' => ['available' => true],
            'Sunday' => ['available' => false]
        ];
    }
    
    // Get current date
    $current_date = new DateTime();
    
    // Loop through the requested number of days
    for ($i = 0; $i < $days; $i++) {
        $check_date = clone $current_date;
        $check_date->modify("+{$i} days");
        
        $date_str = $check_date->format('Y-m-d');
        $day_name = $check_date->format('l'); // Full day name (Monday, Tuesday, etc.)
        $day_short = $check_date->format('D'); // Short day name (Mon, Tue, etc.)
        $date_formatted = $check_date->format('M d'); // Format: Jan 15
        
        // Check if doctor is available on this day
        $is_day_available = isset($availability_schedule[$day_name]) && 
                           isset($availability_schedule[$day_name]['available']) &&
                           $availability_schedule[$day_name]['available'] === true;
        
        // Skip if doctor is not available on this day
        if (!$is_day_available) {
            $response[] = [
                'date' => $date_str,
                'day_name' => $day_short,
                'date_formatted' => $date_formatted,
                'available_slots' => 0,
                'booked_slots' => 0,
                'total_capacity' => 0,
                'is_working_day' => false
            ];
            continue;
        }
        
        // Count booked appointments for this date
        // Using appointment_date field from appointments table
        $booked_sql = "SELECT COUNT(*) as booked
                      FROM appointments
                      WHERE doctor_id = ?
                      AND appointment_date = ?
                      AND status NOT IN ('CANCELLED', 'NO_SHOW')";
        
        $stmt = $conn->prepare($booked_sql);
        if (!$stmt) {
            throw new Exception('Failed to prepare booked statement: ' . $conn->error);
        }
        
        $stmt->bind_param("is", $doctor_id, $date_str);
        $stmt->execute();
        $booked_result = $stmt->get_result();
        $booked_data = $booked_result->fetch_assoc();
        
        $booked_slots = (int)$booked_data['booked'];
        $available_slots = max(0, $max_appointments - $booked_slots);
        
        // Add to response
        $response[] = [
            'date' => $date_str,
            'day_name' => $day_short,
            'date_formatted' => $date_formatted,
            'available_slots' => $available_slots,
            'booked_slots' => $booked_slots,
            'total_capacity' => $max_appointments,
            'is_working_day' => true
        ];
    }
    
    // Add success flag
    $response = [
        'success' => true,
        'doctor_name' => $doctor['full_name'],
        'days' => $response
    ];
    
} catch (Exception $e) {
    error_log("Get availability calendar error: " . $e->getMessage());
    $response = [
        'success' => false,
        'error' => $e->getMessage(),
        'days' => []
    ];
}

// Close connection
if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}

// Return JSON response
echo json_encode($response);
exit();
?>