<?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'];
        }
    }

    // ✅ FIXED: Generate visit number using SQL (not stored function)
    $visit_number_sql = "SELECT CONCAT('VISIT-', DATE_FORMAT(NOW(), '%Y%m%d'), '-', 
                         LPAD(COALESCE(MAX(CAST(SUBSTRING(visit_number, -3) AS UNSIGNED)), 0) + 1, 3, '0')) as new_number
                         FROM patient_visits 
                         WHERE visit_number LIKE CONCAT('VISIT-', DATE_FORMAT(NOW(), '%Y%m%d'), '%')";
    $visit_number_result = $conn->query($visit_number_sql);
    $visit_row = $visit_number_result->fetch_assoc();
    $visit_number = $visit_row['new_number'];

    // ✅ FIXED: Create a visit record with valid ENUM value 'WALK_IN' instead of 'CASH'
    // Valid registration_type values: 'WALK_IN','INSURANCE','PRO_BONO','CORPORATE','REFERRAL','ONLINE'
    $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', 
                           'WALK_IN', '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");
        }
    }

    // ✅ FIXED: Create invoice with patient_portion (required field, NOT NULL)
    $invoice_number = 'INV-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);

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

    $stmt = $conn->prepare($invoice_sql);
    // For walk-in patients, patient_portion = total_amount
    $stmt->bind_param('siiddddi', $invoice_number, $visit_id, $patient_id, 
                      $total_cost, $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);
?>