<?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 imaging study']);
    exit();
}

mysqli_begin_transaction($conn);

try {
    // Generate order number
    $order_number = 'IMG-' . 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 = ? AND category = 'RADIOLOGY'";
        $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'];
        }
    }

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

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

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

    $order_id = $conn->insert_id;

    // Insert individual imaging studies
    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 imaging study 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, invoice_type,
                        created_by, created_at
                    ) VALUES (?, ?, NOW(), DATE_ADD(NOW(), INTERVAL 7 DAY), ?, 0, 0, ?, 0, ?, 
                              'UNPAID', 'IMAGING', ?, 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, item_description, quantity,
                        unit_price, subtotal, tax_amount, discount_amount,
                        line_total, created_at
                     ) VALUES (?, 'IMAGING', ?, 1, ?, ?, 0, 0, ?, NOW())";

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

        $stmt->bind_param('isddd', $invoice_id, $item_description, $unit_price, $unit_price, $unit_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();

    // Create accounting entries
    $fiscal_year = date('Y');
    $fiscal_period = date('n');
    $journal_number = 'JE-' . date('YmdHis');

    // Debit: Accounts Receivable
    $ar_entry_sql = "INSERT INTO account_ledger (
                        account_id, transaction_date, journal_number, description,
                        debit_amount, credit_amount, fiscal_year, fiscal_period,
                        entry_type, reference_type, reference_id, created_by, created_at
                    ) VALUES (
                        (SELECT account_id FROM chart_of_accounts WHERE account_code = '1200' LIMIT 1),
                        CURDATE(), ?, ?, ?, 0, ?, ?, 
                        'AUTO_INVOICE', 'INVOICE', ?, ?, NOW()
                    )";

    $stmt = $conn->prepare($ar_entry_sql);
    $description = 'Imaging studies - Invoice #' . $invoice_number;
    $stmt->bind_param('sdiii', $journal_number, $description, $total_cost, $fiscal_year, $fiscal_period, $invoice_id, $ordered_by);
    $stmt->execute();

    // Credit: Imaging Revenue
    $revenue_entry_sql = "INSERT INTO account_ledger (
                            account_id, transaction_date, journal_number, description,
                            debit_amount, credit_amount, fiscal_year, fiscal_period,
                            entry_type, reference_type, reference_id, created_by, created_at
                          ) VALUES (
                            (SELECT account_id FROM chart_of_accounts WHERE account_code = '4000' LIMIT 1),
                            CURDATE(), ?, ?, 0, ?, ?, ?, 
                            'AUTO_INVOICE', 'INVOICE', ?, ?, NOW()
                          )";

    $stmt = $conn->prepare($revenue_entry_sql);
    $stmt->bind_param('sdiiii', $journal_number, $description, $total_cost, $fiscal_year, $fiscal_period, $invoice_id, $ordered_by);
    $stmt->execute();

    // 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 imaging 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' => 'Imaging 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);
?>