<?php
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Enable error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors on page
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

session_start();
require_once('../includes/admin-security.php');
include_once('includes/config.php');

// Access Check
if (!has_permission('manage_orders')) {
    echo "<script>alert('Access Denied. Redirecting to Dashboard...'); window.location.href='dashboard.php';</script>";
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>All Orders - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
    <link href="css/styles.css?v=4.0" rel="stylesheet" />
    <link href="css/admin-professional.css?v=4.0" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"
        crossorigin="anonymous"></script>
</head>

<body class="sb-nav-fixed">
    <?php include_once('includes/header.php'); ?>

    <div id="layoutSidenav">
        <?php include_once('includes/sidebar.php'); ?>

        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <!-- Page Header -->
                    <div class="page-header mt-4">
                        <div>
                            <h1><i class="fas fa-shopping-bag me-2"></i> All Orders</h1>
                            <p>View and manage all customer orders</p>
                        </div>
                        <div class="d-flex gap-2">
                            <!-- Export Dropdown -->
                            <div class="dropdown">
                                <button class="btn btn-success dropdown-toggle" type="button" id="exportDropdown"
                                    data-bs-toggle="dropdown" aria-expanded="false">
                                    <i class="fas fa-download me-2"></i>Export
                                </button>
                                <ul class="dropdown-menu" aria-labelledby="exportDropdown">
                                    <li><a class="dropdown-item" href="export-orders.php?status=all">
                                            <i class="fas fa-file-csv me-2"></i>Export All (CSV)
                                        </a></li>
                                    <li><a class="dropdown-item" href="export-orders.php?status=Pending">
                                            <i class="fas fa-file-csv me-2"></i>Export Pending
                                        </a></li>
                                    <li><a class="dropdown-item" href="export-orders.php?status=Delivered">
                                            <i class="fas fa-file-csv me-2"></i>Export Delivered
                                        </a></li>
                                </ul>
                            </div>

                            <!-- Filter Button -->
                            <button class="btn btn-outline-primary" data-bs-toggle="modal"
                                data-bs-target="#filterModal">
                                <i class="fas fa-filter me-2"></i>Filter
                            </button>
                        </div>
                    </div>

                    <!-- Filter Modal -->
                    <div class="modal fade" id="filterModal" tabindex="-1" aria-hidden="true">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title"><i class="fas fa-filter me-2"></i>Filter Orders</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>
                                <div class="modal-body">
                                    <form method="get" action="all-orders.php">
                                        <div class="mb-3">
                                            <label class="form-label">Order Status</label>
                                            <select name="status" class="form-select">
                                                <option value="">All Statuses</option>
                                                <option value="Pending">Pending</option>
                                                <option value="Packed">Packed</option>
                                                <option value="Dispatched">Dispatched</option>
                                                <option value="In Transit">In Transit</option>
                                                <option value="Delivered">Delivered</option>
                                                <option value="Cancelled">Cancelled</option>
                                            </select>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Date Range</label>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <input type="date" name="from_date" class="form-control"
                                                        placeholder="From">
                                                </div>
                                                <div class="col-md-6">
                                                    <input type="date" name="to_date" class="form-control"
                                                        placeholder="To">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Amount Range</label>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <input type="number" name="min_amount" class="form-control"
                                                        placeholder="Min $">
                                                </div>
                                                <div class="col-md-6">
                                                    <input type="number" name="max_amount" class="form-control"
                                                        placeholder="Max $">
                                                </div>
                                            </div>
                                        </div>
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="fas fa-check me-2"></i>Apply Filters
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Stats -->
                    <div class="stats-row">
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <div class="stat-mini">
                                    <div class="icon">
                                        <i class="fas fa-shopping-cart"></i>
                                    </div>
                                    <div class="details">
                                        <div class="label">Total Orders</div>
                                        <div class="value">
                                            <?php
                                            $total = mysqli_query($con, "SELECT COUNT(*) as total FROM orders");
                                            $totalOrders = mysqli_fetch_assoc($total);
                                            echo $totalOrders['total'];
                                            ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-3 mb-3">
                                <div class="stat-mini">
                                    <div class="icon">
                                        <i class="fas fa-clock"></i>
                                    </div>
                                    <div class="details">
                                        <div class="label">Pending</div>
                                        <div class="value">
                                            <?php
                                            $pending = mysqli_query($con, "SELECT COUNT(*) as total FROM orders WHERE orderStatus='' OR orderStatus IS NULL");
                                            $pendingOrders = mysqli_fetch_assoc($pending);
                                            echo $pendingOrders['total'];
                                            ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-3 mb-3">
                                <div class="stat-mini">
                                    <div class="icon">
                                        <i class="fas fa-check-circle"></i>
                                    </div>
                                    <div class="details">
                                        <div class="label">Delivered</div>
                                        <div class="value">
                                            <?php
                                            $delivered = mysqli_query($con, "SELECT COUNT(*) as total FROM orders WHERE orderStatus='Delivered'");
                                            $deliveredOrders = mysqli_fetch_assoc($delivered);
                                            echo $deliveredOrders['total'];
                                            ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-3 mb-3">
                                <div class="stat-mini">
                                    <div class="icon">
                                        <i class="fas fa-times-circle"></i>
                                    </div>
                                    <div class="details">
                                        <div class="label">Cancelled</div>
                                        <div class="value">
                                            <?php
                                            $cancelled = mysqli_query($con, "SELECT COUNT(*) as total FROM orders WHERE orderStatus='Cancelled'");
                                            $cancelledOrders = mysqli_fetch_assoc($cancelled);
                                            echo $cancelledOrders['total'];
                                            ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Orders Table -->
                    <div class="table-card">
                        <table class="table table-hover" id="datatablesSimple">
                            <thead>
                                <tr>
                                    <th width="5%">#</th>
                                    <th>Order No.</th>
                                    <th>Customer</th>
                                    <th>Amount</th>
                                    <th>Order Date</th>
                                    <th>Status</th>
                                    <th width="10%">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $query = mysqli_query($con, "SELECT orders.id, orderNumber, totalAmount, orderStatus, orderDate, user_details.name, user_details.contactno 
                                                              FROM orders 
                                                              JOIN users ON users.id = orders.userId
                                                              LEFT JOIN user_details ON user_details.user_id = users.id
                                                              ORDER BY orders.id DESC");
                                $cnt = 1;
                                while ($row = mysqli_fetch_array($query)) {
                                    // Determine status badge class
                                    $status = $row['orderStatus'] ?: 'Pending';
                                    $statusClass = 'pending';
                                    if ($status == 'Delivered')
                                        $statusClass = 'delivered';
                                    elseif ($status == 'Cancelled')
                                        $statusClass = 'cancelled';
                                    elseif ($status == 'Dispatched')
                                        $statusClass = 'dispatched';
                                    elseif ($status == 'Packed')
                                        $statusClass = 'packed';
                                    elseif ($status == 'In Transit')
                                        $statusClass = 'intransit';
                                    elseif ($status == 'Out For Delivery')
                                        $statusClass = 'outfordelivery';
                                    ?>
                                    <tr>
                                        <td><?php echo $cnt; ?></td>
                                        <td><strong><?php echo htmlentities($row['orderNumber']); ?></strong></td>
                                        <td><?php echo htmlentities($row['name']); ?></td>
                                        <td><strong>$<?php echo number_format($row['totalAmount'], 2); ?></strong></td>
                                        <td><?php echo date('M d, Y', strtotime($row['orderDate'])); ?></td>
                                        <td>
                                            <span class="status-badge <?php echo $statusClass; ?>">
                                                <?php echo $status; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <a href="order-details.php?orderid=<?php echo $row['id']; ?>"
                                                class="btn btn-sm btn-outline-primary" title="View Details">
                                                <i class="fas fa-eye me-1"></i> View
                                            </a>
                                        </td>
                                    </tr>
                                    <?php $cnt++;
                                } ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
        crossorigin="anonymous"></script>
    <script src="js/scripts.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/simple-datatables@latest" crossorigin="anonymous"></script>
    <script src="js/datatables-simple-demo.js"></script>
</body>

</html>