<?php
session_start();
include '../db.php';

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'User not authenticated']);
    exit;
}

$user_id = $_SESSION['user_id'];

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = $_POST['action'] ?? '';
        
        switch ($action) {
            case 'transfer_order':
                handleTransferOrder($conn, $user_id);
                break;
                
            case 'merge_orders':
                handleMergeOrders($conn, $user_id);
                break;
                
            default:
                echo json_encode(['success' => false, 'message' => 'Invalid action']);
                break;
        }
    } elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $action = $_GET['action'] ?? '';
        
        switch ($action) {
            case 'get_table_orders':
                getTableOrders($conn);
                break;
                
            case 'get_available_tables':
                getAvailableTables($conn);
                break;
                
            default:
                echo json_encode(['success' => false, 'message' => 'Invalid action']);
                break;
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
}

function handleTransferOrder($conn, $user_id) {
    $source_table_id = intval($_POST['source_table_id']);
    $target_table_id = intval($_POST['target_table_id']);
    $hold_order_id = intval($_POST['hold_order_id']);
    
    if (!$source_table_id || !$target_table_id || !$hold_order_id) {
        echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
        return;
    }
    
    // Start transaction
    $conn->begin_transaction();
    
    try {
        // Get hold order details
        $stmt = $conn->prepare("SELECT * FROM hold_orders WHERE id = ? AND table_id = ?");
        $stmt->bind_param("ii", $hold_order_id, $source_table_id);
        $stmt->execute();
        $hold_order = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        if (!$hold_order) {
            throw new Exception('Hold order not found');
        }
        
        // Check if target table is available
        $stmt = $conn->prepare("SELECT status FROM dinein_tables WHERE id = ? AND is_active = 1");
        $stmt->bind_param("i", $target_table_id);
        $stmt->execute();
        $target_table = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        if (!$target_table) {
            throw new Exception('Target table not found');
        }
        
        // Update hold order to new table
        $stmt = $conn->prepare("UPDATE hold_orders SET table_id = ?, updated_at = NOW() WHERE id = ?");
        $stmt->bind_param("ii", $target_table_id, $hold_order_id);
        $stmt->execute();
        $stmt->close();
        
        // Check if source table is now empty and update its status to available
        $stmt = $conn->prepare("SELECT COUNT(*) as remaining_orders FROM hold_orders WHERE table_id = ?");
        $stmt->bind_param("i", $source_table_id);
        $stmt->execute();
        $remaining_orders = $stmt->get_result()->fetch_assoc()['remaining_orders'];
        $stmt->close();
        
        if ($remaining_orders == 0) {
            // No more orders on source table, set it to available
            $stmt = $conn->prepare("UPDATE dinein_tables SET status = 'available' WHERE id = ?");
            $stmt->bind_param("i", $source_table_id);
            $stmt->execute();
            $stmt->close();
        }
        
        // Log the transfer
        $stmt = $conn->prepare("INSERT INTO table_transfer_logs (source_table_id, target_table_id, hold_order_id, transferred_by, transfer_type, created_at) VALUES (?, ?, ?, ?, 'transfer', NOW())");
        $stmt->bind_param("iiis", $source_table_id, $target_table_id, $hold_order_id, $user_id);
        $stmt->execute();
        $stmt->close();
        
        $conn->commit();
        
        echo json_encode([
            'success' => true, 
            'message' => 'Order transferred successfully',
            'data' => [
                'hold_order_id' => $hold_order_id,
                'source_table_id' => $source_table_id,
                'target_table_id' => $target_table_id
            ]
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function handleMergeOrders($conn, $user_id) {
    $source_table_id = intval($_POST['source_table_id']);
    $target_table_id = intval($_POST['target_table_id']);
    $source_hold_order_id = intval($_POST['source_hold_order_id']);
    $target_hold_order_id = intval($_POST['target_hold_order_id']);
    
    if (!$source_table_id || !$target_table_id || !$source_hold_order_id || !$target_hold_order_id) {
        echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
        return;
    }
    
    // Start transaction
    $conn->begin_transaction();
    
    try {
        // Get both hold orders
        $stmt = $conn->prepare("SELECT * FROM hold_orders WHERE id IN (?, ?)");
        $stmt->bind_param("ii", $source_hold_order_id, $target_hold_order_id);
        $stmt->execute();
        $hold_orders = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        
        if (count($hold_orders) !== 2) {
            throw new Exception('One or both hold orders not found');
        }
        
        $source_order = $hold_orders[0]['id'] == $source_hold_order_id ? $hold_orders[0] : $hold_orders[1];
        $target_order = $hold_orders[0]['id'] == $target_hold_order_id ? $hold_orders[0] : $hold_orders[1];
        
        // Get items from source order
        $stmt = $conn->prepare("SELECT * FROM hold_items WHERE hold_id = ?");
        $stmt->bind_param("i", $source_hold_order_id);
        $stmt->execute();
        $source_items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        
        // Merge items into target order
        foreach ($source_items as $item) {
            // Check if item already exists in target order
            $stmt = $conn->prepare("SELECT id, quantity FROM hold_items WHERE hold_id = ? AND item_id = ?");
            $stmt->bind_param("ii", $target_hold_order_id, $item['item_id']);
            $stmt->execute();
            $existing_item = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            
            if ($existing_item) {
                // Update quantity
                $new_quantity = $existing_item['quantity'] + $item['quantity'];
                $stmt = $conn->prepare("UPDATE hold_items SET quantity = ? WHERE id = ?");
                $stmt->bind_param("di", $new_quantity, $existing_item['id']);
                $stmt->execute();
                $stmt->close();
            } else {
                // Insert new item
                $stmt = $conn->prepare("INSERT INTO hold_items (hold_id, item_id, item_name, quantity, unit_price, tax_rate, modifiers, remarks, store_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->bind_param("iisddssi", 
                    $target_hold_order_id, 
                    $item['item_id'], 
                    $item['item_name'], 
                    $item['quantity'], 
                    $item['unit_price'], 
                    $item['tax_rate'], 
                    $item['modifiers'], 
                    $item['remarks'],
                    $item['store_id']
                );
                $stmt->execute();
                $stmt->close();
            }
        }
        
        // Update target order total
        $stmt = $conn->prepare("SELECT SUM(quantity * unit_price) as new_total FROM hold_items WHERE hold_id = ?");
        $stmt->bind_param("i", $target_hold_order_id);
        $stmt->execute();
        $new_total = $stmt->get_result()->fetch_assoc()['new_total'];
        $stmt->close();
        
        $stmt = $conn->prepare("UPDATE hold_orders SET total_amount = ? WHERE id = ?");
        $stmt->bind_param("di", $new_total, $target_hold_order_id);
        $stmt->execute();
        $stmt->close();
        
        // Delete source order and its items
        $stmt = $conn->prepare("DELETE FROM hold_items WHERE hold_id = ?");
        $stmt->bind_param("i", $source_hold_order_id);
        $stmt->execute();
        $stmt->close();
        
        $stmt = $conn->prepare("DELETE FROM hold_orders WHERE id = ?");
        $stmt->bind_param("i", $source_hold_order_id);
        $stmt->execute();
        $stmt->close();
        
        // Check if source table is now empty and update its status to available
        $stmt = $conn->prepare("SELECT COUNT(*) as remaining_orders FROM hold_orders WHERE table_id = ?");
        $stmt->bind_param("i", $source_table_id);
        $stmt->execute();
        $remaining_orders = $stmt->get_result()->fetch_assoc()['remaining_orders'];
        $stmt->close();
        
        if ($remaining_orders == 0) {
            // No more orders on source table, set it to available
            $stmt = $conn->prepare("UPDATE dinein_tables SET status = 'available' WHERE id = ?");
            $stmt->bind_param("i", $source_table_id);
            $stmt->execute();
            $stmt->close();
        }
        
        // Log the merge
        $stmt = $conn->prepare("INSERT INTO table_transfer_logs (source_table_id, target_table_id, hold_order_id, transferred_by, transfer_type, created_at) VALUES (?, ?, ?, ?, 'merge', NOW())");
        $stmt->bind_param("iiis", $source_table_id, $target_table_id, $target_hold_order_id, $user_id);
        $stmt->execute();
        $stmt->close();
        
        $conn->commit();
        
        echo json_encode([
            'success' => true, 
            'message' => 'Orders merged successfully',
            'data' => [
                'merged_order_id' => $target_hold_order_id,
                'source_table_id' => $source_table_id,
                'target_table_id' => $target_table_id,
                'new_total' => $new_total
            ]
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function getTableOrders($conn) {
    $table_id = intval($_GET['table_id']);
    
    if (!$table_id) {
        echo json_encode(['success' => false, 'message' => 'Table ID required']);
        return;
    }
    
    // Debug: First check if the table exists and what orders are associated with it
    $debug_stmt = $conn->prepare("
        SELECT dt.id, dt.table_name, dt.status,
               ho.id as order_id, ho.customer_name, ho.table_id, ho.order_mode, ho.total_amount
        FROM dinein_tables dt
        LEFT JOIN hold_orders ho ON dt.id = ho.table_id
        WHERE dt.id = ?
    ");
    $debug_stmt->bind_param("i", $table_id);
    $debug_stmt->execute();
    $debug_result = $debug_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $debug_stmt->close();
    
    // Debug: Also check all hold orders to see if there are any orders that might be related
    $all_orders_stmt = $conn->prepare("
        SELECT ho.id, ho.customer_name, ho.table_id, ho.order_mode, ho.total_amount,
               COUNT(hi.id) as item_count
        FROM hold_orders ho
        LEFT JOIN hold_items hi ON ho.id = hi.hold_id
        GROUP BY ho.id
        ORDER BY ho.created_at DESC
        LIMIT 10
    ");
    $all_orders_stmt->execute();
    $all_orders_result = $all_orders_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $all_orders_stmt->close();
    
    // Get hold orders for the table
    $stmt = $conn->prepare("
        SELECT ho.*, 
               COUNT(hi.id) as item_count,
               GROUP_CONCAT(hi.item_name SEPARATOR ', ') as items_summary
        FROM hold_orders ho
        LEFT JOIN hold_items hi ON ho.id = hi.hold_id
        WHERE ho.table_id = ?
        GROUP BY ho.id
        ORDER BY ho.created_at DESC
    ");
    $stmt->bind_param("i", $table_id);
    $stmt->execute();
    $hold_orders = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    // Get detailed items for each order
    foreach ($hold_orders as &$order) {
        $stmt = $conn->prepare("SELECT * FROM hold_items WHERE hold_id = ? ORDER BY item_name");
        $stmt->bind_param("i", $order['id']);
        $stmt->execute();
        $order['items'] = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
    }
    
    echo json_encode([
        'success' => true,
        'data' => $hold_orders,
        'debug' => [
            'table_id_requested' => $table_id,
            'table_debug_info' => $debug_result,
            'all_orders_sample' => $all_orders_result
        ]
    ]);
}

function getAvailableTables($conn) {
    // Get all available tables (not occupied)
    $query = "
        SELECT dt.id, dt.table_name, dt.seats, dt.status, df.name as floor_name
        FROM dinein_tables dt
        LEFT JOIN dinein_floors df ON dt.floor_id = df.id
        WHERE dt.is_active = 1 
        AND dt.status = 'available'
        AND NOT EXISTS (
            SELECT 1 FROM hold_orders ho 
            WHERE ho.table_id = dt.id
        )
        ORDER BY df.name, dt.table_name
    ";
    
    $result = $conn->query($query);
    $tables = [];
    
    while ($row = $result->fetch_assoc()) {
        $tables[] = $row;
    }
    
    echo json_encode([
        'success' => true,
        'data' => $tables
    ]);
}

$conn->close();
?>
