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

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

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

$response = ['success' => false, 'message' => ''];

try {
    // Get form data
    $appointment_id = isset($_POST['appointment_id']) ? (int)$_POST['appointment_id'] : 0;
    $doctor_id = isset($_POST['doctor_id']) ? (int)$_POST['doctor_id'] : 0;
    $new_date = isset($_POST['appointment_date']) ? trim($_POST['appointment_date']) : '';
    $new_time = isset($_POST['appointment_time']) ? trim($_POST['appointment_time']) : '';
    $reason = isset($_POST['reschedule_reason']) ? trim($_POST['reschedule_reason']) : '';
    
    // Validate
    if (!$appointment_id || !$doctor_id || !$new_date || !$new_time || empty($reason)) {
        throw new Exception('All fields are required');
    }
    
    // Validate date format
    $date_obj = DateTime::createFromFormat('Y-m-d', $new_date);
    if (!$date_obj) {
        throw new Exception('Invalid date format');
    }
    
    // Check permissions
    $allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'FRONT_OFFICE'];
    if (!in_array($_SESSION['role_code'], $allowed_roles)) {
        throw new Exception('You do not have permission to reschedule appointments');
    }
    
    // Get current appointment details
    $check_sql = "SELECT appointment_id, status, appointment_date, appointment_time, slot_id
                  FROM appointments 
                  WHERE appointment_id = ?";
    
    $stmt = $conn->prepare($check_sql);
    $stmt->bind_param("i", $appointment_id);
    $stmt->execute();
    $appointment = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if (!$appointment) {
        throw new Exception('Appointment not found');
    }
    
    // Check if appointment can be rescheduled
    if (!in_array($appointment['status'], ['SCHEDULED', 'CONFIRMED'])) {
        throw new Exception('Only scheduled or confirmed appointments can be rescheduled');
    }
    
    // Check if new slot is available
    $slot_check_sql = "SELECT COUNT(*) as count 
                      FROM appointments 
                      WHERE doctor_id = ? 
                      AND appointment_date = ? 
                      AND appointment_time = ?
                      AND status NOT IN ('CANCELLED', 'NO_SHOW')
                      AND appointment_id != ?";
    
    $stmt = $conn->prepare($slot_check_sql);
    $stmt->bind_param("issi", $doctor_id, $new_date, $new_time, $appointment_id);
    $stmt->execute();
    $slot_check = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if ($slot_check['count'] > 0) {
        throw new Exception('Selected time slot is no longer available');
    }
    
    $conn->begin_transaction();
    
    // Free up old slot if exists
    if ($appointment['slot_id']) {
        $free_slot_sql = "UPDATE appointment_slots 
                         SET booked_patients = GREATEST(0, booked_patients - 1),
                             is_available = IF(booked_patients < max_patients, 1, 0)
                         WHERE slot_id = ?";
        
        $stmt = $conn->prepare($free_slot_sql);
        $stmt->bind_param("i", $appointment['slot_id']);
        $stmt->execute();
        $stmt->close();
    }
    
    // Update appointment
    $update_sql = "UPDATE appointments 
                   SET doctor_id = ?,
                       appointment_date = ?,
                       appointment_time = ?,
                       slot_id = NULL,
                       notes = CONCAT(COALESCE(notes, ''), '\n\n[Rescheduled on ', NOW(), ' by user ', ?, ']\nReason: ', ?),
                       updated_at = NOW()
                   WHERE appointment_id = ?";
    
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("issisi", $doctor_id, $new_date, $new_time, $_SESSION['user_id'], $reason, $appointment_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to reschedule appointment');
    }
    $stmt->close();
    
    // Log activity
    $activity_sql = "INSERT INTO activity_logs 
                     (user_id, action_type, entity_type, entity_id, description, ip_address, created_at)
                     VALUES (?, 'UPDATE', 'APPOINTMENT', ?, ?, ?, NOW())";
    
    $old_datetime = date('M d, Y h:i A', strtotime($appointment['appointment_date'] . ' ' . $appointment['appointment_time']));
    $new_datetime = date('M d, Y h:i A', strtotime($new_date . ' ' . $new_time));
    $description = "Rescheduled appointment from {$old_datetime} to {$new_datetime}. Reason: {$reason}";
    $ip_address = $_SERVER['REMOTE_ADDR'];
    
    $stmt = $conn->prepare($activity_sql);
    $stmt->bind_param("iiss", $_SESSION['user_id'], $appointment_id, $description, $ip_address);
    $stmt->execute();
    $stmt->close();
    
    // TODO: Send notification to patient about rescheduling
    
    $conn->commit();
    
    $response = [
        'success' => true,
        'message' => 'Appointment rescheduled successfully'
    ];
    
} catch (Exception $e) {
    if (isset($conn)) {
        $conn->rollback();
    }
    error_log("Reschedule appointment error: " . $e->getMessage());
    $response = [
        'success' => false,
        'message' => $e->getMessage()
    ];
}

if (isset($conn)) {
    $conn->close();
}

echo json_encode($response);
exit();
?>