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

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

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

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

$patient_id = intval($_POST['patient_id']);
$test_types = isset($_POST['test_types']) ? $_POST['test_types'] : [];
$notes = mysqli_real_escape_string($conn, $_POST['notes'] ?? '');
$ordered_by = $_SESSION['user_id'];

if (empty($test_types)) {
    echo json_encode(['success' => false, 'message' => 'Please select at least one test']);
    exit();
}

mysqli_begin_transaction($conn);

try {
    // Generate order number
    $order_number = 'AUD-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);

    // Calculate total cost
    $total_cost = 0;
    $test_costs = [];

    foreach ($test_types as $test_type_id) {
        $cost_query = "SELECT cost FROM ent_test_types WHERE test_type_id = ?";
        $stmt = $conn->prepare($cost_query);
        $stmt->bind_param('i', $test_type_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $test = $result->fetch_assoc();

        if ($test) {
            $test_costs[$test_type_id] = $test['cost'];
            $total_cost += $test['cost'];
        }
    }

    // Generate visit number using stored function
    $visit_number_sql = "SELECT GenerateVisitNumber() as visit_number";
    $visit_number_result = $conn->query($visit_number_sql);
    $visit_row = $visit_number_result->fetch_assoc();
    $visit_number = $visit_row['visit_number'];

    // Create a visit record
    // We create a new PROCEDURE visit for this test order
    $visit_sql = "INSERT INTO patient_visits (
                    visit_number, patient_id, visit_type, visit_source,
                    registration_type, status, priority, 
                    total_amount, patient_portion, balance,
                    registered_by, registration_date, created_at
                  ) VALUES (?, ?, 'PROCEDURE', 'WALK_IN', 
                           'CASH', 'REGISTERED', 'NORMAL', 
                           ?, ?, ?,
                           ?, CURDATE(), NOW())";

    $stmt = $conn->prepare($visit_sql);
    $stmt->bind_param('sidddi', $visit_number, $patient_id, $total_cost, $total_cost, $total_cost, $ordered_by);
    $stmt->execute();
    $visit_id = $conn->insert_id;

    // Insert lab order
    $order_sql = "INSERT INTO lab_orders (
                    order_number, visit_id, patient_id, order_date, ordered_by,
                    order_type, priority, status, total_cost, paid_amount,
                    clinical_notes, ordered_at
                  ) VALUES (?, ?, ?, CURDATE(), ?, 'AUDIOMETRY', 'ROUTINE', 'PENDING', ?, 0, ?, NOW())";

    $stmt = $conn->prepare($order_sql);
    $stmt->bind_param('siiids', $order_number, $visit_id, $patient_id, $ordered_by, $total_cost, $notes);

    if (!$stmt->execute()) {
        throw new Exception("Failed to create order");
    }

    $order_id = $conn->insert_id;

    // Insert individual tests
    foreach ($test_types as $test_type_id) {
        $test_sql = "INSERT INTO lab_order_tests (
                        order_id, test_type_id, test_cost, status, created_at
                     ) VALUES (?, ?, ?, 'PENDING', NOW())";

        $stmt = $conn->prepare($test_sql);
        $test_cost = $test_costs[$test_type_id];
        $stmt->bind_param('iid', $order_id, $test_type_id, $test_cost);

        if (!$stmt->execute()) {
            throw new Exception("Failed to add test to order");
        }
    }

    // Create invoice for the order
    $invoice_number = 'INV-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);

    $invoice_sql = "INSERT INTO invoices (
                        invoice_number, patient_id, invoice_date, due_date,
                        subtotal, tax_amount, discount_amount, total_amount,
                        amount_paid, balance, status,
                        created_by, created_at
                    ) VALUES (?, ?, NOW(), DATE_ADD(NOW(), INTERVAL 7 DAY), ?, 0, 0, ?, 0, ?, 
                              'UNPAID', ?, NOW())";

    $stmt = $conn->prepare($invoice_sql);
    $stmt->bind_param('sidddi', $invoice_number, $patient_id, $total_cost, $total_cost, $total_cost, $ordered_by);

    if (!$stmt->execute()) {
        throw new Exception("Failed to create invoice");
    }

    $invoice_id = $conn->insert_id;

    // Add invoice items
    foreach ($test_types as $test_type_id) {
        $test_info_query = "SELECT test_name, test_code FROM ent_test_types WHERE test_type_id = ?";
        $stmt = $conn->prepare($test_info_query);
        $stmt->bind_param('i', $test_type_id);
        $stmt->execute();
        $test_info = $stmt->get_result()->fetch_assoc();

        $item_sql = "INSERT INTO invoice_items (
                        invoice_id, item_type, reference_id, description, quantity,
                        unit_price, total_price, created_at
                     ) VALUES (?, 'TEST', ?, ?, 1, ?, ?, NOW())";

        $stmt = $conn->prepare($item_sql);
        $description = $test_info['test_name'] . ' (' . $test_info['test_code'] . ')';
        $unit_price = $test_costs[$test_type_id];
        $total_price = $unit_price;

        $stmt->bind_param('iisdd', $invoice_id, $test_type_id, $description, $unit_price, $total_price);
        $stmt->execute();
    }

    // Link invoice to lab order
    $link_sql = "UPDATE lab_orders SET invoice_id = ? WHERE order_id = ?";
    $stmt = $conn->prepare($link_sql);
    $stmt->bind_param('ii', $invoice_id, $order_id);
    $stmt->execute();

    // Manual accounting entry removed to rely on system triggers (CreateInvoiceEntry -> PostJournalToLedger)

    // Log activity
    $log_sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, created_at)
                VALUES (?, 'CREATE', 'LAB_ORDER', ?, ?, ?, NOW())";
    $stmt = $conn->prepare($log_sql);
    $description = "Created audiometry test order: " . $order_number;
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $stmt->bind_param('iiss', $ordered_by, $order_id, $description, $ip_address);
    $stmt->execute();

    mysqli_commit($conn);

    echo json_encode([
        'success' => true,
        'message' => 'Test order created successfully',
        'order_id' => $order_id,
        'order_number' => $order_number,
        'invoice_id' => $invoice_id,
        'invoice_number' => $invoice_number,
        'total_cost' => $total_cost
    ]);

} catch (Exception $e) {
    mysqli_rollback($conn);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

mysqli_close($conn);
?>