<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

require_once '../config/database.php';

try {
    $date = $_GET['date'] ?? null;
    
    if (!$date) {
        throw new Exception('Date parameter is required');
    }
    
    // Validate date format
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
        throw new Exception('Invalid date format. Use YYYY-MM-DD');
    }
    
    // Check if date is in the past
    $requestedDate = new DateTime($date);
    $today = new DateTime();
    $today->setTime(0, 0, 0);
    
    if ($requestedDate < $today) {
        throw new Exception('Cannot book appointments for past dates');
    }
    
    $pdo = getDBConnection();
    
    // Get settings
    $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM settings");
    $stmt->execute();
    $settings = [];
    while ($row = $stmt->fetch()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    
    // Check if system is enabled
    if (empty($settings['system_enabled']) || $settings['system_enabled'] != '1') {
        throw new Exception('Booking system is currently disabled');
    }
    
    // Check advance booking days
    $advanceDays = (int)($settings['advance_booking_days'] ?? 30);
    $maxDate = clone $today;
    $maxDate->add(new DateInterval("P{$advanceDays}D"));
    
    if ($requestedDate > $maxDate) {
        throw new Exception("Bookings are only allowed up to {$advanceDays} days in advance");
    }
    
    // Get start and end times
    $startTime = $settings['start_time'] ?? '09:00';
    $endTime = $settings['end_time'] ?? '18:00';
    $slotDuration = (int)($settings['slot_duration'] ?? 60);
    $slotsPerHour = (int)($settings['slots_per_hour'] ?? 1);
    
    // Get lunch time settings
    $lunchStart = $settings['lunch_start'] ?? '13:00';
    $lunchEnd = $settings['lunch_end'] ?? '14:00';
    
    // Use the actual slot_duration setting instead of calculating from slots_per_hour
    $actualSlotDuration = $slotDuration;
    
    // Debug: Log slot calculation
    error_log("Settings: slot_duration={$slotDuration}, slots_per_hour={$slotsPerHour}");
    error_log("Using actual slot duration: {$actualSlotDuration} minutes");
    
    // Generate time slots excluding lunch time and past times
    $slots = [];
    $currentTime = new DateTime($startTime);
    $endDateTime = new DateTime($endTime);
    
    // Get current time for today (India timezone)
    $now = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
    $currentHour = (int)$now->format('H');
    $currentMinute = (int)$now->format('i');
    
    // Debug: Log current time
    error_log("Current time (IST): {$currentHour}:{$currentMinute}");
    error_log("Requested date: " . $requestedDate->format('Y-m-d'));
    error_log("Today: " . $today->format('Y-m-d'));
    
    while ($currentTime < $endDateTime) {
        $slotStart = $currentTime->format('H:i');
        
        // Add the calculated slot duration
        $currentTime->add(new DateInterval("PT{$actualSlotDuration}M"));
        $slotEnd = $currentTime->format('H:i');
        
        // Skip lunch time slots completely
        if (!($slotStart >= $lunchStart && $slotEnd <= $lunchEnd)) {
            // For today, only show future time slots
            if ($requestedDate->format('Y-m-d') === $today->format('Y-m-d')) {
                $slotHour = (int)explode(':', $slotStart)[0];
                $slotMinute = (int)explode(':', $slotStart)[1];
                
                // Debug: Log slot comparison
                error_log("Checking slot: {$slotStart} - {$slotEnd} (Hour: {$slotHour}, Minute: {$slotMinute})");
                
                // Only show slots that are in the future (current time + 30 minutes buffer)
                $slotTimeInMinutes = ($slotHour * 60) + $slotMinute;
                $currentTimeInMinutes = ($currentHour * 60) + $currentMinute;
                $bufferMinutes = 30; // 30 minutes buffer to allow some preparation time
                
                if ($slotTimeInMinutes > ($currentTimeInMinutes + $bufferMinutes)) {
                    $slots[] = "{$slotStart} - {$slotEnd}";
                    error_log("Slot added: {$slotStart} - {$slotEnd}");
                } else {
                    error_log("Slot skipped (past time or too soon): {$slotStart} - {$slotEnd}");
                }
            } else {
                // For future dates, show all slots
                $slots[] = "{$slotStart} - {$slotEnd}";
                error_log("Slot added (future date): {$slotStart} - {$slotEnd}");
            }
        } else {
            error_log("Slot skipped (lunch time): {$slotStart} - {$slotEnd}");
        }
    }
    
    // Get booked slots for this date
    $stmt = $pdo->prepare("
        SELECT time_slot 
        FROM appointments 
        WHERE appointment_date = ? AND status != 'cancelled'
    ");
    $stmt->execute([$date]);
    $bookedSlots = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Filter out booked slots
    $availableSlots = array_values(array_diff($slots, $bookedSlots));
    
    // Get day of week for pricing
    $dayOfWeek = $requestedDate->format('N'); // 1=Monday, 2=Tuesday, etc.
    
    $price = 0;
    switch ($dayOfWeek) {
        case 2: // Tuesday
            $price = (int)($settings['tuesday_price'] ?? 300);
            break;
        case 6: // Saturday
            $price = (int)($settings['saturday_price'] ?? 300);
            break;
        case 7: // Sunday
            $price = (int)($settings['sunday_price'] ?? 300);
            break;
        default:
            $price = (int)($settings['other_days_price'] ?? 500);
    }
    
    echo json_encode([
        'success' => true,
        'date' => $date,
        'day_of_week' => $requestedDate->format('l'),
        'price' => $price,
        'slots' => $availableSlots,
        'total_slots' => count($slots),
        'available_slots' => count($availableSlots),
        'booked_slots' => count($bookedSlots),
        'debug_info' => [
            'slots_per_hour' => $slotsPerHour,
            'slot_duration' => $slotDuration,
            'actual_slot_duration' => $actualSlotDuration,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'lunch_start' => $lunchStart,
            'lunch_end' => $lunchEnd,
            'total_generated_slots' => count($slots)
        ]
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred'
    ]);
}
?> 