<?php
include 'db.php';


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

// Get filter parameters - simplified to only station filter
$station_filter = $_GET['station'] ?? '';
$limit = intval($_GET['limit'] ?? 50); // Show last 50 orders by default

// Debug: Log the filter values
error_log("Station Filter: " . $station_filter);
error_log("Limit: " . $limit);

// Get stations for filtering
$stations_query = "SELECT id, name FROM kds_stations WHERE is_active = 1 ORDER BY sort_order, name";
$stations_result = $conn->query($stations_query);

// Build the main query for KDS orders - show recent orders by default
$kds_query = "
    SELECT 
        ko.id,
        ko.order_number,
        ko.invoice_number,
        ko.customer_name,
        ko.table_number,
        ko.order_type,
        ko.order_status,
        ko.priority,
        ko.notes,
        ko.created_at,
        ko.updated_at,
        ko.prepared_at,
        ko.served_at,
        dt.table_name,
        df.name as floor_name,
        COUNT(koi.id) as item_count,
        SUM(koi.total_price) as total_amount,
        SUM(CASE WHEN koi.item_status = 'served' THEN 1 ELSE 0 END) as completed_items,
        'completed' as calculated_status,
        'kds' as source
    FROM kds_orders ko
    LEFT JOIN dinein_tables dt ON ko.table_number = dt.table_name
    LEFT JOIN dinein_floors df ON dt.floor_id = df.id
    LEFT JOIN kds_order_items koi ON ko.id = koi.kds_order_id
    WHERE ko.order_status IN ('served', 'completed')
";

$params = [];
$types = '';

// Add station filter if selected
if (!empty($station_filter)) {
    $kds_query .= " AND EXISTS (
        SELECT 1 FROM kds_order_items koi_filter
        LEFT JOIN kds_station_items ksi ON koi_filter.item_id = ksi.item_id AND ksi.is_active = 1
        WHERE koi_filter.kds_order_id = ko.id
        AND ksi.station_id = ?
    )";
    $params[] = $station_filter;
    $types .= 'i';
}

$kds_query .= " GROUP BY ko.id ORDER BY ko.created_at DESC LIMIT ?";
$params[] = $limit;
$types .= 'i';

// Only use KDS orders - no regular sales data needed

// Execute KDS orders query
$kds_stmt = $conn->prepare($kds_query);
if (!empty($types)) {
    $kds_stmt->bind_param($types, ...$params);
}
$kds_stmt->execute();
$kds_result = $kds_stmt->get_result();

// Get KDS orders results with items
$all_orders = [];
while ($order = $kds_result->fetch_assoc()) {
    // Get items for this order (same as KDS does)
    $items_query = "
        SELECT 
            koi.id,
            koi.item_name,
            koi.quantity,
            koi.unit_price,
            koi.total_price,
            koi.item_status,
            koi.special_instructions,
            ks.name as station_name,
            ks.color as station_color
        FROM kds_order_items koi
        LEFT JOIN kds_station_items ksi ON koi.item_id = ksi.item_id AND ksi.is_active = 1
        LEFT JOIN kds_stations ks ON ksi.station_id = ks.id AND ks.is_active = 1
        WHERE koi.kds_order_id = ?
        ORDER BY koi.id
    ";
    
    $items_stmt = $conn->prepare($items_query);
    $items_stmt->bind_param('i', $order['id']);
    $items_stmt->execute();
    $items_result = $items_stmt->get_result();
    
    $order['items'] = [];
    while ($item = $items_result->fetch_assoc()) {
        $order['items'][] = $item;
    }
    
    $all_orders[] = $order;
}

// Orders are already sorted by creation date (newest first) from the query

// Calculate totals
$total_orders = count($all_orders);
$total_amount = array_sum(array_column($all_orders, 'total_amount'));
$completed_orders = count(array_filter($all_orders, function($order) {
    return $order['order_status'] === 'completed' || $order['order_status'] === 'served';
}));
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order History - ITRPOS</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <!-- Feather Icons -->
    <script src="https://unpkg.com/feather-icons"></script>
    
    <!-- Custom KDS CSS for consistent styling -->
    <link rel="stylesheet" href="assets/css/kds.css">
    
    <style>
        /* Order History - KDS Style Layout */
        body {
            background-color: #f5f5f5;
            color: #333333;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            overflow-x: hidden;
            margin: 0;
            padding: 0;
        }
        
        .page-header {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
            padding: 8px 0;
            margin-bottom: 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        /* Compact header with inline filters */
        .header-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .header-left {
            display: flex;
            align-items: center;
            gap: 20px;
            flex: 1;
            min-width: 0;
        }
        
        .header-right {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-shrink: 0;
        }
        
        .header-title {
            font-size: 1.5rem;
            font-weight: 600;
            margin: 0;
        }
        
        .header-subtitle {
            font-size: 0.9rem;
            opacity: 0.9;
            margin: 0;
        }
        
        .header-filters {
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .header-filter {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .header-filter label {
            font-size: 0.85rem;
            margin: 0;
            white-space: nowrap;
        }
        
        .header-filter select {
            background: rgba(255,255,255,0.9);
            border: 1px solid rgba(255,255,255,0.3);
            border-radius: 4px;
            color: #333;
            font-size: 0.85rem;
            padding: 4px 8px;
            min-width: 120px;
        }
        
        .header-filter select:focus {
            background: white;
            border-color: rgba(255,255,255,0.8);
            outline: none;
        }
        
        /* Stats cards removed for more space */
        
        /* Filter section removed - moved to header */
        
        .btn-back {
            background: rgba(255,255,255,0.2);
            border: 1px solid rgba(255,255,255,0.3);
            color: white;
            padding: 8px 16px;
            border-radius: 5px;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .btn-back:hover {
            background: rgba(255,255,255,0.3);
            color: white;
            text-decoration: none;
        }
        
        .restore-btn {
            font-size: 0.8rem;
            padding: 4px 8px;
            border-radius: 6px;
            transition: all 0.2s ease;
        }
        
        .restore-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }
        
        .restore-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        /* Order History Specific Styles */
        
        /* Fix text visibility for order history - ensure proper contrast */
        .orders-grid .order-card .item-name,
        .order-card .item-name,
        .item-name {
            color: #333 !important;
            font-weight: 500 !important;
            font-size: 16px !important;
            white-space: normal !important;
            overflow: visible !important;
            text-overflow: unset !important;
            max-width: none !important;
        }
        
        /* Completed Status Button */
        .completed-button {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 8px 16px;
            font-size: 14px;
            font-weight: 600;
            width: 100%;
            margin-top: 8px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            box-shadow: 0 2px 4px rgba(40, 167, 69, 0.3);
            cursor: default;
        }
        
        /* Responsive header filters */
        @media (max-width: 992px) {
            .header-content {
                flex-direction: column;
                align-items: stretch;
                gap: 10px;
            }
            
            .header-left {
                flex-direction: column;
                align-items: center;
                gap: 10px;
            }
            
            .header-filters {
                justify-content: center;
                gap: 10px;
            }
            
            .header-right {
                justify-content: center;
            }
        }
        
        @media (max-width: 768px) {
            .header-filters {
                flex-direction: column;
                gap: 8px;
                width: 100%;
            }
            
            .header-filter {
                justify-content: space-between;
                width: 100%;
            }
            
            .header-filter select {
                min-width: 150px;
            }
        }
    </style>
</head>
<body>
    <!-- Compact Page Header with Filters -->
    <div class="page-header">
        <div class="container-fluid">
            <div class="header-content">
                <div class="header-left">
                    <div>
                        <h2 class="header-title">
                            <i class="fas fa-history me-2"></i>
                            Order History
                        </h2>
                        <p class="header-subtitle">Recent completed orders</p>
                    </div>
                    
                    <div class="header-filters">
                        <div class="header-filter">
                            <label for="station">Station:</label>
                            <select name="station" id="station" class="form-select">
                                <option value="">All Stations</option>
                                <?php if ($stations_result && $stations_result->num_rows > 0): ?>
                                    <?php mysqli_data_seek($stations_result, 0); ?>
                                    <?php while ($station = $stations_result->fetch_assoc()): ?>
                                        <option value="<?= $station['id'] ?>" <?= $station_filter == $station['id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($station['name']) ?>
                                        </option>
                                    <?php endwhile; ?>
                                <?php endif; ?>
                            </select>
                        </div>
                        
                        <div class="header-filter">
                            <label for="limit">Orders:</label>
                            <select name="limit" id="limit" class="form-select">
                                <option value="25" <?= $limit == 25 ? 'selected' : '' ?>>Last 25</option>
                                <option value="50" <?= $limit == 50 ? 'selected' : '' ?>>Last 50</option>
                                <option value="100" <?= $limit == 100 ? 'selected' : '' ?>>Last 100</option>
                            </select>
                        </div>
                        
                        <a href="order_history.php<?= !empty($station_filter) ? '?station=' . urlencode($station_filter) . '&limit=' . $limit : '?limit=' . $limit ?>" class="btn btn-sm btn-light">
                            <i class="fas fa-refresh"></i>
                        </a>
                    </div>
                </div>
                
                <div class="header-right">
                    <a href="kds.php" class="btn-back">
                        <i class="fas fa-arrow-left me-2"></i>
                        Back to KDS
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="container-fluid">
        <!-- Stats cards removed for maximum screen space -->

        <!-- Filter section moved to header for space optimization -->

        <!-- Debug section removed for cleaner interface -->

        <!-- Orders List - KDS Style Layout -->
        <div class="orders-grid" id="orders-container">
            <?php if (empty($all_orders)): ?>
                <div class="no-orders">
                    <i class="fas fa-clipboard-list"></i>
                    <h3>No Orders Found</h3>
                    <p>No completed orders match your current filters.</p>
                </div>
            <?php else: ?>
                <?php 
                // SIMPLIFIED: Distribute orders evenly across 3 columns to prevent cutoff
                $totalOrders = count($all_orders);
                $columnsCount = min(3, $totalOrders); // Max 3 columns or number of orders
                $ordersPerColumn = ceil($totalOrders / $columnsCount);
                
                $columns = [];
                for ($i = 0; $i < $columnsCount; $i++) {
                    $columns[$i] = [];
                }
                
                // Distribute orders round-robin to ensure even distribution
                foreach ($all_orders as $index => $order) {
                    $columnIndex = $index % $columnsCount;
                    $columns[$columnIndex][] = $order;
                }
                
                // Remove empty columns
                $columns = array_filter($columns, function($column) {
                    return !empty($column);
                });
                ?>
                
                <?php foreach ($columns as $column): ?>
                    <div class="orders-column">
                        <?php foreach ($column as $order): ?>
                            <div class="order-card completed <?= (isset($order['notes']) && strpos($order['notes'], 'RUNNING ORDER') !== false) ? 'running-order' : '' ?>" data-order-id="<?= $order['id'] ?>">
                                
                                <?php if (isset($order['notes']) && strpos($order['notes'], 'RUNNING ORDER') !== false): ?>
                                    <span class="running-order-badge">COMPLETED - RUNNING ORDER</span>
                                <?php endif; ?>
                                
                                <div class="order-header timer-normal">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <?php if ($order['order_type'] === 'dine_in' && $order['table_name']): ?>
                                                <div class="table-floor-info">
                                                    Table: <span class="table-name"><?= htmlspecialchars($order['table_name']) ?></span>
                                                    <?php if ($order['floor_name']): ?>
                                                        | Floor: <span class="floor-name"><?= htmlspecialchars($order['floor_name']) ?></span>
                                                    <?php endif; ?>
                                                </div>
                                                <div class="order-number">Order #<?= htmlspecialchars($order['order_number']) ?></div>
                                            <?php else: ?>
                                                <div class="table-floor-info">Order #<?= htmlspecialchars($order['order_number']) ?></div>
                                            <?php endif; ?>
                                            
                                            <span class="order-type-badge <?= $order['order_type'] ?>">
                                                <?= ucfirst(str_replace('_', ' ', $order['order_type'])) ?>
                                            </span>
                                            
                                            <div class="order-time normal">
                                                <i class="fas fa-check me-1"></i>
                                                <span>COMPLETED</span>
                                            </div>
                                        </div>
                                        <div class="text-end">
                                            <div class="customer-name"><?= htmlspecialchars($order['customer_name']) ?></div>
                                            <?php if ($order['priority'] !== 'normal'): ?>
                                                <div class="priority-info">
                                                    <span class="priority-indicator <?= $order['priority'] ?>"></span><?= strtoupper($order['priority']) ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="order-body">
                                    <div class="items-list">
                                        <?php foreach ($order['items'] as $item): ?>
                                            <div class="item-row">
                                                <div class="d-flex align-items-start flex-grow-1">
                                                    <span class="item-quantity me-3"><?= $item['quantity'] ?>x</span>
                                                    <div class="flex-grow-1">
                                                        <div class="d-flex align-items-center">
                                                            <span class="item-name me-2"><?= htmlspecialchars($item['item_name']) ?></span>
                                                        </div>
                                                        <?php if ($item['special_instructions']): ?>
                                                            <?php 
                                                            $parts = explode(' | REMARKS: ', $item['special_instructions']);
                                                            $modifiers = $parts[0];
                                                            $remarks = isset($parts[1]) ? $parts[1] : '';
                                                            ?>
                                                            <?php if ($modifiers): ?>
                                                                <div class="item-modifiers text-primary small mt-1">
                                                                    <i class="fas fa-tags me-1"></i><?= htmlspecialchars($modifiers) ?>
                                                                </div>
                                                            <?php endif; ?>
                                                            <?php if ($remarks): ?>
                                                                <div class="item-remarks text-warning small mt-1">
                                                                    <i class="fas fa-comment me-1"></i><?= htmlspecialchars($remarks) ?>
                                                                </div>
                                                            <?php endif; ?>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                                <div class="d-flex align-items-center flex-shrink-0 ms-2">
                                                    <?php if ($item['station_name']): ?>
                                                        <span class="badge me-2" style="background-color: <?= $item['station_color'] ?: '#6c757d' ?>; color: white; font-size: 9px;">
                                                            <?= htmlspecialchars($item['station_name']) ?>
                                                        </span>
                                                    <?php endif; ?>
                                                    <span class="item-status served">COMPLETED</span>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                
                                <div class="order-actions-container">
                                    <div class="completed-button">
                                        <i class="fas fa-check me-2"></i>
                                        COMPLETED
                                    </div>
                                    <?php if ($order['source'] === 'kds' && $order['order_status'] === 'served'): ?>
                                        <button class="btn btn-sm btn-outline-primary restore-btn mt-2" 
                                                data-order-id="<?= $order['id'] ?>" 
                                                onclick="restoreToKDS(<?= $order['id'] ?>, 'pending')">
                                            <i class="fas fa-undo me-1"></i>Restore to KDS
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Real-time filtering functionality
        document.addEventListener('DOMContentLoaded', function() {
            const stationSelect = document.getElementById('station');
            const limitSelect = document.getElementById('limit');
            
            // Auto-reload when station filter changes
            stationSelect.addEventListener('change', function() {
                updateFilters();
            });
            
            // Auto-reload when limit changes
            limitSelect.addEventListener('change', function() {
                updateFilters();
            });
            
            function updateFilters() {
                const station = stationSelect.value;
                const limit = limitSelect.value;
                
                // Build URL with current parameters
                const baseUrl = window.location.origin + window.location.pathname;
                let url = baseUrl;
                
                // Add parameters
                const params = [];
                if (station) {
                    params.push('station=' + encodeURIComponent(station));
                }
                if (limit) {
                    params.push('limit=' + encodeURIComponent(limit));
                }
                
                if (params.length > 0) {
                    url += '?' + params.join('&');
                }
                
                // Reload page with new parameters
                window.location.href = url;
            }
        });
        
        // Function to restore order to KDS
        function restoreToKDS(orderId, restoreStatus) {
            if (!confirm('Are you sure you want to restore this order to the KDS screen? This will make it visible again for kitchen staff as a pending order.')) {
                return;
            }
            
            // Disable the button to prevent double-clicking
            const buttons = document.querySelectorAll(`[data-order-id="${orderId}"].restore-btn`);
            buttons.forEach(btn => btn.disabled = true);
            
            fetch('ajax/kds_restore_order.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'restore_to_kds',
                    order_id: orderId,
                    restore_status: restoreStatus
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show success message
                    showAlert('success', 'Order successfully restored to KDS! The order will now appear on the KDS screen as a pending order.');
                    
                    // Reload the page after a short delay to reflect the changes
                    setTimeout(() => {
                        window.location.reload();
                    }, 2000);
                } else {
                    showAlert('error', 'Error: ' + data.message);
                    // Re-enable buttons on error
                    buttons.forEach(btn => btn.disabled = false);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('error', 'Network error occurred. Please try again.');
                // Re-enable buttons on error
                buttons.forEach(btn => btn.disabled = false);
            });
        }
        
        // Function to show alerts
        function showAlert(type, message) {
            // Create alert element
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show position-fixed`;
            alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            // Add to page
            document.body.appendChild(alertDiv);
            
            // Auto-remove after 5 seconds
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }
        
        // Simple height management for maximum space
        function updateLayoutHeights() {
            const header = document.querySelector('.page-header');
            const headerHeight = header ? header.offsetHeight : 0;
            const padding = 20;
            const availableHeight = window.innerHeight - headerHeight - padding;
            
            const ordersGrid = document.getElementById('orders-container');
            if (ordersGrid) {
                ordersGrid.style.height = availableHeight + 'px';
            }
        }

        // Initialize when page loads - simple approach
        document.addEventListener('DOMContentLoaded', function() {
            updateLayoutHeights();
            
            // Handle window resize
            window.addEventListener('resize', function() {
                clearTimeout(window.resizeTimeout);
                window.resizeTimeout = setTimeout(updateLayoutHeights, 250);
            });
        });
    </script>
</body>
</html>
