<?php
session_start();
require_once dirname(__DIR__, 2) . '/includes/db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
    exit();
}

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

if (empty($data['visit_id']) || empty($data['requests'])) {
    echo json_encode(['status' => 'error', 'message' => 'Payload missing visit ID or items.']);
    exit();
}

$visit_id = intval($data['visit_id']);
$patient_no = $conn->real_escape_string($data['patient_no']);
$requests = $data['requests'];
$doctor_id = $_SESSION['staff_id'] ?? 1;

// 1. Transaction Start - Ensures atomicity
$conn->begin_transaction();

try {
    // 2. Prepare lookup from Service Catalog
    // We grab workflow_profile_id to know WHERE it goes, and cash_price_adult to know HOW MUCH it costs.
    $stmtCatalog = $conn->prepare("SELECT workflow_profile_id, cash_price_adult, service_type FROM service_catalog WHERE id = ?");
    
    // 3. Prepare Queue Insertion (The New Dynamic Engine)
    $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) 
        VALUES (?, ?, ?, ?, ?, ?, ?, 'Unpaid', 'Pending Payment')");

    // 4. Prepare Billing Insertion
    $stmtBilling = $conn->prepare("INSERT INTO visit_details 
        (visit_master_id, service_id, quantity, billed_amount, is_consultation, status) 
        VALUES (?, ?, 1, ?, ?, 'Pending')");

    foreach ($requests as $item) {
        $service_id = intval($item['service_id']);
        $priority = $conn->real_escape_string($item['priority']);
        $notes = $conn->real_escape_string($item['notes']);

        // Look up catalog data for this specific service
        $stmtCatalog->bind_param("i", $service_id);
        $stmtCatalog->execute();
        $catResult = $stmtCatalog->get_result();
        
        if ($catRow = $catResult->fetch_assoc()) {
            
            // If the item doesn't have a workflow profile assigned yet, default to 1 (or handle via DB constraint)
            $workflow_id = $catRow['workflow_profile_id'] ? $catRow['workflow_profile_id'] : 1; 
            $price = $catRow['cash_price_adult']; 
            $is_consultation = ($catRow['service_type'] == 'Consultation') ? 1 : 0;
            
            // Execute Route to Queue
            $stmtQueue->bind_param("isiisss", $visit_id, $patient_no, $service_id, $workflow_id, $doctor_id, $notes, $priority);
            if (!$stmtQueue->execute()) {
                throw new Exception("Queue insert failed: " . $stmtQueue->error);
            }

            // Execute Route to Billing
            $stmtBilling->bind_param("iidi", $visit_id, $service_id, $price, $is_consultation);
            if (!$stmtBilling->execute()) {
                 throw new Exception("Billing insert failed: " . $stmtBilling->error);
            }
        }
    }

    // If loop completes without throwing errors, save to database
    $conn->commit();
    echo json_encode(['status' => 'success']);

} catch (Exception $e) {
    // If anything fails, rollback everything so we don't get orphan records
    $conn->rollback();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}

// Clean up
$stmtCatalog->close();
$stmtQueue->close();
$stmtBilling->close();
$conn->close();
?>