<?php
session_start();
require_once $_SERVER['DOCUMENT_ROOT'] . '/rimax/application/dripend/includes/db.php';
header('Content-Type: application/json');

$json_input = file_get_contents("php://input");
$data = json_decode($json_input, true);

if (!isset($data['patient_no']) || empty($data['orders'])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid or empty request data.']);
    exit;
}

$patient_no = trim($data['patient_no']);
$visit_id = isset($data['visit_id']) && intval($data['visit_id']) > 0 ? intval($data['visit_id']) : null;
$payment_cat = isset($data['payment_category']) ? trim($data['payment_category']) : 'Cash';
$ccc_code = isset($data['ccc_code']) ? trim($data['ccc_code']) : NULL;

$insurance_id = isset($data['insurance_id']) && intval($data['insurance_id']) > 0 ? intval($data['insurance_id']) : NULL;
$corp_no = isset($data['corp_no']) ? trim($data['corp_no']) : NULL;

// ---------------------------------------------------------
// DYNAMIC STAFF FALLBACK LOGIC (Prevents FK_LAB_DOC Error)
// ---------------------------------------------------------
$doctor_id = isset($_SESSION['staff_id']) ? intval($_SESSION['staff_id']) : 0; 
$staff_name = isset($_SESSION['staff_name']) ? $_SESSION['staff_name'] : 'System Admin';
$ip_addr = $_SERVER['REMOTE_ADDR'];

// If no session exists, dynamically fetch an active staff ID from the database to satisfy the foreign key
if ($doctor_id === 0) {
    $resStaff = $conn->query("SELECT staff_id, first_name, last_name FROM staff WHERE is_active = 1 LIMIT 1");
    if ($resStaff && $resStaff->num_rows > 0) {
        $rowStaff = $resStaff->fetch_assoc();
        $doctor_id = intval($rowStaff['staff_id']);
        $staff_name = trim($rowStaff['first_name'] . ' ' . $rowStaff['last_name']);
    } else {
        $doctor_id = 4; // Absolute fallback to match your existing DB structure
    }
}

$orders = $data['orders'];
$conn->begin_transaction();

try {
    // 1. Walk-in Mode: Create Visit Session
    if (!$visit_id) {
        $appt_no = 'DIA-' . date('Ymd') . '-' . rand(1000, 9999);
        $stmtVisit = $conn->prepare("
            INSERT INTO visit_master 
            (appointment_no, patient_no, visit_date, visit_time, payment_category, ccc_code, nhis_service_type, billing_structure, status, attendance_type, specialty_code, visit_number, total_billed) 
            VALUES (?, ?, CURDATE(), CURTIME(), ?, ?, 'Diagnostic', 'Unbundled', 'Pending', 'EAE', 'DIAG', 1, 0.00)
        ");
        $stmtVisit->bind_param("ssss", $appt_no, $patient_no, $payment_cat, $ccc_code);
        if (!$stmtVisit->execute()) { throw new Exception("Failed to generate Diagnostic Visit."); }
        $visit_id = $conn->insert_id;
        $stmtVisit->close();
    }

    // 2. Update Patient Corporate Insurance Record if provided
    if ($payment_cat === 'Corporate' && !empty($insurance_id) && !empty($corp_no)) {
        $stmtPatUpdate = $conn->prepare("UPDATE patient SET other_insurance_id = ?, other_insurance_no = ? WHERE patient_no = ?");
        $stmtPatUpdate->bind_param("iss", $insurance_id, $corp_no, $patient_no);
        $stmtPatUpdate->execute();
        $stmtPatUpdate->close();
    }

    // 3. Prepare Core Central Trackers
    $stmtQueue = $conn->prepare("
        INSERT INTO service_request_queue 
        (visit_id, patient_no, service_id, workflow_profile_id, requested_by, clinical_notes, priority, payment_status, current_stage, request_date) 
        VALUES (?, ?, ?, (SELECT workflow_profile_id FROM service_catalog WHERE id = ?), ?, ?, ?, 'Unpaid', 'Pending Payment', NOW())
    ");

    $stmtBill = $conn->prepare("
        INSERT INTO visit_details 
        (visit_master_id, service_id, quantity, billed_amount, is_consultation, status) 
        VALUES (?, ?, 1, ?, 0, 'Pending')
    ");

    // 4. Prepare Departmental Dispatchers
    $stmtCatalog = $conn->prepare("SELECT department_id, service_name, service_type FROM service_catalog WHERE id = ?");
    
    $stmtLab = $conn->prepare("
        INSERT INTO clinical_lab_requests 
        (visit_id, patient_no, department_id, service_id, test_name, status, requested_by, priority, notes) 
        VALUES (?, ?, ?, ?, ?, 'Pending', ?, ?, ?)
    ");

    $stmtRx = $conn->prepare("
        INSERT INTO clinical_prescriptions 
        (visit_id, patient_no, service_id, drug_name, status, prescribed_by) 
        VALUES (?, ?, ?, ?, 'Pending Pharmacy', ?)
    ");

    if (!$stmtQueue || !$stmtBill || !$stmtCatalog || !$stmtLab || !$stmtRx) {
        throw new Exception("System Error: Failed to prepare routing statements.");
    }

    $total_cart_bill = 0.00;

    foreach ($orders as $item) {
        $service_id = intval($item['id']);
        $notes = trim($item['notes']);
        $priority = trim($item['priority']);
        $billed_amount = floatval($item['price']); 

        $total_cart_bill += $billed_amount;

        // Insert into Central Queue
        $stmtQueue->bind_param("isiisss", $visit_id, $patient_no, $service_id, $service_id, $doctor_id, $notes, $priority);
        if (!$stmtQueue->execute()) { throw new Exception("Queue Insertion Failed."); }

        // Insert into Billing
        $stmtBill->bind_param("iid", $visit_id, $service_id, $billed_amount);
        if (!$stmtBill->execute()) { throw new Exception("Billing Insertion Failed."); }

        // Departmental Dispatcher
        $stmtCatalog->bind_param("i", $service_id);
        $stmtCatalog->execute();
        $catRes = $stmtCatalog->get_result();
        
        if ($catRow = $catRes->fetch_assoc()) {
            $dept_id = intval($catRow['department_id']);
            $service_name = $catRow['service_name'];
            $service_type = $catRow['service_type'];

            // Route directly to Laboratory (Department ID 8 or Investigation type)
            if ($dept_id === 8 || stripos($service_type, 'Investigation') !== false) {
                $stmtLab->bind_param("isiisiss", $visit_id, $patient_no, $dept_id, $service_id, $service_name, $doctor_id, $priority, $notes);
                $stmtLab->execute();
            }
            // Route directly to Pharmacy (Department ID 14, 15 or Drug type)
            elseif ($service_type === 'Drug' || $dept_id === 14 || $dept_id === 15) {
                $stmtRx->bind_param("isisi", $visit_id, $patient_no, $service_id, $service_name, $doctor_id);
                $stmtRx->execute();
            }
        }
    }

    // 5. Update Total Bill & Audit
    $stmtUpdateBill = $conn->prepare("UPDATE visit_master SET total_billed = total_billed + ? WHERE id = ?");
    $stmtUpdateBill->bind_param("di", $total_cart_bill, $visit_id);
    $stmtUpdateBill->execute();
    $stmtUpdateBill->close();

    $audit_record_id = "VISIT-" . $visit_id;
    $audit_data = json_encode([
        'patient_no' => $patient_no,
        'visit_id' => $visit_id,
        'total_billed_amount' => $total_cart_bill,
        'services_requested' => count($orders),
        'saved_by_name' => $staff_name
    ]);
    
    $stmtAudit = $conn->prepare("
        INSERT INTO system_audit_logs 
        (staff_id, action_type, table_name, record_id, new_values, ip_address) 
        VALUES (?, 'INSERT', 'service_request_queue', ?, ?, ?)
    ");
    $stmtAudit->bind_param("isss", $doctor_id, $audit_record_id, $audit_data, $ip_addr);
    $stmtAudit->execute();
    $stmtAudit->close();

    $conn->commit();
    echo json_encode(['status' => 'success', 'message' => 'Orders successfully routed to departments and billed.']);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}

if(isset($stmtQueue)) $stmtQueue->close();
if(isset($stmtBill)) $stmtBill->close();
if(isset($stmtCatalog)) $stmtCatalog->close();
if(isset($stmtLab)) $stmtLab->close();
if(isset($stmtRx)) $stmtRx->close();
$conn->close();
?>