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

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

try {
    // Get table ID from request
    $table_id = isset($_GET['table_id']) ? intval($_GET['table_id']) : 0;
    
    if (!$table_id) {
        throw new Exception('Table ID is required');
    }
    
    // Fetch comprehensive table information
    $table_query = "
        SELECT 
            dt.id,
            dt.table_name,
            dt.seats,
            dt.status,
            df.id as floor_id,
            df.name as floor_name,
            CASE 
                WHEN EXISTS (SELECT 1 FROM hold_orders ho WHERE ho.table_id = dt.id) THEN 'occupied'
                ELSE dt.status
            END as calculated_status
        FROM dinein_tables dt
        LEFT JOIN dinein_floors df ON dt.floor_id = df.id
        WHERE dt.id = ? AND dt.is_active = 1
    ";
    
    $stmt = $conn->prepare($table_query);
    $stmt->bind_param('i', $table_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception('Table not found');
    }
    
    $table = $result->fetch_assoc();
    
    // Fetch all orders for this table
    $orders_query = "
        SELECT 
            ho.id,
            ho.customer_name,
            ho.order_mode,
            ho.total_amount,
            ho.created_at,
            ho.updated_at,
            ho.order_taker_id,
            CONCAT('HOLD-', LPAD(ho.id, 6, '0')) as reference,
            (SELECT COUNT(*) FROM kds_orders ko WHERE ko.table_number = dt.table_name AND ko.order_status NOT IN ('served', 'ready')) as active_kds_orders
        FROM hold_orders ho
        LEFT JOIN dinein_tables dt ON ho.table_id = dt.id
        WHERE ho.table_id = ? 
        ORDER BY ho.created_at DESC
    ";
    
    $orders_stmt = $conn->prepare($orders_query);
    $orders_stmt->bind_param('i', $table_id);
    $orders_stmt->execute();
    $orders_result = $orders_stmt->get_result();
    
    $orders = [];
    $total_amount = 0;
    $total_items = 0;
    
    while ($order = $orders_result->fetch_assoc()) {
        // Fetch order items for each order
        $items_query = "
            SELECT 
                hi.id,
                hi.item_name,
                hi.quantity,
                hi.unit_price,
                hi.tax_rate,
                hi.modifiers,
                hi.remarks,
                (hi.quantity * hi.unit_price) as line_total
            FROM hold_items hi
            WHERE hi.hold_id = ?
            ORDER BY hi.id
        ";
        
        $items_stmt = $conn->prepare($items_query);
        $items_stmt->bind_param('i', $order['id']);
        $items_stmt->execute();
        $items_result = $items_stmt->get_result();
        
        $items = [];
        while ($item = $items_result->fetch_assoc()) {
            // Parse modifiers JSON if exists
            if (!empty($item['modifiers'])) {
                $item['modifiers'] = json_decode($item['modifiers'], true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    $item['modifiers'] = [];
                }
            } else {
                $item['modifiers'] = [];
            }
            
            $items[] = $item;
            $total_items += $item['quantity'];
        }
        
        $order['items'] = $items;
        $order['item_count'] = count($items);
        $order['status'] = 'held';
        $order['has_running_orders'] = $order['active_kds_orders'] > 0;
        
        $orders[] = $order;
        $total_amount += floatval($order['total_amount']);
    }
    
    // Get tax settings for payment method calculations
    $tax_method = getTaxCalculationMethod($conn);
    $payment_tax_rates = getAllPaymentMethodTaxRates($conn);
    
    // Calculate payment method totals for each order
    foreach ($orders as &$order) {
        $subtotal = 0;
        foreach ($order['items'] as $item) {
            $subtotal += floatval($item['line_total']);
        }
        
        $order['subtotal'] = $subtotal;
        $order['payment_totals'] = [];
        
        // Calculate payment method totals if payment method tax is enabled
        if ($tax_method === 'payment_method' && !empty($payment_tax_rates)) {
            foreach ($payment_tax_rates as $method => $rate) {
                $tax_amount = $subtotal * ($rate / 100);
                $order['payment_totals'][$method] = [
                    'rate' => $rate,
                    'subtotal' => $subtotal,
                    'tax_amount' => $tax_amount,
                    'total' => $subtotal + $tax_amount
                ];
            }
        }
    }
    
    // Calculate table statistics
    $table_stats = [
        'total_orders' => count($orders),
        'total_items' => $total_items,
        'total_amount' => $total_amount,
        'last_order_time' => !empty($orders) ? $orders[0]['created_at'] : null,
        'has_active_kds' => !empty($orders) && $orders[0]['has_running_orders'],
        'tax_method' => $tax_method,
        'payment_tax_rates' => $payment_tax_rates
    ];
    
    echo json_encode([
        'success' => true,
        'table' => $table,
        'orders' => $orders,
        'stats' => $table_stats
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>
