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

include 'layouts/dbconn.php';

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

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

try {
    // Get parameters
    $appointment_id = isset($_POST['appointment_id']) ? (int)$_POST['appointment_id'] : 0;
    $new_status = isset($_POST['status']) ? trim($_POST['status']) : '';
    
    // Validate
    if (!$appointment_id || !$new_status) {
        throw new Exception('Appointment ID and status are required');
    }
    
    // Valid statuses
    $valid_statuses = ['SCHEDULED', 'CONFIRMED', 'CHECKED_IN', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED', 'NO_SHOW'];
    if (!in_array($new_status, $valid_statuses)) {
        throw new Exception('Invalid status');
    }
    
    // Get current appointment
    $check_sql = "SELECT appointment_id, status, patient_id, doctor_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');
    }
    
    // Role-based permission check
    $allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'RECEPTIONIST', 'NURSE', 'ENT_DOCTOR', 'ENT_CONSULTANT'];
    if (!in_array($_SESSION['role_code'], $allowed_roles)) {
        throw new Exception('You do not have permission to update appointments');
    }
    
    // Validate status transitions
    $current_status = $appointment['status'];
    $valid_transitions = [
        'SCHEDULED' => ['CONFIRMED', 'CANCELLED', 'NO_SHOW'],
        'CONFIRMED' => ['CHECKED_IN', 'CANCELLED', 'NO_SHOW'],
        'CHECKED_IN' => ['IN_PROGRESS', 'CANCELLED'],
        'IN_PROGRESS' => ['COMPLETED'],
        'COMPLETED' => [],
        'CANCELLED' => [],
        'NO_SHOW' => []
    ];
    
    if (!isset($valid_transitions[$current_status]) || 
        !in_array($new_status, $valid_transitions[$current_status])) {
        throw new Exception("Cannot change status from {$current_status} to {$new_status}");
    }
    
    // Begin transaction
    $conn->begin_transaction();
    
    // Update appointment status
    $update_sql = "UPDATE appointments 
                   SET status = ?, 
                       updated_at = NOW()";
    
    // Add specific timestamp fields based on status
    switch ($new_status) {
        case 'CHECKED_IN':
            $update_sql .= ", checked_in_at = NOW()";
            break;
        case 'COMPLETED':
            $update_sql .= ", completed_at = NOW()";
            break;
    }
    
    $update_sql .= " WHERE appointment_id = ?";
    
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("si", $new_status, $appointment_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update appointment status');
    }
    $stmt->close();
    
   $activity_sql = "INSERT INTO activity_logs 
                 (user_id, action, entity_type, entity_id, description, ip_address, status)
                 VALUES (?, 'UPDATE', 'APPOINTMENT', ?, ?, ?, 'SUCCESS')";

$description = "Updated appointment status from " . strtoupper($current_status) . " to " . strtoupper($status);
$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 (SMS/Email)
    // This can be implemented using your notification system
    
    $conn->commit();
    
    $response = [
        'success' => true,
        'message' => 'Appointment status updated successfully',
        'new_status' => $new_status
    ];
    
} catch (Exception $e) {
    if (isset($conn)) {
        $conn->rollback();
    }
    error_log("Update appointment status error: " . $e->getMessage());
    $response = [
        'success' => false,
        'message' => $e->getMessage()
    ];
}

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

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