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

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

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

$user_id = $_SESSION['user_id'];
$appointment_id = $_POST['appointment_id'] ?? '';
$new_date = $_POST['new_date'] ?? '';
$new_time = $_POST['new_time'] ?? '';
$reason = $_POST['reason'] ?? '';

if (empty($appointment_id) || empty($new_date) || empty($new_time)) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit();
}

// Verify the appointment belongs to this doctor
$check_query = "SELECT appointment_id, patient_id, doctor_id, appointment_date, appointment_time 
                FROM appointments 
                WHERE appointment_id = ? AND doctor_id = ?";
$check_stmt = $conn->prepare($check_query);
$check_stmt->bind_param("ii", $appointment_id, $user_id);
$check_stmt->execute();
$appointment = $check_stmt->get_result()->fetch_assoc();

if (!$appointment) {
    echo json_encode(['success' => false, 'message' => 'Appointment not found or access denied']);
    exit();
}

// Start transaction
$conn->begin_transaction();

try {
    // Check if new time slot is available
    $slot_check = "SELECT slot_id FROM appointment_slots 
                   WHERE doctor_id = ? 
                   AND slot_date = ? 
                   AND start_time = ? 
                   AND is_available = 1";
    $slot_stmt = $conn->prepare($slot_check);
    $slot_stmt->bind_param("iss", $user_id, $new_date, $new_time);
    $slot_stmt->execute();
    $slot_result = $slot_stmt->get_result();
    
    $new_slot_id = null;
    if ($slot_result->num_rows > 0) {
        $slot = $slot_result->fetch_assoc();
        $new_slot_id = $slot['slot_id'];
    }
    
    // Update appointment
    $update_query = "UPDATE appointments 
                     SET appointment_date = ?,
                         appointment_time = ?,
                         slot_id = ?,
                         status = 'SCHEDULED',
                         notes = CONCAT(IFNULL(notes, ''), '\nRescheduled: ', ?)
                     WHERE appointment_id = ?";
    $update_stmt = $conn->prepare($update_query);
    $update_stmt->bind_param("ssisi", $new_date, $new_time, $new_slot_id, $reason, $appointment_id);
    
    if (!$update_stmt->execute()) {
        throw new Exception('Failed to update appointment');
    }
    
    // Log the activity
    $log_query = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address) 
                  VALUES (?, 'UPDATE', 'appointment', ?, ?, ?)";
    $log_stmt = $conn->prepare($log_query);
    $description = "Rescheduled appointment to " . $new_date . " " . $new_time;
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $log_stmt->bind_param("iiss", $user_id, $appointment_id, $description, $ip_address);
    $log_stmt->execute();
    
    // Queue SMS notification to patient
    $notify_query = "INSERT INTO notification_queue (notification_type, recipient_data, priority, scheduled_for)
                     SELECT 'sms', 
                            JSON_OBJECT(
                                'phone', p.phone_number,
                                'message', CONCAT('Your appointment has been rescheduled to ', 
                                                 DATE_FORMAT(?, '%d/%m/%Y'), ' at ', 
                                                 TIME_FORMAT(?, '%h:%i %p'), 
                                                 '. Ref: ', a.appointment_number),
                                'appointment_id', a.appointment_id
                            ),
                            5,
                            NOW()
                     FROM appointments a
                     INNER JOIN patients p ON a.patient_id = p.patient_id
                     WHERE a.appointment_id = ?";
    $notify_stmt = $conn->prepare($notify_query);
    $notify_stmt->bind_param("ssi", $new_date, $new_time, $appointment_id);
    $notify_stmt->execute();
    
    // Commit transaction
    $conn->commit();
    
    echo json_encode([
        'success' => true, 
        'message' => 'Appointment rescheduled successfully. Patient will be notified via SMS.'
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>