<?php
include 'db.php';


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

// Get filter parameters
$start_date = $_GET['start_date'] ?? date('Y-m-d', strtotime('-7 days'));
$end_date = $_GET['end_date'] ?? date('Y-m-d');
$order_type = $_GET['order_type'] ?? '';
$status_filter = $_GET['status'] ?? '';
$customer_filter = $_GET['customer'] ?? '';

// Build the main query for KDS orders
$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,
        '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 DATE(ko.created_at) BETWEEN ? AND ?
";

$params = [$start_date, $end_date];
$types = 'ss';

if (!empty($order_type)) {
    $kds_query .= " AND ko.order_type = ?";
    $params[] = $order_type;
    $types .= 's';
}

if (!empty($status_filter)) {
    $kds_query .= " AND ko.order_status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

if (!empty($customer_filter)) {
    $kds_query .= " AND ko.customer_name LIKE ?";
    $params[] = "%$customer_filter%";
    $types .= 's';
}

$kds_query .= " GROUP BY ko.id ORDER BY ko.created_at DESC";

// Build query for regular sales orders
$sales_query = "
    SELECT 
        s.id,
        s.invoice_number as order_number,
        s.invoice_number,
        s.customer_name,
        NULL as table_number,
        CASE 
            WHEN s.table_id IS NOT NULL THEN 'dine_in'
            WHEN s.order_mode = 'take_away' THEN 'take_away'
            WHEN s.order_mode = 'delivery' THEN 'delivery'
            ELSE 'dine_in'
        END as order_type,
        'completed' as order_status,
        'normal' as priority,
        NULL as notes,
        s.sale_date as created_at,
        s.sale_date as updated_at,
        s.sale_date as prepared_at,
        s.sale_date as served_at,
        NULL as table_name,
        NULL as floor_name,
        COUNT(si.id) as item_count,
        s.net_amount as total_amount,
        COUNT(si.id) as completed_items,
        'sale' as source
    FROM sales s
    LEFT JOIN sale_items si ON s.id = si.sale_id
    WHERE DATE(s.sale_date) BETWEEN ? AND ?
";

$sales_params = [$start_date, $end_date];
$sales_types = 'ss';

if (!empty($order_type)) {
    $sales_query .= " AND CASE 
        WHEN s.table_id IS NOT NULL THEN 'dine_in'
        WHEN s.order_mode = 'take_away' THEN 'take_away'
        WHEN s.order_mode = 'delivery' THEN 'delivery'
        ELSE 'dine_in'
    END = ?";
    $sales_params[] = $order_type;
    $sales_types .= 's';
}

if (!empty($customer_filter)) {
    $sales_query .= " AND s.customer_name LIKE ?";
    $sales_params[] = "%$customer_filter%";
    $sales_types .= 's';
}

$sales_query .= " GROUP BY s.id ORDER BY s.sale_date DESC";

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

// Execute sales orders query
$sales_stmt = $conn->prepare($sales_query);
if (!empty($sales_params)) {
    $sales_stmt->bind_param($sales_types, ...$sales_params);
}
$sales_stmt->execute();
$sales_result = $sales_stmt->get_result();

// Combine and sort results
$all_orders = [];
while ($order = $kds_result->fetch_assoc()) {
    $all_orders[] = $order;
}
while ($order = $sales_result->fetch_assoc()) {
    $all_orders[] = $order;
}

// Sort by creation date (newest first)
usort($all_orders, function($a, $b) {
    return strtotime($b['created_at']) - strtotime($a['created_at']);
});

// 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">
    
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 0;
            margin-bottom: 30px;
        }
        
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .stats-number {
            font-size: 2rem;
            font-weight: bold;
            color: #667eea;
        }
        
        .order-card {
            background: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transition: transform 0.2s ease;
        }
        
        .order-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
        }
        
        .order-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .order-number {
            font-size: 1.2rem;
            font-weight: bold;
            color: #333;
        }
        
        .order-type-badge {
            padding: 4px 8px;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: bold;
            text-transform: uppercase;
        }
        
        .order-type-badge.dine_in { background: #e3f2fd; color: #1976d2; }
        .order-type-badge.take_away { background: #f3e5f5; color: #7b1fa2; }
        .order-type-badge.delivery { background: #e8f5e8; color: #388e3c; }
        
        .status-badge {
            padding: 4px 12px;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: bold;
            text-transform: uppercase;
        }
        
        .status-badge.pending { background: #fff3e0; color: #f57c00; }
        .status-badge.preparing { background: #e3f2fd; color: #1976d2; }
        .status-badge.ready { background: #e8f5e8; color: #388e3c; }
        .status-badge.served { background: #f3e5f5; color: #7b1fa2; }
        .status-badge.completed { background: #e8f5e8; color: #388e3c; }
        .status-badge.cancelled { background: #ffebee; color: #d32f2f; }
        
        .priority-badge {
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 0.7rem;
            font-weight: bold;
        }
        
        .priority-badge.normal { background: #e8f5e8; color: #388e3c; }
        .priority-badge.urgent { background: #fff3e0; color: #f57c00; }
        .priority-badge.rush { background: #ffebee; color: #d32f2f; }
        
        .order-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 10px;
        }
        
        .detail-item {
            display: flex;
            flex-direction: column;
        }
        
        .detail-label {
            font-size: 0.8rem;
            color: #666;
            margin-bottom: 2px;
        }
        
        .detail-value {
            font-weight: 500;
            color: #333;
        }
        
        .filter-section {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .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;
        }
        
        .source-badge {
            padding: 2px 6px;
            border-radius: 8px;
            font-size: 0.7rem;
            font-weight: bold;
        }
        
        .source-badge.kds { background: #e3f2fd; color: #1976d2; }
        .source-badge.sale { background: #f3e5f5; color: #7b1fa2; }
        
        .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;
        }
    </style>
</head>
<body>
    <!-- Page Header -->
    <div class="page-header">
        <div class="container-fluid">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h2 class="mb-0">
                        <i class="fas fa-history me-3"></i>
                        Order History
                    </h2>
                    <p class="mb-0 mt-2">Complete order tracking and history with restore functionality</p>
                </div>
                <div class="col-md-4 text-end">
                    <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">
        <!-- Statistics Cards -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="stats-card text-center">
                    <div class="stats-number"><?= number_format($total_orders) ?></div>
                    <div class="text-muted">Total Orders</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card text-center">
                    <div class="stats-number"><?= number_format($completed_orders) ?></div>
                    <div class="text-muted">Completed Orders</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card text-center">
                    <div class="stats-number"><?= number_format($total_amount, 2) ?></div>
                    <div class="text-muted">Total Amount</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card text-center">
                    <div class="stats-number"><?= $total_orders > 0 ? number_format(($completed_orders / $total_orders) * 100, 1) : 0 ?>%</div>
                    <div class="text-muted">Completion Rate</div>
                </div>
            </div>
        </div>

        <!-- Filter Section -->
        <div class="filter-section">
            <form method="get" class="row g-3">
                <div class="col-md-2">
                    <label for="start_date" class="form-label">Start Date</label>
                    <input type="date" name="start_date" id="start_date" class="form-control" value="<?= htmlspecialchars($start_date) ?>">
                </div>
                <div class="col-md-2">
                    <label for="end_date" class="form-label">End Date</label>
                    <input type="date" name="end_date" id="end_date" class="form-control" value="<?= htmlspecialchars($end_date) ?>">
                </div>
                <div class="col-md-2">
                    <label for="order_type" class="form-label">Order Type</label>
                    <select name="order_type" id="order_type" class="form-select">
                        <option value="">All Types</option>
                        <option value="dine_in" <?= $order_type === 'dine_in' ? 'selected' : '' ?>>Dine In</option>
                        <option value="take_away" <?= $order_type === 'take_away' ? 'selected' : '' ?>>Take Away</option>
                        <option value="delivery" <?= $order_type === 'delivery' ? 'selected' : '' ?>>Delivery</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label for="status" class="form-label">Status</label>
                    <select name="status" id="status" class="form-select">
                        <option value="">All Status</option>
                        <option value="pending" <?= $status_filter === 'pending' ? 'selected' : '' ?>>Pending</option>
                        <option value="preparing" <?= $status_filter === 'preparing' ? 'selected' : '' ?>>Preparing</option>
                        <option value="ready" <?= $status_filter === 'ready' ? 'selected' : '' ?>>Ready</option>
                        <option value="served" <?= $status_filter === 'served' ? 'selected' : '' ?>>Served</option>
                        <option value="completed" <?= $status_filter === 'completed' ? 'selected' : '' ?>>Completed</option>
                        <option value="cancelled" <?= $status_filter === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label for="customer" class="form-label">Customer</label>
                    <input type="text" name="customer" id="customer" class="form-control" value="<?= htmlspecialchars($customer_filter) ?>" placeholder="Search customer...">
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary me-2">
                        <i class="fas fa-search me-1"></i>
                        Filter
                    </button>
                    <a href="order_history.php" class="btn btn-outline-secondary">
                        <i class="fas fa-times me-1"></i>
                        Clear
                    </a>
                </div>
            </form>
        </div>

        <!-- Orders List -->
        <div class="row">
            <div class="col-12">
                <?php if (empty($all_orders)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-clipboard-list fa-3x text-muted mb-3"></i>
                        <h4 class="text-muted">No Orders Found</h4>
                        <p class="text-muted">No orders match your current filters.</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($all_orders as $order): ?>
                        <div class="order-card">
                            <div class="order-header">
                                <div class="d-flex align-items-center">
                                    <div class="order-number me-3">
                                        <?= htmlspecialchars($order['order_number']) ?>
                                    </div>
                                    <span class="order-type-badge <?= $order['order_type'] ?> me-2">
                                        <?= ucfirst(str_replace('_', ' ', $order['order_type'])) ?>
                                    </span>
                                    <span class="status-badge <?= $order['order_status'] ?> me-2">
                                        <?= ucfirst($order['order_status']) ?>
                                    </span>
                                    <?php if ($order['priority'] !== 'normal'): ?>
                                        <span class="priority-badge <?= $order['priority'] ?> me-2">
                                            <?= strtoupper($order['priority']) ?>
                                        </span>
                                    <?php endif; ?>
                                    <span class="source-badge <?= $order['source'] ?>">
                                        <?= strtoupper($order['source']) ?>
                                    </span>
                                </div>
                                <div class="text-end">
                                    <div class="fw-bold"><?= number_format($order['total_amount'], 2) ?></div>
                                    <small class="text-muted"><?= $order['item_count'] ?> items</small>
                                </div>
                            </div>
                            
                            <div class="order-details">
                                <div class="detail-item">
                                    <span class="detail-label">Customer</span>
                                    <span class="detail-value"><?= htmlspecialchars($order['customer_name']) ?></span>
                                </div>
                                
                                <?php if ($order['table_name']): ?>
                                    <div class="detail-item">
                                        <span class="detail-label">Table</span>
                                        <span class="detail-value">
                                            <?= htmlspecialchars($order['table_name']) ?>
                                            <?php if ($order['floor_name']): ?>
                                                (<?= htmlspecialchars($order['floor_name']) ?>)
                                            <?php endif; ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="detail-item">
                                    <span class="detail-label">Created</span>
                                    <span class="detail-value">
                                        <?= date('M j, Y g:i A', strtotime($order['created_at'])) ?>
                                    </span>
                                </div>
                                
                                <?php if ($order['prepared_at'] && $order['prepared_at'] !== $order['created_at']): ?>
                                    <div class="detail-item">
                                        <span class="detail-label">Prepared</span>
                                        <span class="detail-value">
                                            <?= date('M j, Y g:i A', strtotime($order['prepared_at'])) ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($order['served_at'] && $order['served_at'] !== $order['created_at']): ?>
                                    <div class="detail-item">
                                        <span class="detail-label">Served</span>
                                        <span class="detail-value">
                                            <?= date('M j, Y g:i A', strtotime($order['served_at'])) ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                                                 <?php if ($order['notes']): ?>
                                     <div class="detail-item">
                                         <span class="detail-label">Notes</span>
                                         <span class="detail-value"><?= htmlspecialchars($order['notes']) ?></span>
                                     </div>
                                 <?php endif; ?>
                                 
                                 <?php if ($order['source'] === 'kds' && in_array($order['order_status'], ['served', 'completed'])): ?>
                                     <div class="detail-item">
                                         <span class="detail-label">Actions</span>
                                         <div class="d-flex gap-2 mt-1">
                                             <button class="btn btn-sm btn-warning restore-btn" 
                                                     data-order-id="<?= $order['id'] ?>" 
                                                     data-restore-status="preparing"
                                                     onclick="restoreToKDS(<?= $order['id'] ?>, 'preparing')">
                                                 <i class="fas fa-undo me-1"></i>Restore to Preparing
                                             </button>
                                             <button class="btn btn-sm btn-success restore-btn" 
                                                     data-order-id="<?= $order['id'] ?>" 
                                                     data-restore-status="ready"
                                                     onclick="restoreToKDS(<?= $order['id'] ?>, 'ready')">
                                                 <i class="fas fa-undo me-1"></i>Restore to Ready
                                             </button>
                                         </div>
                                     </div>
                                 <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // 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.')) {
                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 again.');
                    
                    // 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);
        }
    </script>
</body>
</html>
