<?php
session_start();
require_once '../layouts/dbconn.php';
require_once '../layouts/session.php';

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';

try {
    switch ($action) {
        case 'check_slots':
            checkAvailableSlots($conn);
            break;
        
        case 'get_doctor_schedule':
            getDoctorSchedule($conn);
            break;
        
        case 'debug_doctor':
            debugDoctorInfo($conn);
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
}

function checkAvailableSlots($conn) {
    $doctor_id = $_POST['doctor_id'] ?? 0;
    $date = $_POST['date'] ?? '';
    
    // DEBUG: Log what we received
    error_log("=== SLOT CHECK DEBUG ===");
    error_log("Received doctor_id: " . $doctor_id);
    error_log("Received date: " . $date);
    
    if (!$doctor_id || !$date) {
        echo json_encode([
            'success' => false, 
            'message' => 'Doctor ID and date required',
            'debug' => [
                'received_doctor_id' => $doctor_id,
                'received_date' => $date
            ]
        ]);
        return;
    }
    
    // Get day of week (lowercase for JSON matching)
    $dayOfWeek = strtolower(date('l', strtotime($date)));
    error_log("Calculated day of week: " . $dayOfWeek);
    
    // 0. CHECK DATE-SPECIFIC SLOTS FIRST (doctor_schedule_slots) - hybrid model
    $day_sessions = [];
    $table_exists = $conn->query("SHOW TABLES LIKE 'doctor_schedule_slots'");
    if ($table_exists && $table_exists->num_rows > 0) {
        $date_sql = "SELECT start_time, end_time, location_type, facility_name, facility_address FROM doctor_schedule_slots 
                     WHERE doctor_id = ? AND schedule_date = ? ORDER BY start_time";
        $date_stmt = $conn->prepare($date_sql);
        $date_stmt->bind_param("is", $doctor_id, $date);
        $date_stmt->execute();
        $date_result = $date_stmt->get_result();
        while ($row = $date_result->fetch_assoc()) {
            $day_sessions[] = [
                'location_type' => $row['location_type'],
                'start' => substr($row['start_time'], 0, 5),
                'end' => substr($row['end_time'], 0, 5),
                'facility_name' => $row['facility_name'],
                'facility_address' => $row['facility_address']
            ];
        }
    }
    $use_date_specific = !empty($day_sessions);
    
    // 1. CHECK IF DOCTOR EXISTS AND GET SCHEDULE FROM JSON (for fallback)
    $doctor_check_sql = "SELECT d.doctor_id, u.full_name, d.user_id, d.availability_schedule, d.appointment_duration
                        FROM doctors d
                        INNER JOIN users u ON d.user_id = u.user_id
                        WHERE d.doctor_id = ? AND d.is_active = 1";
    $stmt = $conn->prepare($doctor_check_sql);
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $doctor_result = $stmt->get_result();
    
    if ($doctor_result->num_rows === 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Doctor not found in database',
            'debug' => [
                'doctor_id' => $doctor_id,
                'query_executed' => true
            ]
        ]);
        error_log("ERROR: Doctor ID $doctor_id not found in doctors table");
        return;
    }
    
    $doctor_info = $doctor_result->fetch_assoc();
    error_log("Found doctor: " . $doctor_info['full_name'] . " (ID: " . $doctor_info['doctor_id'] . ")");
    
    $appointment_duration = (int)$doctor_info['appointment_duration'];
    
    // 2. IF NO DATE-SPECIFIC SLOTS, FALL BACK TO WEEKLY SCHEDULE
    if (!$use_date_specific) {
        $schedule_json = $doctor_info['availability_schedule'];
        if (empty($schedule_json)) {
            echo json_encode([
                'success' => false,
                'message' => "No schedule configured for {$doctor_info['full_name']}. Please update doctor's availability.",
                'debug' => ['doctor_id' => $doctor_id, 'has_schedule_json' => false]
            ]);
            return;
        }
        $schedule_data = json_decode($schedule_json, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            echo json_encode(['success' => false, 'message' => 'Invalid schedule data format']);
            return;
        }
        if (!isset($schedule_data[$dayOfWeek]) || empty($schedule_data[$dayOfWeek]['sessions'])) {
            $working_days = [];
            foreach ($schedule_data as $day => $data) {
                if (!empty($data['sessions'])) $working_days[] = ucfirst($day);
            }
            echo json_encode([
                'success' => false,
                'message' => "Doctor has no schedule for " . ucfirst($dayOfWeek),
                'working_days' => $working_days
            ]);
            return;
        }
        $day_sessions = $schedule_data[$dayOfWeek]['sessions'];
    }
    
    error_log("Using " . ($use_date_specific ? 'date-specific' : 'weekly') . " schedule: " . count($day_sessions) . " sessions");
    
    // DEBUG: Check appointments table structure
    $check_columns_sql = "SHOW COLUMNS FROM appointments";
    $columns_result = $conn->query($check_columns_sql);
    $columns = [];
    while ($col = $columns_result->fetch_assoc()) {
        $columns[] = $col['Field'];
    }
    error_log("Appointments table columns: " . implode(', ', $columns));
    
    // 4. GET EXISTING APPOINTMENTS - Check which columns exist
    $has_appointment_datetime = in_array('appointment_datetime', $columns);
    $has_appointment_date = in_array('appointment_date', $columns);
    $has_appointment_time = in_array('appointment_time', $columns);
    
    error_log("appointment_datetime exists: " . ($has_appointment_datetime ? 'YES' : 'NO'));
    error_log("appointment_date exists: " . ($has_appointment_date ? 'YES' : 'NO'));
    error_log("appointment_time exists: " . ($has_appointment_time ? 'YES' : 'NO'));
    
    // Build query based on available columns
    if ($has_appointment_datetime) {
        $booked_slots_sql = "SELECT TIME(appointment_datetime) as booked_time
                             FROM appointments
                             WHERE doctor_id = ? 
                               AND DATE(appointment_datetime) = ?
                               AND status NOT IN ('CANCELLED', 'NO_SHOW')";
    } else if ($has_appointment_date && $has_appointment_time) {
        $booked_slots_sql = "SELECT appointment_time as booked_time
                             FROM appointments
                             WHERE doctor_id = ? 
                               AND appointment_date = ?
                               AND status NOT IN ('CANCELLED', 'NO_SHOW')";
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Cannot determine appointments table structure',
            'debug' => [
                'columns_found' => $columns,
                'has_datetime' => $has_appointment_datetime,
                'has_date' => $has_appointment_date,
                'has_time' => $has_appointment_time
            ]
        ]);
        return;
    }
    
    $stmt = $conn->prepare($booked_slots_sql);
    $stmt->bind_param("is", $doctor_id, $date);
    $stmt->execute();
    $booked_result = $stmt->get_result();
    
    $booked_times = [];
    while ($row = $booked_result->fetch_assoc()) {
        $booked_times[] = $row['booked_time'];
    }
    
    error_log("Found " . count($booked_times) . " booked appointments");
    if (!empty($booked_times)) {
        error_log("Booked times: " . implode(', ', $booked_times));
    }
    
    // 5. GENERATE AVAILABLE SLOTS FROM EACH SESSION
    $available_slots = [];
    $schedules = [];
    
    foreach ($day_sessions as $index => $session) {
        error_log("Processing session #" . ($index + 1));
        
        $location_type = $session['location_type'] ?? 'internal';
        $start_time = $session['start'] ?? null;
        $end_time = $session['end'] ?? null;
        
        if (!$start_time || !$end_time) {
            error_log("WARNING: Session missing start or end time");
            continue;
        }
        
        // Ensure times have seconds
        if (strlen($start_time) === 5) $start_time .= ':00';
        if (strlen($end_time) === 5) $end_time .= ':00';
        
        $facility_name = $session['facility_name'] ?? null;
        $facility_address = $session['facility_address'] ?? '';
        
        error_log("Processing session: $location_type $start_time-$end_time");
        
        $schedules[] = [
            'session_type' => ucfirst($location_type),
            'location' => $location_type === 'external' ? $facility_name : 'Main Hospital',
            'start_time' => $start_time,
            'end_time' => $end_time,
            'facility_address' => $facility_address
        ];
        
        // Generate time slots for this session
        try {
            $start = new DateTime($date . ' ' . $start_time);
            $end = new DateTime($date . ' ' . $end_time);
        } catch (Exception $e) {
            error_log("ERROR creating DateTime: " . $e->getMessage());
            continue;
        }
        
        $slot_count = 0;
        while ($start < $end) {
            $slot_time = $start->format('H:i:s');
            
            // Check if this slot is already booked
            if (!in_array($slot_time, $booked_times)) {
                $available_slots[] = [
                    'time' => $slot_time,
                    'formatted_time' => $start->format('g:i A'),
                    'session_type' => ucfirst($location_type),
                    'location' => $location_type === 'external' ? $facility_name : 'Main Hospital'
                ];
                $slot_count++;
            } else {
                error_log("Slot $slot_time already booked");
            }
            
            try {
                $start->add(new DateInterval('PT' . $appointment_duration . 'M'));
            } catch (Exception $e) {
                error_log("ERROR adding interval: " . $e->getMessage());
                break;
            }
        }
        
        error_log("Generated $slot_count available slots for this session");
    }
    
    error_log("Total available slots: " . count($available_slots));
    
    echo json_encode([
        'success' => true,
        'has_slots' => count($available_slots) > 0,
        'slots' => $available_slots,
        'schedules' => $schedules,
        'message' => count($available_slots) > 0 
            ? count($available_slots) . ' slots available' 
            : 'No available slots for this date',
        'debug' => [
            'doctor_id' => $doctor_id,
            'doctor_name' => $doctor_info['full_name'],
            'date' => $date,
            'day_of_week' => $dayOfWeek,
            'total_sessions' => count($day_sessions),
            'total_slots_generated' => count($available_slots),
            'booked_count' => count($booked_times),
            'booked_times' => $booked_times,
            'appointment_duration' => $appointment_duration,
            'table_structure' => [
                'has_datetime' => $has_appointment_datetime ?? false,
                'has_date_time_separate' => ($has_appointment_date && $has_appointment_time) ?? false
            ]
        ]
    ]);
}

function getDoctorSchedule($conn) {
    $doctor_id = $_GET['doctor_id'] ?? 0;
    
    if (!$doctor_id) {
        echo json_encode(['success' => false, 'message' => 'Doctor ID required']);
        return;
    }
    
    // Get doctor and their JSON schedule
    $doctor_check_sql = "SELECT d.doctor_id, u.full_name, d.availability_schedule, 
                                d.appointment_duration, d.consultation_fee, d.follow_up_fee
                        FROM doctors d
                        INNER JOIN users u ON d.user_id = u.user_id
                        WHERE d.doctor_id = ? AND d.is_active = 1";
    $stmt = $conn->prepare($doctor_check_sql);
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $doctor_result = $stmt->get_result();
    
    if ($doctor_result->num_rows === 0) {
        echo json_encode([
            'success' => false, 
            'message' => 'Doctor not found',
            'debug' => ['doctor_id' => $doctor_id]
        ]);
        return;
    }
    
    $doctor_info = $doctor_result->fetch_assoc();
    $schedule_json = $doctor_info['availability_schedule'];
    
    if (empty($schedule_json)) {
        echo json_encode([
            'success' => true,
            'schedules' => [],
            'message' => 'No schedule configured for this doctor',
            'debug' => [
                'doctor_id' => $doctor_id,
                'doctor_name' => $doctor_info['full_name'],
                'total_schedules' => 0
            ]
        ]);
        return;
    }
    
    $schedule_data = json_decode($schedule_json, true);
    
    // Format schedules for display - convert JSON to table format
    $formatted_schedules = [];
    $days_order = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
    
    foreach ($days_order as $day) {
        if (isset($schedule_data[$day]) && !empty($schedule_data[$day]['sessions'])) {
            foreach ($schedule_data[$day]['sessions'] as $session) {
                $start_time = $session['start'];
                $end_time = $session['end'];
                
                // Add seconds if missing
                if (strlen($start_time) === 5) $start_time .= ':00';
                if (strlen($end_time) === 5) $end_time .= ':00';
                
                $formatted_schedules[] = [
                    'day_of_week' => ucfirst($day),
                    'start_time' => $start_time,
                    'end_time' => $end_time,
                    'session_type' => ucfirst($session['location_type']),
                    'location' => $session['facility_name'] ?? 'Main Hospital',
                    'max_patients' => 20, // Default value
                    'appointment_duration' => $doctor_info['appointment_duration'],
                    'consultation_fee' => $doctor_info['consultation_fee'],
                    'is_active' => 1
                ];
            }
        }
    }
    
    echo json_encode([
        'success' => true,
        'schedules' => $formatted_schedules,
        'debug' => [
            'doctor_id' => $doctor_id,
            'doctor_name' => $doctor_info['full_name'],
            'total_schedules' => count($formatted_schedules)
        ]
    ]);
}

function debugDoctorInfo($conn) {
    $doctor_id = $_GET['doctor_id'] ?? $_POST['doctor_id'] ?? 0;
    
    // Get doctor info
    $doctor_sql = "SELECT d.*, u.full_name, u.user_id
                  FROM doctors d
                  INNER JOIN users u ON d.user_id = u.user_id
                  WHERE d.doctor_id = ?";
    $stmt = $conn->prepare($doctor_sql);
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $doctor = $stmt->get_result()->fetch_assoc();
    
    // Parse schedule from JSON
    $schedule_data = null;
    $schedule_summary = [];
    if ($doctor && $doctor['availability_schedule']) {
        $schedule_data = json_decode($doctor['availability_schedule'], true);
        
        // Create summary
        if ($schedule_data) {
            foreach ($schedule_data as $day => $data) {
                if (!empty($data['sessions'])) {
                    $schedule_summary[$day] = count($data['sessions']) . ' session(s)';
                }
            }
        }
    }
    
    // Get appointments count
    $appt_sql = "SELECT COUNT(*) as count FROM appointments WHERE doctor_id = ?";
    $stmt = $conn->prepare($appt_sql);
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $appt_count = $stmt->get_result()->fetch_assoc()['count'];
    
    // Get recent appointments
    $recent_appt_sql = "SELECT appointment_id, appointment_number, patient_id, 
                               appointment_date, appointment_time, status
                        FROM appointments 
                        WHERE doctor_id = ? 
                        ORDER BY appointment_date DESC, appointment_time DESC 
                        LIMIT 5";
    $stmt = $conn->prepare($recent_appt_sql);
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $recent_appointments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
    // Get appointment slots count (if using pre-generated slots)
    $slots_sql = "SELECT COUNT(*) as count FROM appointment_slots WHERE doctor_id = ?";
    $stmt = $conn->prepare($slots_sql);
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $slots_count = $stmt->get_result()->fetch_assoc()['count'];
    
    echo json_encode([
        'success' => true,
        'doctor' => $doctor,
        'schedule_data' => $schedule_data,
        'schedule_summary' => $schedule_summary,
        'appointment_count' => $appt_count,
        'recent_appointments' => $recent_appointments,
        'slots_count' => $slots_count,
        'debug' => [
            'doctor_exists' => $doctor ? true : false,
            'has_schedule_json' => !empty($doctor['availability_schedule']),
            'schedule_is_valid_json' => $schedule_data ? true : false,
            'total_appointments' => $appt_count,
            'total_pre_generated_slots' => $slots_count
        ]
    ]);
}
?>