<?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 provided');
    }
    
    // Get current appointment
    $check_sql = "SELECT appointment_id, status, patient_id, doctor_id, appointment_number
                  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->error);
    }
    $stmt->close();
    
    // Log activity - Using correct column names from activity_log table
    $activity_sql = "INSERT INTO activity_log 
                     (user_id, action, module, record_id, record_type, new_values, ip_address, user_agent, session_id, logged_at)
                     VALUES (?, 'UPDATE', 'APPOINTMENTS', ?, 'APPOINTMENT', ?, ?, ?, ?, NOW())";
    
    $new_values_json = json_encode([
        'appointment_number' => $appointment['appointment_number'],
        'previous_status' => $current_status,
        'new_status' => $new_status,
        'updated_by' => $_SESSION['user_id'],
        'updated_by_role' => $_SESSION['role_code']
    ]);
    
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $session_id = session_id();
    
    $stmt = $conn->prepare($activity_sql);
    $stmt->bind_param("iissss", $_SESSION['user_id'], $appointment_id, $new_values_json, $ip_address, $user_agent, $session_id);
    
    if (!$stmt->execute()) {
        // Log activity failure shouldn't break the main operation
        error_log("Failed to log activity: " . $stmt->error);
    }
    $stmt->close();
    
    // Send notification based on status
    try {
        // Get patient phone for SMS
        $patient_sql = "SELECT u.phone_primary, u.full_name, u.email
                       FROM patients p
                       INNER JOIN users u ON p.user_id = u.user_id
                       WHERE p.patient_id = ?";
        $stmt = $conn->prepare($patient_sql);
        $stmt->bind_param("i", $appointment['patient_id']);
        $stmt->execute();
        $patient_info = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        if ($patient_info) {
            // Prepare notification message based on status
            $message = '';
            switch ($new_status) {
                case 'CONFIRMED':
                    $message = "Dear {$patient_info['full_name']}, your appointment ({$appointment['appointment_number']}) has been confirmed. See you soon!";
                    break;
                case 'CHECKED_IN':
                    $message = "Dear {$patient_info['full_name']}, you have been checked in. Please wait to be called.";
                    break;
                case 'COMPLETED':
                    $message = "Dear {$patient_info['full_name']}, thank you for your visit. Your appointment has been completed.";
                    break;
            }
            
            // TODO: Send SMS/Email notification
            // You can implement this using your notification system
            // For now, we'll just log it
            if (!empty($message)) {
                error_log("Notification to send: " . $message);
            }
        }
    } catch (Exception $notif_error) {
        // Notification failure shouldn't break the main operation
        error_log("Notification error: " . $notif_error->getMessage());
    }
    
    $conn->commit();
    
    // Success response with status label
    $status_labels = [
        'SCHEDULED' => 'Scheduled',
        'CONFIRMED' => 'Confirmed',
        'CHECKED_IN' => 'Checked In',
        'IN_PROGRESS' => 'In Progress',
        'COMPLETED' => 'Completed',
        'CANCELLED' => 'Cancelled',
        'NO_SHOW' => 'No Show'
    ];
    
    $response = [
        'success' => true,
        'message' => 'Appointment status updated to ' . $status_labels[$new_status],
        'new_status' => $new_status,
        'status_label' => $status_labels[$new_status]
    ];
    
} catch (Exception $e) {
    if (isset($conn) && $conn->connect_errno === 0) {
        $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();
?>