<?php
include 'db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if tablet user is logged in
if (!isset($_SESSION['tablet_logged_in']) || !$_SESSION['tablet_logged_in']) {
    header('Location: tablet_login.php');
    exit;
}

// Get logged in order taker info
$logged_in_order_taker_id = $_SESSION['tablet_order_taker_id'];
$logged_in_order_taker_name = $_SESSION['tablet_order_taker_name'];
$logged_in_employee_id = $_SESSION['tablet_order_taker_employee_id'];

// Get order types from settings
$orderTypes = [];
$enabledModes = [];

$query = "
    SELECT code, name 
    FROM settings 
    WHERE category_id = 4 
      AND is_active = 1 
      AND value = '1'
";

$result = $conn->query($query);

while ($row = $result->fetch_assoc()) {
    $orderTypes[] = $row;
    $enabledModes[] = $row['code'];
}

// Get categories and items
$categories = $conn->query("SELECT * FROM categories ORDER BY name");
$show_material = $conn->query("SELECT value FROM settings WHERE code = 'show_material_items_on_pos'")->fetch_assoc()['value'] ?? '0';
$display_images = $conn->query("SELECT value FROM settings WHERE code = 'display_images_on_pos'")->fetch_assoc()['value'] ?? '1';

if ($show_material === '1') {
    $items = $conn->query("SELECT items.*, categories.name AS category_name, sub_categories.name AS subcategory_name 
                           FROM items 
                           LEFT JOIN categories ON items.category_id = categories.id
                           LEFT JOIN sub_categories ON items.sub_category_id = sub_categories.id");
} else {
    $items = $conn->query("SELECT items.*, categories.name AS category_name, sub_categories.name AS subcategory_name 
                           FROM items 
                           LEFT JOIN categories ON items.category_id = categories.id
                           LEFT JOIN sub_categories ON items.sub_category_id = sub_categories.id
                           WHERE items.item_role != 'material'");
}

// Get tables for dine-in
$tables = $conn->query("SELECT dt.*, 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 
                        ORDER BY df.name, dt.table_name");

// Get customers
$customers = $conn->query("SELECT * FROM customers WHERE active = 1 ORDER BY name");

// Get active order takers
$order_takers = $conn->query("SELECT * FROM order_takers WHERE is_active = 1 ORDER BY name");

// Get tax rate
function getTaxRate($tax_rate_id, $conn) {
    if (!$tax_rate_id) return 0.00;
    $res = $conn->query("SELECT rate FROM tax_rates WHERE id = $tax_rate_id");
    if ($row = $res->fetch_assoc()) {
        return (float)$row['rate'];
    }
    return 0.00;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Tablet Order System - ITRPOS</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    
    <!-- Custom Tablet CSS -->
    <link rel="stylesheet" href="assets/css/tablet-order.css">
    
    <!-- Prevent zoom on input focus -->
    <style>
        input, select, textarea {
            font-size: 16px !important;
        }
    </style>
</head>
<body class="tablet-body">
    <!-- Header -->
    <header class="tablet-header">
        <div class="container-fluid">
            <div class="row align-items-center">
                <div class="col-6">
                    <h1 class="tablet-title">
                        <i class="fas fa-tablet-alt me-2"></i>
                        Tablet Order System
                    </h1>
                </div>
                <div class="col-6 text-end">
                    <div class="header-actions">
                        <span class="text-light me-3">
                            <i class="fas fa-user me-1"></i>
                            <?= htmlspecialchars($logged_in_order_taker_name) ?>
                        </span>
                        <button class="btn btn-outline-light btn-sm me-2" onclick="refreshTablet()">
                            <i class="fas fa-sync-alt"></i>
                        </button>
                        <button class="btn btn-outline-light btn-sm me-2" onclick="showSettings()">
                            <i class="fas fa-cog"></i>
                        </button>
                        <button class="btn btn-outline-light btn-sm me-2" onclick="logout()">
                            <i class="fas fa-sign-out-alt"></i>
                        </button>
                        <button class="btn btn-outline-light btn-sm" onclick="window.close()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="tablet-container">
        <!-- Screen 1: Order Mode Selection -->
        <div id="order-mode-screen" class="order-screen active">
            <div class="order-mode-container">
                <div class="order-mode-buttons">
                    <button class="btn-order-mode primary" data-type="dine_in">
                        <i class="fas fa-utensils"></i>
                        <span>DINE IN</span>
                    </button>
                    <div class="secondary-buttons">
                        <button class="btn-order-mode secondary" data-type="take_away">
                            <i class="fas fa-shopping-bag"></i>
                            <span>TAKE AWAY</span>
                        </button>
                        <button class="btn-order-mode secondary" data-type="delivery">
                            <i class="fas fa-truck"></i>
                            <span>DELIVERY</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Screen 2: Table Selection -->
        <div id="table-selection-screen" class="order-screen">
            <div class="table-selection-container">
                <div class="table-header">
                    <button class="btn btn-outline-secondary btn-sm" onclick="goBackToOrderMode()">
                        <i class="fas fa-arrow-left me-1"></i>Back
                    </button>
                    <h3 class="table-title">All Tables</h3>
                    <button class="btn btn-outline-primary btn-sm" onclick="goToOrderMode()">
                        <i class="fas fa-home"></i>Home
                    </button>
                </div>
                <div class="table-grid" id="table-grid">
                    <!-- Tables will be loaded here -->
                </div>
            </div>
        </div>

        <!-- Screen 3: Item/Cart Selection -->
        <div id="item-cart-screen" class="order-screen">
            <div class="item-cart-container">
                <!-- Top Navigation -->
                <div class="top-navigation">
                    <button class="btn btn-outline-secondary btn-sm" onclick="goBackToTableSelection()">
                        <i class="fas fa-arrow-left me-1"></i>Back
                    </button>
                    <div class="order-info">
                        <span id="current-order-type">Dine In</span>
                        <span id="current-table-info" style="display: none;">- Table 5</span>
                    </div>
                    <div class="user-info">
                        <i class="fas fa-user me-1"></i>
                        <?= htmlspecialchars($logged_in_order_taker_name) ?>
                    </div>
                </div>

                <!-- Main Categories -->
                <div class="main-categories-section">
                    <div class="main-categories" id="main-categories">
                        <!-- Main categories will be loaded here -->
                    </div>
                </div>

                <!-- Main Content Area -->
                <div class="main-content-area">
                    <!-- Left: Items Display -->
                    <div class="items-section">
                        <div class="items-grid" id="items-grid">
                            <!-- Items will be loaded here -->
                        </div>
                    </div>

                    <!-- Middle: Sub Categories -->
                    <div class="sub-categories-section">
                        <div class="sub-categories" id="sub-categories">
                            <!-- Sub categories will be loaded here -->
                        </div>
                    </div>

                    <!-- Right: Order List/Cart -->
                    <div class="order-list-section">
                        <div class="order-list-header">
                            <h5><i class="fas fa-shopping-cart me-2"></i>Order List</h5>
                            <span class="cart-count" id="cart-count">0</span>
                        </div>
                        <div class="order-items" id="cart-items">
                            <!-- Cart items will be displayed here -->
                        </div>
                        <div class="order-summary">
                            <div class="summary-row">
                                <span>Subtotal:</span>
                                <span id="subtotal">0.00</span>
                            </div>
                            <div class="summary-row">
                                <span>Tax:</span>
                                <span id="tax-amount">0.00</span>
                            </div>
                            <div class="summary-row total">
                                <span>Total:</span>
                                <span id="total-amount">0.00</span>
                            </div>
                        </div>
                        <div class="order-actions">
                            <button class="btn btn-warning w-100 mb-2" onclick="tabletOrderSystem.holdOrder()">
                                <i class="fas fa-pause me-2"></i>Hold Order
                            </button>
                            <button class="btn btn-secondary w-100" onclick="tabletOrderSystem.clearCart()">
                                <i class="fas fa-trash me-2"></i>Clear Cart
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modifier Selection Modal -->
    <div class="modal fade" id="tabletModifierModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Customize Your Order</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="text-center mb-3">
                        <h6 id="tabletModalItemName">Item Name</h6>
                        <h6>Base Price: Rs <span id="tabletBasePrice">0.00</span></h6>
                        <h5 id="tabletTotalPriceDisplay">Total: Rs <span id="tabletTotalPrice">0.00</span></h5>
                    </div>
                    <div id="tabletModifierGroupsContainer">
                        <!-- Modifier groups will be loaded here -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="tabletConfirmModifierBtn">Add to Cart</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Tablet Modifier Styles -->
    <style>
    /* Modifier Modal Styles for Tablet */
    #tabletModifierModal .modal-lg {
        max-width: 800px;
    }
    
    #tabletModifierModal .modifier-group {
        border: 1px solid #dee2e6;
        margin-bottom: 1rem;
    }
    
    #tabletModifierModal .card-header {
        background-color: #f8f9fa;
        border-bottom: 1px solid #dee2e6;
        padding: 1rem;
    }
    
    #tabletModifierModal .card-body {
        padding: 1rem;
    }
    
    #tabletModifierModal .form-check {
        margin-bottom: 0.75rem;
        padding: 0.75rem;
        border: 1px solid #e9ecef;
        border-radius: 8px;
        background-color: #fff;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    
    #tabletModifierModal .form-check:hover {
        background-color: #f8f9fa;
        border-color: #007bff;
    }
    
    #tabletModifierModal .form-check-input:checked + .form-check-label {
        color: #007bff;
        font-weight: 600;
    }
    
    #tabletModifierModal .form-check-input {
        width: 1.25rem;
        height: 1.25rem;
        margin-top: 0.125rem;
        margin-right: 0.75rem;
    }
    
    #tabletModifierModal .form-check-label {
        font-size: 1rem;
        cursor: pointer;
        margin-bottom: 0;
        flex: 1;
    }
    
    #tabletModifierModal .badge {
        font-size: 0.75rem;
        padding: 0.375rem 0.75rem;
    }
    
    #tabletModifierModal .text-center h6 {
        font-size: 1.1rem;
        margin-bottom: 0.5rem;
    }
    
    #tabletModifierModal .text-center h5 {
        font-size: 1.3rem;
        font-weight: bold;
        color: #28a745;
    }
    
    #tabletModifierModal .modal-footer {
        padding: 1.5rem;
        gap: 1rem;
    }
    
    #tabletModifierModal .modal-footer .btn {
        padding: 0.75rem 2rem;
        font-size: 1.1rem;
        border-radius: 8px;
        min-width: 120px;
    }
    
    /* Touch-friendly cart modifiers display */
    .cart-item-modifiers {
        font-size: 0.85rem;
        color: #6c757d;
        font-style: italic;
        margin-top: 0.25rem;
    }
    
    /* Touch-friendly cart remarks display */
    .cart-item-remarks {
        font-size: 0.85rem;
        color: #ffc107;
        font-style: italic;
        margin-top: 0.25rem;
        font-weight: 500;
    }
    
    .remove-btn {
        background: #dc3545;
        color: white;
        border: none;
        border-radius: 50%;
        width: 30px;
        height: 30px;
        font-size: 16px;
        font-weight: bold;
        margin-left: 8px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .remove-btn:hover {
        background: #c82333;
    }
    </style>

    <!-- Remarks Modal -->
    <div class="modal fade" id="tabletRemarksModal" tabindex="-1" data-bs-backdrop="static">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add Remarks</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="tabletRemarksInput" class="form-label">Special Instructions:</label>
                        <textarea class="form-control" id="tabletRemarksInput" rows="3" placeholder="Enter any special instructions for this item..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="tabletSaveRemarksBtn">Save Remarks</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- Custom Tablet JS -->
    <script src="assets/js/tablet-order.js"></script>

    <script>
        // Initialize with items data
        const itemsData = <?= json_encode($items->fetch_all(MYSQLI_ASSOC)) ?>;
        const categoriesData = <?= json_encode($categories->fetch_all(MYSQLI_ASSOC)) ?>;
        const tablesData = <?= json_encode($tables->fetch_all(MYSQLI_ASSOC)) ?>;
        
        // Set order taker ID for hold orders
        window.orderTakerId = <?= $logged_in_order_taker_id ?>;
        
        // Initialize the tablet order system
        document.addEventListener('DOMContentLoaded', function() {
            initializeTabletOrder(itemsData, categoriesData, tablesData);
        });
        
        // Logout function
        function logout() {
            if (confirm('Are you sure you want to logout?')) {
                window.location.href = 'tablet_logout.php';
            }
        }
    </script>
</body>
</html>

<?php
function getOrderTypeIcon($type) {
    switch ($type) {
        case 'dine_in':
            return 'utensils';
        case 'take_away':
            return 'shopping-bag';
        case 'delivery':
            return 'truck';
        default:
            return 'shopping-cart';
    }
}
?>
