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

header('Content-Type: application/json');

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

$user_id = $_SESSION['user_id'];

// Get form data
$patient_id = intval($_POST['patient_id'] ?? 0);
$department_id = intval($_POST['department_id'] ?? 0);
$priority = $_POST['priority'] ?? 'NORMAL';
$service_type = trim($_POST['service_type'] ?? '');
$chief_complaint = trim($_POST['chief_complaint'] ?? '');
$special_needs = trim($_POST['special_needs'] ?? '');
$has_appointment = intval($_POST['has_appointment'] ?? 0);

// Validate required fields
if ($patient_id === 0 || $department_id === 0) {
    echo json_encode(['success' => false, 'message' => 'Patient and department are required']);
    exit();
}

// Validate priority
if (!in_array($priority, ['NORMAL', 'URGENT', 'EMERGENCY'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid priority level']);
    exit();
}

// Check if patient exists and get details
$patient_sql = "SELECT 
    p.patient_id,
    p.patient_number,
    p.registration_type,
    u.full_name,
    u.phone_primary,
    u.gender,
    u.date_of_birth,
    TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as age
FROM patients p
INNER JOIN users u ON p.user_id = u.user_id
WHERE p.patient_id = ? AND p.is_active = 1 AND u.status = 'ACTIVE'";

$stmt = $conn->prepare($patient_sql);
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
    exit();
}

$stmt->bind_param('i', $patient_id);
$stmt->execute();
$patient_result = $stmt->get_result();

if ($patient_result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Patient not found']);
    exit();
}

$patient = $patient_result->fetch_assoc();
$stmt->close();

// Check if department exists and get details
$dept_sql = "SELECT department_code, department_name FROM departments WHERE department_id = ? AND is_active = 1";
$stmt = $conn->prepare($dept_sql);
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
    exit();
}

$stmt->bind_param('i', $department_id);
$stmt->execute();
$dept_result = $stmt->get_result();

if ($dept_result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Department not found']);
    exit();
}

$department = $dept_result->fetch_assoc();
$stmt->close();

// Check if patient is already in queue for this department today
$check_sql = "SELECT queue_id FROM patient_queue 
              WHERE patient_id = ? 
              AND department_id = ? 
              AND DATE(queue_entry_time) = CURDATE()
              AND queue_status IN ('WAITING', 'IN_SERVICE')";
$stmt = $conn->prepare($check_sql);
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
    exit();
}

$stmt->bind_param('ii', $patient_id, $department_id);
$stmt->execute();
$check_result = $stmt->get_result();

if ($check_result->num_rows > 0) {
    echo json_encode(['success' => false, 'message' => 'Patient is already in queue for this department today']);
    exit();
}
$stmt->close();

// Begin transaction
$conn->begin_transaction();

try {
    // Generate queue number: DEPT-YYYYMMDD-SEQ
    $date_str = date('Ymd');
    $seq_sql = "SELECT COUNT(*) as count FROM patient_queue 
                WHERE department_id = ? AND DATE(queue_entry_time) = CURDATE()";
    $stmt = $conn->prepare($seq_sql);
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }
    
    $stmt->bind_param('i', $department_id);
    $stmt->execute();
    $seq_result = $stmt->get_result();
    $seq_row = $seq_result->fetch_assoc();
    $sequence = str_pad($seq_row['count'] + 1, 3, '0', STR_PAD_LEFT);
    $queue_number = $department['department_code'] . '-' . $date_str . '-' . $sequence;
    $stmt->close();
    
    // Insert into patient_queue - aligned with schema
    $insert_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,
        special_needs,
        has_appointment,
        is_vip,
        vitals_taken,
        notification_preference,
        created_by,
        created_at
    ) VALUES (?, ?, NULL, ?, 'WAITING', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, 'SMS', ?, NOW())";
    
    $stmt = $conn->prepare($insert_sql);
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }
    
    // Use phone_primary from patient data, but store as phone_number in queue
    $phone_number = $patient['phone_primary'] ?? '';
    
    $stmt->bind_param(
        'siissssssisssii',
        $queue_number,
        $patient_id,
        $department_id,
        $priority,
        $patient['registration_type'],
        $patient['full_name'],
        $patient['patient_number'],
        $phone_number,
        $patient['age'],
        $patient['gender'],
        $service_type,
        $chief_complaint,
        $special_needs,
        $has_appointment,
        $user_id
    );
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to add patient to queue: ' . $stmt->error);
    }
    
    $queue_id = $conn->insert_id;
    $stmt->close();
    
    // Update queue positions and wait times using stored procedures
    $conn->query("CALL UpdateQueuePositions($department_id)");
    $conn->query("CALL UpdateQueueWaitTimes($department_id)");
    
    // Get the updated position and estimated wait time
    $position_sql = "SELECT position_in_queue, estimated_wait_minutes 
                     FROM patient_queue 
                     WHERE queue_id = ?";
    $stmt = $conn->prepare($position_sql);
    $stmt->bind_param('i', $queue_id);
    $stmt->execute();
    $position_result = $stmt->get_result();
    $position_data = $position_result->fetch_assoc();
    $position = $position_data['position_in_queue'] ?? 1;
    $estimated_wait = $position_data['estimated_wait_minutes'] ?? 0;
    $stmt->close();
    
    // Log in queue history (if table exists)
    $history_sql = "INSERT INTO queue_history (
        queue_id,
        patient_id,
        department_id,
        department_name,
        action,
        from_status,
        to_status,
        queue_position,
        performed_by,
        performed_by_name,
        notes
    ) SELECT 
        ?,
        ?,
        ?,
        ?,
        'QUEUED',
        NULL,
        'WAITING',
        ?,
        ?,
        u.full_name,
        'Patient added to queue manually'
    FROM users u
    WHERE u.user_id = ?";
    
    $stmt = $conn->prepare($history_sql);
    if ($stmt) {
        $stmt->bind_param(
            'iiisiii',
            $queue_id,
            $patient_id,
            $department_id,
            $department['department_name'],
            $position,
            $user_id,
            $user_id
        );
        $stmt->execute(); // Don't throw error if history table doesn't exist
        $stmt->close();
    }
    
    // Commit transaction
    $conn->commit();
    
    // Send SMS notification (optional - can be implemented later)
    // sendQueueNotification($phone_number, $queue_number, $department['department_name'], $position);
    
    echo json_encode([
        'success' => true,
        'message' => 'Patient added to queue successfully',
        'data' => [
            'queue_id' => $queue_id,
            'queue_number' => $queue_number,
            'patient_name' => $patient['full_name'],
            'department' => $department['department_name'],
            'position' => $position,
            'estimated_wait' => $estimated_wait
        ]
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    error_log("Add to queue error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}

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