<?php
/**
 * File 5: ajax/complete_service.php
 * Complete service and route to billing
 */
session_start();
include '../layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    $_SESSION['error_message'] = 'Unauthorized';
    header('Location: ../queue_dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$queue_id = $_GET['queue_id'] ?? 0;
$patient_id = $_GET['patient_id'] ?? 0;

if (!$queue_id || !$patient_id) {
    $_SESSION['error_message'] = 'Invalid parameters';
    header('Location: ../queue_dashboard.php');
    exit();
}

try {
    $conn->begin_transaction();
    
    // Get current queue data
    $queue_sql = "SELECT * FROM patient_queue WHERE queue_id = ?";
    $stmt = $conn->prepare($queue_sql);
    $stmt->bind_param("i", $queue_id);
    $stmt->execute();
    $queue_result = $stmt->get_result();
    
    if ($queue_result->num_rows === 0) {
        throw new Exception("Queue record not found");
    }
    
    $queue_data = $queue_result->fetch_assoc();
    
    // Complete current service
    $update_sql = "UPDATE patient_queue 
                  SET queue_status = 'COMPLETED',
                      service_end_time = NOW(),
                      total_service_minutes = TIMESTAMPDIFF(MINUTE, COALESCE(service_start_time, queue_entry_time), NOW()),
                      updated_by = ?
                  WHERE queue_id = ?";
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("ii", $user_id, $queue_id);
    $stmt->execute();
    
    // Get billing department
    $billing_dept_sql = "SELECT department_id, department_code FROM departments WHERE department_code = 'BILLING' AND is_active = 1";
    $billing_result = $conn->query($billing_dept_sql);
    
    if ($billing_result && $billing_result->num_rows > 0) {
        $billing_dept = $billing_result->fetch_assoc();
        
        // Generate new queue number for billing
        $queue_number_sql = "SELECT GenerateQueueNumber(?) as queue_number";
        $stmt = $conn->prepare($queue_number_sql);
        $dept_code = $billing_dept['department_code'];
        $stmt->bind_param("s", $dept_code);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result && $result->num_rows > 0) {
            $billing_queue_number = $result->fetch_assoc()['queue_number'];
            
            // Add to billing queue
            $billing_sql = "INSERT INTO patient_queue (
                queue_number, patient_id, visit_id, department_id,
                queue_status, priority, registration_type,
                patient_name, patient_number, phone_number, age, gender,
                service_type, chief_complaint, previous_department_id,
                transfer_reason, referred_by, is_vip, notification_preference, created_by
            ) VALUES (?, ?, ?, ?, 'WAITING', 'NORMAL', ?, ?, ?, ?, ?, ?, 'Payment Processing', 'Service completed', ?, 'Billing', ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($billing_sql);
            $stmt->bind_param("siiisssssisiiisi",
                $billing_queue_number, 
                $queue_data['patient_id'], 
                $queue_data['visit_id'],
                $billing_dept['department_id'], 
                $queue_data['registration_type'],
                $queue_data['patient_name'], 
                $queue_data['patient_number'], 
                $queue_data['phone_number'],
                $queue_data['age'], 
                $queue_data['gender'],
                $queue_data['department_id'], 
                $user_id, 
                $queue_data['is_vip'],
                $queue_data['notification_preference'], 
                $user_id
            );
            $stmt->execute();
            
            // Update positions
            $conn->query("CALL UpdateQueuePositions(" . $billing_dept['department_id'] . ")");
            $conn->query("CALL UpdateQueueWaitTimes(" . $billing_dept['department_id'] . ")");
        }
    }
    
    // Update queue positions for current department
    if (isset($queue_data['department_id'])) {
        $conn->query("CALL UpdateQueuePositions(" . $queue_data['department_id'] . ")");
    }
    
    // Log activity
    $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, ip_address, logged_at)
                    VALUES (?, 'COMPLETE', 'QUEUE', ?, 'QUEUE', ?, NOW())";
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $stmt = $conn->prepare($activity_sql);
    $stmt->bind_param("iis", $user_id, $queue_id, $ip_address);
    $stmt->execute();
    
    $conn->commit();
    
    $_SESSION['success_message'] = 'Service completed and patient routed to billing';
    header('Location: ../queue_dashboard.php');
    
} catch (Exception $e) {
    $conn->rollback();
    $_SESSION['error_message'] = 'Failed to complete service: ' . $e->getMessage();
    header('Location: ../view_patient.php?id=' . $patient_id . '&queue_id=' . $queue_id);
}
?>