<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Kitchen Orders List
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path
$base_path = null;

// Method 1: Try dirname(__DIR__, 3)
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// Method 3: If still not found, use absolute path
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Load required files
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/helpers.php';
require_once $base_path . '/config/auth.php';

// Require authentication
require_auth();

// Set page title
$page_title = 'Kitchen Orders';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

if (!$user_id) {
    if (function_exists('redirect')) {
        redirect('login.php');
    } else {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Get filter parameters
$status = isset($_GET['status']) ? $_GET['status'] : 'pending';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : date('Y-m-d');
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : date('Y-m-d');

// Build where clause
$where = "DATE(o.created_at) BETWEEN ? AND ?";
$params = [$date_from, $date_to];

if ($status !== 'all') {
    $where .= " AND o.status = ?";
    $params[] = $status;
}

// Get kitchen orders
$orders = [];
try {
    $orders = db_fetch_all("
        SELECT 
            o.*,
            s.receipt_number,
            s.customer_name,
            u.first_name, u.last_name,
            ol.outlet_name,
            (SELECT COUNT(*) FROM pos_sale_items WHERE sale_id = s.sale_id) as item_count
        FROM kitchen_orders o
        JOIN pos_sales s ON o.sale_id = s.sale_id
        JOIN users u ON o.created_by = u.user_id
        JOIN pos_outlets ol ON o.outlet_id = ol.outlet_id
        WHERE $where
        ORDER BY o.created_at DESC
    ", $params) ?: [];
} catch (Exception $e) {
    error_log("Error fetching kitchen orders: " . $e->getMessage());
}

// Include header
$header_path = BASE_PATH . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Kitchen Orders</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Orders</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> <?php echo htmlspecialchars($current_user['username'] ?? 'User'); ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Orders</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/pos/dashboard.php">POS</a></li>
                    <li class="breadcrumb-item active">Orders</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Filters -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Filters</h3>
            </div>
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <label for="status">Status</label>
                        <select class="form-select" id="status" name="status">
                            <option value="all" <?php echo $status == 'all' ? 'selected' : ''; ?>>All Orders</option>
                            <option value="pending" <?php echo $status == 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="preparing" <?php echo $status == 'preparing' ? 'selected' : ''; ?>>Preparing</option>
                            <option value="ready" <?php echo $status == 'ready' ? 'selected' : ''; ?>>Ready</option>
                            <option value="served" <?php echo $status == 'served' ? 'selected' : ''; ?>>Served</option>
                            <option value="cancelled" <?php echo $status == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label for="date_from">From</label>
                        <input type="date" class="form-control" id="date_from" name="date_from" value="<?php echo $date_from; ?>">
                    </div>
                    <div class="col-md-3">
                        <label for="date_to">To</label>
                        <input type="date" class="form-control" id="date_to" name="date_to" value="<?php echo $date_to; ?>">
                    </div>
                    <div class="col-md-3">
                        <label>&nbsp;</label>
                        <button type="submit" class="btn btn-primary w-100">Apply Filters</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Orders Table -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Orders</h3>
            </div>
            <div class="card-body p-0">
                <?php if (empty($orders)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-utensils fa-4x mb-3"></i>
                        <h5>No orders found</h5>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Order #</th>
                                    <th>Receipt #</th>
                                    <th>Customer</th>
                                    <th>Outlet</th>
                                    <th>Items</th>
                                    <th>Status</th>
                                    <th>Created By</th>
                                    <th>Time</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($orders as $order): ?>
                                <tr>
                                    <td><strong><?php echo htmlspecialchars($order['order_number']); ?></strong></td>
                                    <td><?php echo htmlspecialchars($order['receipt_number']); ?></td>
                                    <td><?php echo htmlspecialchars($order['customer_name']); ?></td>
                                    <td><?php echo htmlspecialchars($order['outlet_name']); ?></td>
                                    <td class="text-center"><?php echo $order['item_count']; ?></td>
                                    <td>
                                        <span class="badge bg-<?php 
                                            echo $order['status'] == 'pending' ? 'warning' : 
                                                ($order['status'] == 'preparing' ? 'info' : 
                                                ($order['status'] == 'ready' ? 'primary' : 
                                                ($order['status'] == 'served' ? 'success' : 
                                                ($order['status'] == 'cancelled' ? 'danger' : 'secondary'))));
                                        ?>">
                                            <?php echo ucfirst($order['status']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo htmlspecialchars($order['first_name'] . ' ' . $order['last_name']); ?></td>
                                    <td><?php echo date('H:i', strtotime($order['created_at'])); ?></td>
                                    <td>
                                        <a href="kitchen-order.php?id=<?php echo $order['sale_id']; ?>" class="btn btn-sm btn-info" target="_blank">
                                            <i class="fas fa-print"></i> Print
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<?php
// Include footer
$footer_path = BASE_PATH . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>