<?php
include 'db.php';
include 'includes/tax_helpers.php';

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

try {
    $id = intval($_GET['id'] ?? 0);
    
    if ($id <= 0) {
        throw new Exception('Invalid hold order ID');
    }

    $order_result = $conn->query("
        SELECT ho.*, dt.table_name, c.discount_applied, c.discount_rate
        FROM hold_orders ho 
        LEFT JOIN dinein_tables dt ON ho.table_id = dt.id 
        LEFT JOIN customers c ON ho.customer_id = c.id
        WHERE ho.id = $id LIMIT 1
    ");
    
    if (!$order_result) {
        throw new Exception('Database error: ' . $conn->error);
    }
    
    $order = $order_result->fetch_assoc();
    
    if (!$order) {
        throw new Exception('Hold order not found');
    }

    $items_result = $conn->query("SELECT * FROM hold_items WHERE hold_id = $id");
    
    if (!$items_result) {
        throw new Exception('Database error: ' . $conn->error);
    }
    
    $items = [];
    while ($row = $items_result->fetch_assoc()) {
        // Parse modifiers JSON if exists
        if (!empty($row['modifiers'])) {
            $row['modifiers'] = json_decode($row['modifiers'], true);
            // Handle JSON decode errors
            if (json_last_error() !== JSON_ERROR_NONE) {
                error_log("JSON decode error for hold item {$row['id']}: " . json_last_error_msg());
                $row['modifiers'] = [];
            }
        } else {
            $row['modifiers'] = [];
        }
        
        // Include remarks
        $row['remarks'] = $row['remarks'] ?? '';
        
        $items[] = $row;
    }

    // Get tax settings for payment method calculations
    $tax_method = getTaxCalculationMethod($conn);
    $payment_tax_rates = getAllPaymentMethodTaxRates($conn);
    
    // Calculate subtotal from items
    $subtotal = 0;
    foreach ($items as $item) {
        $subtotal += floatval($item['unit_price']) * intval($item['quantity']);
    }
    
    // Calculate payment method totals if payment method tax is enabled
    $payment_totals = [];
    if ($tax_method === 'payment_method' && !empty($payment_tax_rates)) {
        foreach ($payment_tax_rates as $method => $rate) {
            $tax_amount = $subtotal * ($rate / 100);
            $payment_totals[$method] = [
                'rate' => $rate,
                'subtotal' => $subtotal,
                'tax_amount' => $tax_amount,
                'total' => $subtotal + $tax_amount
            ];
        }
    }

    echo json_encode([
        'success' => true,
        'order' => $order, 
        'items' => $items,
        'subtotal' => $subtotal,
        'tax_method' => $tax_method,
        'payment_tax_rates' => $payment_tax_rates,
        'payment_totals' => $payment_totals
    ]);

} catch (Exception $e) {
    error_log("Error loading held order: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
