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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit();
}

$user_id = $_SESSION['user_id'];

// Get form data
$patient_id = $_POST['patient_id'] ?? null;
$department_id = $_POST['department_id'] ?? null;
$priority = $_POST['priority'] ?? 'NORMAL';
$service_type = $_POST['service_type'] ?? '';
$chief_complaint = $_POST['chief_complaint'] ?? '';

if (!$patient_id || !$department_id) {
    echo json_encode(['success' => false, 'message' => 'Patient and Department are required']);
    exit();
}

try {
    $conn->begin_transaction();
    
    // Get patient details
    $patient_sql = "SELECT 
        p.patient_id,
        p.patient_number,
        u.full_name as patient_name,
        u.phone_number,
        u.date_of_birth,
        TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as age,
        u.gender,
        p.registration_type
    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", $patient_id);
    $stmt->execute();
    $patient = $stmt->get_result()->fetch_assoc();
    
    if (!$patient) {
        throw new Exception('Patient not found');
    }
    
    // Get department info
    $dept_sql = "SELECT department_code FROM departments WHERE department_id = ?";
    $stmt_dept = $conn->prepare($dept_sql);
    $stmt_dept->bind_param("i", $department_id);
    $stmt_dept->execute();
    $dept = $stmt_dept->get_result()->fetch_assoc();
    
    if (!$dept) {
        throw new Exception('Department not found');
    }
    
    // Check if patient already in queue today
    $check_sql = "SELECT queue_id FROM patient_queue 
                  WHERE patient_id = ? 
                  AND DATE(queue_entry_time) = CURDATE()
                  AND queue_status IN ('WAITING', 'IN_SERVICE')";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("i", $patient_id);
    $check_stmt->execute();
    $existing = $check_stmt->get_result()->fetch_assoc();
    
    if ($existing) {
        throw new Exception('Patient is already in queue today');
    }
    
    // Generate queue number
    $queue_number_prefix = $dept['department_code'] . '-' . date('Ymd');
    $seq_sql = "SELECT COUNT(*) + 1 as seq 
                FROM patient_queue 
                WHERE queue_number LIKE ? 
                AND DATE(queue_entry_time) = CURDATE()";
    $stmt_seq = $conn->prepare($seq_sql);
    $prefix_like = $queue_number_prefix . '%';
    $stmt_seq->bind_param("s", $prefix_like);
    $stmt_seq->execute();
    $seq_result = $stmt_seq->get_result()->fetch_assoc();
    $queue_number = $queue_number_prefix . '-' . str_pad($seq_result['seq'], 3, '0', STR_PAD_LEFT);
    
    // Calculate position in queue
    $position_sql = "SELECT COUNT(*) + 1 as position 
                    FROM patient_queue 
                    WHERE department_id = ? 
                    AND queue_status = 'WAITING'
                    AND DATE(queue_entry_time) = CURDATE()";
    $stmt_pos = $conn->prepare($position_sql);
    $stmt_pos->bind_param("i", $department_id);
    $stmt_pos->execute();
    $position_result = $stmt_pos->get_result()->fetch_assoc();
    
    // Insert into queue
    $insert_sql = "INSERT INTO patient_queue (
        queue_number,
        patient_id,
        department_id,
        queue_status,
        priority,
        registration_type,
        patient_name,
        patient_number,
        phone_number,
        age,
        gender,
        service_type,
        chief_complaint,
        position_in_queue,
        created_by,
        arrival_time,
        queue_entry_time
    ) VALUES (?, ?, ?, 'WAITING', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
    
    $stmt_insert = $conn->prepare($insert_sql);
    $stmt_insert->bind_param(
        "siisssssissi",
        $queue_number,
        $patient_id,
        $department_id,
        $priority,
        $patient['registration_type'],
        $patient['patient_name'],
        $patient['patient_number'],
        $patient['phone_number'],
        $patient['age'],
        $patient['gender'],
        $service_type,
        $chief_complaint,
        $position_result['position'],
        $user_id
    );
    
    if (!$stmt_insert->execute()) {
        throw new Exception('Failed to add patient to queue');
    }
    
    $queue_id = $conn->insert_id;
    
    // Log activity
    $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, details, ip_address) 
                     VALUES (?, 'ADD_TO_QUEUE', 'QUEUE', ?, ?, ?)";
    $stmt_log = $conn->prepare($activity_sql);
    $details = "Added patient {$patient['patient_name']} to queue";
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $stmt_log->bind_param("iiss", $user_id, $queue_id, $details, $ip_address);
    $stmt_log->execute();
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Patient successfully added to queue',
        'queue_number' => $queue_number,
        'queue_id' => $queue_id
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>