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

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['full_name'] ?? 'Staff';
$action = $_GET['action'] ?? '';
$queue_id = $_GET['queue_id'] ?? 0;

if (empty($action) || empty($queue_id)) {
    header('Location: queue_dashboard.php');
    exit();
}

// Fetch queue details
$queue_sql = "SELECT q.*, d.department_name 
              FROM patient_queue q
              INNER JOIN departments d ON q.department_id = d.department_id
              WHERE q.queue_id = ?";
$stmt = $conn->prepare($queue_sql);
$stmt->bind_param("i", $queue_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Queue record not found";
    header('Location: queue_dashboard.php');
    exit();
}

$queue = $result->fetch_assoc();

try {
    $conn->begin_transaction();
    
    switch ($action) {
        case 'call':
            // Call patient - Send notification and update called time
            $update_sql = "UPDATE patient_queue 
                          SET called_time = NOW(),
                              updated_by = ?
                          WHERE queue_id = ?";
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("ii", $user_id, $queue_id);
            $stmt->execute();
            
            // Send SMS notification if phone available
            if (!empty($queue['phone_number'])) {
                sendQueueNotification(
                    $queue['phone_number'],
                    $queue['patient_name'],
                    $queue['queue_number'],
                    $queue['department_name'],
                    $queue['notification_preference']
                );
                
                // Update SMS sent flag
                $sms_sql = "UPDATE patient_queue SET sms_sent = 1, sms_sent_at = NOW() WHERE queue_id = ?";
                $stmt = $conn->prepare($sms_sql);
                $stmt->bind_param("i", $queue_id);
                $stmt->execute();
            }
            
            // Log activity
            logQueueActivity($conn, $queue_id, $queue['patient_id'], $queue['visit_id'], 
                           $queue['department_id'], 'CALLED', $queue['queue_status'], 
                           $queue['queue_status'], $user_id, $user_name, "Patient called for service");
            
            $_SESSION['success_message'] = "Patient " . $queue['patient_name'] . " has been called and notified";
            break;
            
        case 'start_service':
            // Start service for patient
            $update_sql = "UPDATE patient_queue 
                          SET queue_status = 'IN_SERVICE',
                              service_start_time = NOW(),
                              called_time = COALESCE(called_time, NOW()),
                              total_wait_minutes = TIMESTAMPDIFF(MINUTE, queue_entry_time, NOW()),
                              serving_staff_id = ?,
                              serving_staff_name = ?,
                              updated_by = ?
                          WHERE queue_id = ?";
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("isii", $user_id, $user_name, $user_id, $queue_id);
            $stmt->execute();
            
            // Update queue positions for the department
            $conn->query("CALL UpdateQueuePositions(" . $queue['department_id'] . ")");
            $conn->query("CALL UpdateQueueWaitTimes(" . $queue['department_id'] . ")");
            
            // Log activity
            logQueueActivity($conn, $queue_id, $queue['patient_id'], $queue['visit_id'], 
                           $queue['department_id'], 'STARTED_SERVICE', 'WAITING', 
                           'IN_SERVICE', $user_id, $user_name, "Service started");
            
            $_SESSION['success_message'] = "Service started for " . $queue['patient_name'];
            break;
            
        case 'complete':
            // Complete service
            $update_sql = "UPDATE patient_queue 
                          SET queue_status = 'COMPLETED',
                              service_end_time = NOW(),
                              total_service_minutes = TIMESTAMPDIFF(MINUTE, service_start_time, NOW()),
                              updated_by = ?
                          WHERE queue_id = ?";
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("ii", $user_id, $queue_id);
            $stmt->execute();
            
            // Update queue positions for the department
            $conn->query("CALL UpdateQueuePositions(" . $queue['department_id'] . ")");
            $conn->query("CALL UpdateQueueWaitTimes(" . $queue['department_id'] . ")");
            
            // Log activity
            logQueueActivity($conn, $queue_id, $queue['patient_id'], $queue['visit_id'], 
                           $queue['department_id'], 'COMPLETED_SERVICE', 'IN_SERVICE', 
                           'COMPLETED', $user_id, $user_name, "Service completed");
            
            // Update department statistics
            updateDepartmentStats($conn, $queue['department_id']);
            
            $_SESSION['success_message'] = "Service completed for " . $queue['patient_name'];
            break;
            
        case 'cancel':
            // Cancel queue entry
            $cancel_reason = $_POST['cancel_reason'] ?? 'Not specified';
            
            $update_sql = "UPDATE patient_queue 
                          SET queue_status = 'CANCELLED',
                              cancellation_reason = ?,
                              cancelled_by = ?,
                              service_end_time = NOW(),
                              updated_by = ?
                          WHERE queue_id = ?";
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("siii", $cancel_reason, $user_id, $user_id, $queue_id);
            $stmt->execute();
            
            // Update queue positions
            $conn->query("CALL UpdateQueuePositions(" . $queue['department_id'] . ")");
            $conn->query("CALL UpdateQueueWaitTimes(" . $queue['department_id'] . ")");
            
            // Log activity
            logQueueActivity($conn, $queue_id, $queue['patient_id'], $queue['visit_id'], 
                           $queue['department_id'], 'CANCELLED', $queue['queue_status'], 
                           'CANCELLED', $user_id, $user_name, "Queue cancelled: " . $cancel_reason);
            
            $_SESSION['success_message'] = "Queue entry cancelled for " . $queue['patient_name'];
            break;
            
        case 'no_show':
            // Mark as no show
            $update_sql = "UPDATE patient_queue 
                          SET queue_status = 'NO_SHOW',
                              service_end_time = NOW(),
                              updated_by = ?
                          WHERE queue_id = ?";
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("ii", $user_id, $queue_id);
            $stmt->execute();
            
            // Update queue positions
            $conn->query("CALL UpdateQueuePositions(" . $queue['department_id'] . ")");
            $conn->query("CALL UpdateQueueWaitTimes(" . $queue['department_id'] . ")");
            
            // Log activity
            logQueueActivity($conn, $queue_id, $queue['patient_id'], $queue['visit_id'], 
                           $queue['department_id'], 'NO_SHOW', $queue['queue_status'], 
                           'NO_SHOW', $user_id, $user_name, "Patient did not show up");
            
            $_SESSION['warning_message'] = $queue['patient_name'] . " marked as no-show";
            break;
            
        default:
            $_SESSION['error_message'] = "Invalid action";
            break;
    }
    
    $conn->commit();
    
} catch (Exception $e) {
    $conn->rollback();
    $_SESSION['error_message'] = "Action failed: " . $e->getMessage();
}

header('Location: queue_dashboard.php');
exit();

/**
 * Log queue activity to history table
 */
function logQueueActivity($conn, $queue_id, $patient_id, $visit_id, $department_id, 
                          $action, $from_status, $to_status, $user_id, $user_name, $notes) {
    $sql = "INSERT INTO queue_history (
                queue_id, patient_id, visit_id, department_id, department_name,
                action, from_status, to_status, performed_by, performed_by_name, notes
            ) 
            SELECT 
                ?, ?, ?, ?, d.department_name,
                ?, ?, ?, ?, ?, ?
            FROM departments d WHERE d.department_id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iiissssissi", 
        $queue_id, $patient_id, $visit_id, $department_id,
        $action, $from_status, $to_status, 
        $user_id, $user_name, $notes, $department_id
    );
    $stmt->execute();
}

/**
 * Send queue notification via SMS/WhatsApp
 */
function sendQueueNotification($phone, $patient_name, $queue_number, $department_name, $preference = 'SMS') {
    global $conn;
    
    $message = "Dear " . $patient_name . ",\n\n";
    $message .= "Your queue number " . $queue_number . " is now being called.\n";
    $message .= "Please proceed to " . $department_name . ".\n\n";
    $message .= "Thank you for your patience.";
    
    // Normalize phone number
    $phone = normalizePhoneNumber($phone);
    
    if ($preference === 'WHATSAPP') {
        // Queue WhatsApp message
        queueWhatsAppMessage($conn, $phone, $message, 'queue_call');
    } else {
        // Queue SMS message
        queueSMSMessage($conn, $phone, $message, 'queue_call');
    }
}

/**
 * Queue SMS message for sending
 */
function queueSMSMessage($conn, $phone, $message, $type = 'queue_call') {
    $payload = json_encode([
        'phone' => $phone,
        'message' => $message,
        'type' => $type
    ]);
    
    $sql = "INSERT INTO job_queue (job_type, payload, priority, status) 
            VALUES ('sms', ?, 8, 'pending')";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $payload);
    $stmt->execute();
}

/**
 * Queue WhatsApp message for sending
 */
function queueWhatsAppMessage($conn, $phone, $message, $type = 'queue_call') {
    $payload = json_encode([
        'phone' => $phone,
        'message' => $message,
        'type' => $type
    ]);
    
    $sql = "INSERT INTO job_queue (job_type, payload, priority, status) 
            VALUES ('whatsapp', ?, 8, 'pending')";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $payload);
    $stmt->execute();
}

/**
 * Normalize phone number to Kenyan format
 */
function normalizePhoneNumber($phone) {
    // Remove all non-numeric characters
    $phone = preg_replace('/[^0-9]/', '', $phone);
    
    // Convert to international format
    if (substr($phone, 0, 1) === '0') {
        $phone = '254' . substr($phone, 1);
    } elseif (substr($phone, 0, 3) !== '254') {
        $phone = '254' . $phone;
    }
    
    return '+' . $phone;
}

/**
 * Update department statistics
 */
function updateDepartmentStats($conn, $department_id) {
    $today = date('Y-m-d');
    $current_hour = date('G');
    
    // Calculate statistics for today
    $stats_sql = "SELECT 
        COUNT(*) as total_patients,
        COUNT(CASE WHEN queue_status = 'WAITING' THEN 1 END) as waiting,
        COUNT(CASE WHEN queue_status = 'IN_SERVICE' THEN 1 END) as in_service,
        COUNT(CASE WHEN queue_status = 'COMPLETED' THEN 1 END) as completed,
        COUNT(CASE WHEN queue_status = 'CANCELLED' THEN 1 END) as cancelled,
        COUNT(CASE WHEN queue_status = 'NO_SHOW' THEN 1 END) as no_show,
        AVG(total_wait_minutes) as avg_wait,
        MAX(total_wait_minutes) as max_wait,
        MIN(total_wait_minutes) as min_wait,
        AVG(total_service_minutes) as avg_service,
        MAX(total_service_minutes) as max_service,
        COUNT(CASE WHEN priority = 'EMERGENCY' THEN 1 END) as emergency_count,
        COUNT(CASE WHEN priority = 'URGENT' THEN 1 END) as urgent_count,
        COUNT(CASE WHEN priority = 'NORMAL' THEN 1 END) as normal_count
    FROM patient_queue
    WHERE department_id = ?
    AND DATE(queue_entry_time) = ?";
    
    $stmt = $conn->prepare($stats_sql);
    $stmt->bind_param("is", $department_id, $today);
    $stmt->execute();
    $stats = $stmt->get_result()->fetch_assoc();
    
    // Insert or update statistics
    $upsert_sql = "INSERT INTO queue_statistics (
        department_id, stat_date, stat_hour,
        total_patients, patients_waiting, patients_in_service, patients_completed,
        patients_cancelled, patients_no_show,
        avg_wait_minutes, max_wait_minutes, min_wait_minutes,
        avg_service_minutes, max_service_minutes,
        emergency_count, urgent_count, normal_count
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE
        total_patients = VALUES(total_patients),
        patients_waiting = VALUES(patients_waiting),
        patients_in_service = VALUES(patients_in_service),
        patients_completed = VALUES(patients_completed),
        patients_cancelled = VALUES(patients_cancelled),
        patients_no_show = VALUES(patients_no_show),
        avg_wait_minutes = VALUES(avg_wait_minutes),
        max_wait_minutes = VALUES(max_wait_minutes),
        min_wait_minutes = VALUES(min_wait_minutes),
        avg_service_minutes = VALUES(avg_service_minutes),
        max_service_minutes = VALUES(max_service_minutes),
        emergency_count = VALUES(emergency_count),
        urgent_count = VALUES(urgent_count),
        normal_count = VALUES(normal_count),
        updated_at = NOW()";
    
    $stmt = $conn->prepare($upsert_sql);
    $stmt->bind_param("isiiiiiiiiiiiiii",
        $department_id, $today, $current_hour,
        $stats['total_patients'], $stats['waiting'], $stats['in_service'], $stats['completed'],
        $stats['cancelled'], $stats['no_show'],
        $stats['avg_wait'], $stats['max_wait'], $stats['min_wait'],
        $stats['avg_service'], $stats['max_service'],
        $stats['emergency_count'], $stats['urgent_count'], $stats['normal_count']
    );
    $stmt->execute();
}
?>