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

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

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ENT_DOCTOR', 'ENT_CONSULTANT'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'You do not have permission to perform this action']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

try {
    $doctor_id = isset($_POST['doctor_id']) ? (int)$_POST['doctor_id'] : 0;
    
    if (!$doctor_id) {
        throw new Exception('Invalid doctor ID');
    }
    
    // Check permission - doctors can only update their own schedule
    if (!in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN'])) {
        $check_sql = "SELECT user_id FROM doctors WHERE doctor_id = ?";
        $stmt = $conn->prepare($check_sql);
        $stmt->bind_param('i', $doctor_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $doctor = $result->fetch_assoc();
        
        if (!$doctor || $doctor['user_id'] !== $_SESSION['user_id']) {
            throw new Exception('You can only update your own schedule');
        }
    }
    
    $conn->begin_transaction();
    
    // Process schedule data
    $schedule = isset($_POST['schedule']) ? $_POST['schedule'] : [];
    $schedule_data = [];
    
    $days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
    
    $total_internal_sessions = 0;
    $total_external_sessions = 0;
    $total_days_with_schedule = 0;
    
    foreach ($days as $day) {
        $schedule_data[$day] = ['sessions' => []];
        
        if (isset($schedule[$day]['sessions']) && is_array($schedule[$day]['sessions'])) {
            $day_sessions = [];
            
            foreach ($schedule[$day]['sessions'] as $session_index => $session) {
                // Skip if no location type
                if (!isset($session['location_type'])) {
                    continue;
                }
                
                $location_type = trim($session['location_type']);
                
                // Validate required fields
                if (empty($session['start']) || empty($session['end'])) {
                    throw new Exception("Start and end times are required for all sessions on " . ucfirst($day));
                }
                
                $start_time = trim($session['start']);
                $end_time = trim($session['end']);
                
                // Validate time format
                if (!strtotime($start_time) || !strtotime($end_time)) {
                    throw new Exception("Invalid time format for " . ucfirst($day));
                }
                
                // Ensure end time is after start time
                if (strtotime($end_time) <= strtotime($start_time)) {
                    throw new Exception("End time must be after start time for " . ucfirst($day));
                }
                
                // Build session data
                $session_data = [
                    'location_type' => $location_type,
                    'start' => $start_time,
                    'end' => $end_time
                ];
                
                // Handle external facility details
                if ($location_type === 'external') {
                    if (empty($session['facility_name'])) {
                        throw new Exception("Facility name is required for external sessions on " . ucfirst($day));
                    }
                    
                    $session_data['facility_name'] = trim($session['facility_name']);
                    $session_data['facility_address'] = isset($session['facility_address']) ? trim($session['facility_address']) : '';
                    $session_data['facility_contact'] = isset($session['facility_contact']) ? trim($session['facility_contact']) : '';
                    
                    $total_external_sessions++;
                } else {
                    $total_internal_sessions++;
                }
                
                $day_sessions[] = $session_data;
            }
            
            // Sort sessions by start time
            usort($day_sessions, function($a, $b) {
                return strtotime($a['start']) - strtotime($b['start']);
            });
            
            // Check for overlapping sessions
            for ($i = 0; $i < count($day_sessions) - 1; $i++) {
                $current_end = strtotime($day_sessions[$i]['end']);
                $next_start = strtotime($day_sessions[$i + 1]['start']);
                
                if ($current_end > $next_start) {
                    throw new Exception("Overlapping time slots detected on " . ucfirst($day) . ". Please ensure sessions do not overlap.");
                }
            }
            
            $schedule_data[$day]['sessions'] = $day_sessions;
            
            if (!empty($day_sessions)) {
                $total_days_with_schedule++;
            }
        }
    }
    
    // Convert to JSON
    $availability_json = json_encode($schedule_data, JSON_PRETTY_PRINT);
    
    if ($availability_json === false) {
        throw new Exception('Failed to encode schedule data');
    }
    
    // Update doctor schedule
    $update_sql = "UPDATE doctors SET 
                    availability_schedule = ?,
                    updated_at = CURRENT_TIMESTAMP
                   WHERE doctor_id = ?";
    
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param('si', $availability_json, $doctor_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update schedule in database');
    }
    
    // Log activity with detailed description
    $activity_sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description) 
                     VALUES (?, 'UPDATE', 'doctor_schedule', ?, ?)";
    $stmt = $conn->prepare($activity_sql);
    $description = sprintf(
        "Updated weekly schedule for doctor ID: %d (Days with schedule: %d, Internal sessions: %d, External sessions: %d)",
        $doctor_id,
        $total_days_with_schedule,
        $total_internal_sessions,
        $total_external_sessions
    );
    $stmt->bind_param('iis', $_SESSION['user_id'], $doctor_id, $description);
    $stmt->execute();
    
    $conn->commit();
    
    // Prepare summary for response
    $summary = [];
    foreach ($schedule_data as $day => $data) {
        if (!empty($data['sessions'])) {
            $internal_count = 0;
            $external_count = 0;
            
            foreach ($data['sessions'] as $session) {
                if ($session['location_type'] === 'external') {
                    $external_count++;
                } else {
                    $internal_count++;
                }
            }
            
            $summary[] = ucfirst($day) . ': ' . 
                        ($internal_count > 0 ? $internal_count . ' internal' : '') .
                        ($internal_count > 0 && $external_count > 0 ? ', ' : '') .
                        ($external_count > 0 ? $external_count . ' external' : '');
        }
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Schedule updated successfully',
        'data' => [
            'total_days' => $total_days_with_schedule,
            'internal_sessions' => $total_internal_sessions,
            'external_sessions' => $total_external_sessions,
            'total_sessions' => $total_internal_sessions + $total_external_sessions,
            'summary' => $summary
        ]
    ]);
    
} catch (Exception $e) {
    if (isset($conn)) {
        $conn->rollback();
    }
    
    error_log("Schedule update error: " . $e->getMessage());
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>