<?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'] ?? '';

if (empty($appointment_id)) {
    echo json_encode(['success' => false, 'message' => 'Appointment ID is required']);
    exit();
}

// Verify the appointment belongs to this doctor
$check_query = "SELECT a.appointment_id, a.patient_id, a.doctor_id, a.slot_id, a.appointment_number,
                       p.phone_number, p.first_name, p.last_name
                FROM appointments a
                INNER JOIN patients p ON a.patient_id = p.patient_id
                WHERE a.appointment_id = ? AND a.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 {
    // Update appointment status
    $update_query = "UPDATE appointments 
                     SET status = 'CANCELLED',
                         cancellation_reason = 'Cancelled by doctor',
                         cancelled_by = ?
                     WHERE appointment_id = ?";
    $update_stmt = $conn->prepare($update_query);
    $update_stmt->bind_param("ii", $user_id, $appointment_id);
    
    if (!$update_stmt->execute()) {
        throw new Exception('Failed to cancel appointment');
    }
    
    // Free up the slot if assigned
    if ($appointment['slot_id']) {
        $slot_update = "UPDATE appointment_slots 
                        SET is_available = 1, 
                            booked_patients = booked_patients - 1
                        WHERE slot_id = ?";
        $slot_stmt = $conn->prepare($slot_update);
        $slot_stmt->bind_param("i", $appointment['slot_id']);
        $slot_stmt->execute();
    }
    
    // Log the activity
    $log_query = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address) 
                  VALUES (?, 'UPDATE', 'appointment', ?, 'Cancelled appointment', ?)";
    $log_stmt = $conn->prepare($log_query);
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $log_stmt->bind_param("iis", $user_id, $appointment_id, $ip_address);
    $log_stmt->execute();
    
    // Queue SMS notification to patient
    $patient_name = $appointment['first_name'] . ' ' . $appointment['last_name'];
    $sms_message = "Dear " . $patient_name . ", your appointment (Ref: " . $appointment['appointment_number'] . 
                   ") has been cancelled by the doctor. Please contact the hospital to reschedule. " .
                   "We apologize for any inconvenience.";
    
    $notify_query = "INSERT INTO notification_queue (notification_type, recipient_data, priority, scheduled_for)
                     VALUES ('sms', ?, 6, NOW())";
    $notify_stmt = $conn->prepare($notify_query);
    $recipient_data = json_encode([
        'phone' => $appointment['phone_number'],
        'message' => $sms_message,
        'appointment_id' => $appointment_id
    ]);
    $notify_stmt->bind_param("s", $recipient_data);
    $notify_stmt->execute();
    
    // Commit transaction
    $conn->commit();
    
    echo json_encode([
        'success' => true, 
        'message' => 'Appointment cancelled successfully. Patient will be notified via SMS.'
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>