<?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');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

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 {
    $pdo = getDBConnection();
    
    // Get settings including working days
    $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('start_time', 'end_time', 'lunch_start', 'lunch_end', 'advance_booking_days', 'monday_booking', 'tuesday_booking', 'wednesday_booking', 'thursday_booking', 'friday_booking', 'saturday_booking', 'sunday_booking')");
    $stmt->execute();
    $settings = [];
    while ($row = $stmt->fetch()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    
    $startTime = $settings['start_time'] ?? '09:00';
    $endTime = $settings['end_time'] ?? '18:00';
    $lunchStart = $settings['lunch_start'] ?? '13:00';
    $lunchEnd = $settings['lunch_end'] ?? '14:00';
    $advanceDays = (int)($settings['advance_booking_days'] ?? 30);
    
    // Get working days configuration
    $workingDays = [
        'monday' => ($settings['monday_booking'] ?? 'off') === 'on',
        'tuesday' => ($settings['tuesday_booking'] ?? 'off') === 'on',
        'wednesday' => ($settings['wednesday_booking'] ?? 'off') === 'on',
        'thursday' => ($settings['thursday_booking'] ?? 'off') === 'on',
        'friday' => ($settings['friday_booking'] ?? 'off') === 'on',
        'saturday' => ($settings['saturday_booking'] ?? 'off') === 'on',
        'sunday' => ($settings['sunday_booking'] ?? 'off') === 'on'
    ];
    
    // Get current date
    $today = new DateTime();
    $today->setTime(0, 0, 0);
    
    // Get max date (today + advance days)
    $maxDate = clone $today;
    $maxDate->add(new DateInterval("P{$advanceDays}D"));
    
    $availableDates = [];
    $currentDate = clone $today;
    
    // Generate dates for next 30 days
    while ($currentDate <= $maxDate) {
        $dateStr = $currentDate->format('Y-m-d');
        $dayOfWeek = $currentDate->format('N'); // 1=Monday, 7=Sunday
        
        // Check if it's a day off
        $stmt = $pdo->prepare("SELECT id FROM day_off WHERE date = ?");
        $stmt->execute([$dateStr]);
        $isDayOff = $stmt->fetch();
        
        // Check if this day is enabled for booking
        $dayName = strtolower($currentDate->format('l'));
        $isWorkingDay = $workingDays[$dayName] ?? false;
        
        // Debug: Log each day's status
        error_log("Date: {$dateStr}, Day: {$dayName}, Working: " . ($isWorkingDay ? 'YES' : 'NO') . ", DayOff: " . ($isDayOff ? 'YES' : 'NO'));
        
        if (!$isDayOff && $isWorkingDay) {
            // Check if there are any available slots for this date (excluding lunch time)
            $stmt = $pdo->prepare("
                SELECT COUNT(*) as available_slots
                FROM available_slots 
                WHERE is_active = 1
                AND slot_time NOT BETWEEN ? AND ?
                AND slot_time NOT IN (
                    SELECT slot_time FROM slot_off 
                    WHERE date = ? 
                    AND slot_time BETWEEN ? AND ?
                )
            ");
            $stmt->execute([$lunchStart, $lunchEnd, $dateStr, $startTime, $endTime]);
            $availableSlots = (int)$stmt->fetchColumn();
            
            if ($availableSlots > 0) {
                $availableDates[] = [
                    'date' => $dateStr,
                    'day_name' => $currentDate->format('l'),
                    'available_slots' => $availableSlots,
                    'is_office_day' => $isWorkingDay
                ];
            }
        }
        
        $currentDate->add(new DateInterval('P1D'));
    }
    
    // Debug: Log working days configuration
    error_log("Working days configuration: " . json_encode($workingDays));
    error_log("Available dates found: " . count($availableDates));
    
    echo json_encode([
        'success' => true,
        'available_dates' => $availableDates,
        'total_dates' => count($availableDates),
        'working_days' => $workingDays,
        'settings' => [
            'start_time' => $startTime,
            'end_time' => $endTime,
            'lunch_start' => $lunchStart,
            'lunch_end' => $lunchEnd,
            'advance_booking_days' => $advanceDays
        ],
        'timestamp' => time(), // Force refresh
        'debug_info' => 'Available dates updated at ' . date('Y-m-d H:i:s')
    ]);
    
} 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'
    ]);
}
?> 