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

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

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

$tablet_user_id = $_SESSION['tablet_order_taker_id'];

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = $_POST['action'] ?? '';
        
        switch ($action) {
            case 'transfer_order':
                handleTransferOrder($conn, $tablet_user_id);
                break;
                
            case 'merge_orders':
                handleMergeOrders($conn, $tablet_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, $tablet_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');
        }
        
        if ($target_table['status'] !== 'available') {
            throw new Exception('Target table is not available');
        }
        
        // 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();
        
        // Update target table status to occupied
        $stmt = $conn->prepare("UPDATE dinein_tables SET status = 'occupied' WHERE id = ?");
        $stmt->bind_param("i", $target_table_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, $tablet_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, $tablet_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, $tablet_user_id);
        $stmt->execute();
        $stmt->close();
        
        $conn->commit();
        
        echo json_encode([
            'success' => true, 
            'message' => 'Orders merged successfully',
            'data' => [
                'source_hold_order_id' => $source_hold_order_id,
                'target_hold_order_id' => $target_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 getTableOrders($conn) {
    $table_id = intval($_GET['table_id']);
    
    if (!$table_id) {
        echo json_encode(['success' => false, 'message' => 'Table ID is required']);
        return;
    }
    
    try {
        // Get hold orders for the table
        $stmt = $conn->prepare("
            SELECT 
                ho.*,
                COUNT(hi.id) as item_count,
                SUM(hi.quantity * hi.unit_price) as calculated_total
            FROM hold_orders ho
            LEFT JOIN hold_items hi ON ho.id = hi.hold_id
            WHERE ho.table_id = ? AND ho.order_mode = 'dine_in'
            GROUP BY ho.id
            ORDER BY ho.created_at DESC
        ");
        $stmt->bind_param("i", $table_id);
        $stmt->execute();
        $orders = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        
        // Get items for each order
        foreach ($orders as &$order) {
            $stmt = $conn->prepare("
                SELECT 
                    hi.*,
                    i.name as item_name
                FROM hold_items hi
                LEFT JOIN items i ON hi.item_id = i.id
                WHERE hi.hold_id = ?
                ORDER BY hi.id
            ");
            $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' => $orders
        ]);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function getAvailableTables($conn) {
    try {
        // Get available tables
        $stmt = $conn->prepare("
            SELECT 
                dt.*,
                COALESCE(f.name, 'Main Floor') as floor_name
            FROM dinein_tables dt
            LEFT JOIN dinein_floors f ON dt.floor_id = f.id
            WHERE dt.status = 'available' AND dt.is_active = 1
            ORDER BY COALESCE(f.name, 'Main Floor'), dt.table_name
        ");
        
        if (!$stmt) {
            throw new Exception('Failed to prepare statement: ' . $conn->error);
        }
        
        $stmt->execute();
        
        if ($stmt->error) {
            throw new Exception('Failed to execute statement: ' . $stmt->error);
        }
        
        $result = $stmt->get_result();
        $tables = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        
        echo json_encode([
            'success' => true,
            'data' => $tables,
            'count' => count($tables)
        ]);
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false, 
            'message' => $e->getMessage(),
            'debug' => [
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]
        ]);
    }
}
?>
