<?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', 'RECEPTIONIST'];
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 {
    $conn->begin_transaction();
    
    $appointment_id = isset($_POST['appointment_id']) ? (int)$_POST['appointment_id'] : 0;
    $cancellation_reason = isset($_POST['cancellation_reason']) ? trim($_POST['cancellation_reason']) : '';
    
    if (!$appointment_id) {
        throw new Exception('Invalid appointment ID');
    }
    
    if (empty($cancellation_reason)) {
        throw new Exception('Cancellation reason is required');
    }
    
    // Get appointment details
    $check_sql = "SELECT a.*, p.patient_id, u.full_name as patient_name, u.phone_primary, u.email
                  FROM appointments a
                  INNER JOIN patients p ON a.patient_id = p.patient_id
                  INNER JOIN users u ON p.user_id = u.user_id
                  WHERE a.appointment_id = ?";
    $stmt = $conn->prepare($check_sql);
    $stmt->bind_param('i', $appointment_id);
    $stmt->execute();
    $appointment = $stmt->get_result()->fetch_assoc();
    
    if (!$appointment) {
        throw new Exception('Appointment not found');
    }
    
    // Check if appointment can be cancelled
    if (!in_array($appointment['status'], ['SCHEDULED', 'CONFIRMED'])) {
        throw new Exception('Only scheduled or confirmed appointments can be cancelled');
    }
    
    // Update appointment status
    $update_sql = "UPDATE appointments SET 
                    status = 'CANCELLED',
                    cancellation_reason = ?,
                    cancelled_by = ?,
                    cancelled_at = CURRENT_TIMESTAMP,
                    updated_at = CURRENT_TIMESTAMP
                   WHERE appointment_id = ?";
    
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param('sii', $cancellation_reason, $_SESSION['user_id'], $appointment_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to cancel appointment');
    }
    
    // Log activity
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? null;
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? null;
    
    $activity_sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, user_agent) 
                     VALUES (?, 'CANCEL', 'appointment', ?, ?, ?, ?)";
    $stmt = $conn->prepare($activity_sql);
    $description = "Cancelled appointment #{$appointment['appointment_number']} for {$appointment['patient_name']}. Reason: $cancellation_reason";
    $stmt->bind_param('iisss', $_SESSION['user_id'], $appointment_id, $description, $ip_address, $user_agent);
    $stmt->execute();
    
    // TODO: Send notification to patient (SMS/Email)
    // You can integrate with your SMS and Email systems here
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Appointment cancelled successfully'
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>