<?php
include 'includes/header.php';

// --- Logic: Update Status ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_status'])) {
    $order_id = $_POST['order_id'];
    $status = $_POST['status'];
    $pdo->prepare("UPDATE orders SET status = ? WHERE id = ?")->execute([$status, $order_id]);
    
    // Refresh to remove post data
    echo "<script>window.location.href='orders.php';</script>";
}

// --- Logic: View Order Details (Modal Data) ---
$viewOrder = null;
$orderItems = [];
if (isset($_GET['view_order'])) {
    $viewId = $_GET['view_order'];
    
    // Fetch Order Info
    $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ?");
    $stmt->execute([$viewId]);
    $viewOrder = $stmt->fetch();

    if ($viewOrder) {
        // Fetch Order Items with Product Details
        $stmtItems = $pdo->prepare("
            SELECT oi.*, p.name as product_name, p.image 
            FROM order_items oi 
            LEFT JOIN products p ON oi.product_id = p.id 
            WHERE oi.order_id = ?
        ");
        $stmtItems->execute([$viewId]);
        $orderItems = $stmtItems->fetchAll();
    }
}

// --- Logic: Fetch All Orders ---
$sql = "SELECT * FROM orders ORDER BY created_at DESC";
$orders = $pdo->query($sql)->fetchAll();

// Calculate Stats
$totalRevenue = 0;
foreach($orders as $o) {
    if($o['status'] != 'cancelled') $totalRevenue += $o['total_amount'];
}
?>

<!-- Page Heading & Stats -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="fw-bold text-dark mb-1">Order Management</h2>
        <p class="text-muted mb-0">Track and manage customer orders.</p>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-lg-3">
        <div class="card border-0 shadow-sm p-3">
            <div class="d-flex align-items-center">
                <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 48px; height: 48px;">
                    <i class="fas fa-shopping-bag fa-lg"></i>
                </div>
                <div>
                    <h6 class="text-muted text-uppercase small fw-bold mb-0">Total Orders</h6>
                    <h3 class="fw-bold mb-0"><?= count($orders) ?></h3>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-6 col-lg-3">
        <div class="card border-0 shadow-sm p-3">
            <div class="d-flex align-items-center">
                <div class="bg-success text-white rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 48px; height: 48px;">
                    <i class="fas fa-dollar-sign fa-lg"></i>
                </div>
                <div>
                    <h6 class="text-muted text-uppercase small fw-bold mb-0">Total Revenue</h6>
                    <h3 class="fw-bold mb-0">$<?= number_format($totalRevenue, 2) ?></h3>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Orders Table Card -->
<div class="card shadow-sm border-0">
    <div class="card-header bg-white py-3 fw-bold border-bottom d-flex justify-content-between align-items-center">
        <span><i class="fas fa-list text-primary me-2"></i> Recent Orders</span>
        <button class="btn btn-sm btn-light border" onclick="window.location.reload()"><i class="fas fa-sync-alt"></i></button>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="bg-light text-muted small text-uppercase">
                    <tr>
                        <th class="ps-4">Order ID</th>
                        <th>Customer</th>
                        <th>Status</th>
                        <th>Total</th>
                        <th>Date</th>
                        <th class="text-end pe-4">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($orders)): ?>
                        <tr><td colspan="6" class="text-center py-5 text-muted">No orders found.</td></tr>
                    <?php else: ?>
                        <?php foreach($orders as $o): ?>
                        <tr>
                            <td class="ps-4 fw-bold">#<?= $o['id'] ?></td>
                            <td>
                                <?php if($o['user_id']): ?>
                                    <div class="d-flex align-items-center">
                                        <div class="bg-light rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 35px; height: 35px;">
                                            <i class="fas fa-user text-secondary"></i>
                                        </div>
                                        <div>
                                            <span class="d-block fw-bold text-dark">Member</span>
                                            <small class="text-muted">User ID: <?= $o['user_id'] ?></small>
                                        </div>
                                    </div>
                                <?php else: ?>
                                    <div class="d-flex align-items-center">
                                        <div class="bg-light rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 35px; height: 35px;">
                                            <i class="fas fa-user-secret text-secondary"></i>
                                        </div>
                                        <div>
                                            <span class="d-block fw-bold text-dark"><?= htmlspecialchars($o['guest_name'] ?? 'Guest') ?></span>
                                            <small class="text-muted"><?= htmlspecialchars($o['guest_email']) ?></small>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <form method="POST" class="d-inline-block">
                                    <input type="hidden" name="order_id" value="<?= $o['id'] ?>">
                                    <input type="hidden" name="update_status" value="1">
                                    <select name="status" class="form-select form-select-sm border-0 fw-bold px-2 py-1" 
                                        onchange="this.form.submit()" 
                                        style="width: auto; cursor:pointer; 
                                        background-color: <?= $o['status']=='completed'?'#d1e7dd':($o['status']=='cancelled'?'#f8d7da':'#fff3cd') ?>; 
                                        color: <?= $o['status']=='completed'?'#0f5132':($o['status']=='cancelled'?'#842029':'#664d03') ?>;">
                                        <option value="pending" <?= $o['status'] == 'pending' ? 'selected' : '' ?>>Pending</option>
                                        <option value="completed" <?= $o['status'] == 'completed' ? 'selected' : '' ?>>Completed</option>
                                        <option value="cancelled" <?= $o['status'] == 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                                    </select>
                                </form>
                            </td>
                            <td class="fw-bold">$<?= number_format($o['total_amount'], 2) ?></td>
                            <td class="text-muted small"><?= date('M d, Y', strtotime($o['created_at'])) ?></td>
                            <td class="text-end pe-4">
                                <a href="orders.php?view_order=<?= $o['id'] ?>" class="btn btn-sm btn-primary shadow-sm">
                                    View Items
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- View Order Modal -->
<?php if ($viewOrder): ?>
<div class="modal fade" id="orderModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content border-0 shadow">
      <div class="modal-header bg-dark text-white">
        <h5 class="modal-title">Order Details #<?= $viewOrder['id'] ?></h5>
        <a href="orders.php" class="btn-close btn-close-white" aria-label="Close"></a>
      </div>
      <div class="modal-body bg-light">
          <!-- Customer Info -->
          <div class="card mb-3 border-0 shadow-sm">
              <div class="card-body">
                  <h6 class="fw-bold border-bottom pb-2 mb-3 text-uppercase small text-muted">Customer Information</h6>
                  <div class="row">
                      <div class="col-md-6">
                          <strong>Name:</strong> <?= htmlspecialchars($viewOrder['guest_name'] ?? 'N/A') ?><br>
                          <strong>Email:</strong> <?= htmlspecialchars($viewOrder['guest_email'] ?? 'N/A') ?>
                      </div>
                      <div class="col-md-6">
                           <strong>Address:</strong><br>
                           <?= nl2br(htmlspecialchars($viewOrder['address'])) ?>
                      </div>
                  </div>
              </div>
          </div>

          <!-- Items List -->
          <div class="card border-0 shadow-sm">
              <div class="card-body p-0">
                  <div class="table-responsive">
                    <table class="table table-borderless align-middle mb-0">
                        <thead class="bg-white border-bottom">
                            <tr class="text-muted small text-uppercase">
                                <th class="ps-3">Product</th>
                                <th class="text-center">Price</th>
                                <th class="text-center">Qty</th>
                                <th class="text-end pe-3">Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($orderItems as $item): ?>
                            <tr class="border-bottom">
                                <td class="ps-3">
                                    <div class="d-flex align-items-center">
                                        <?php if($item['image']): ?>
                                            <img src="../<?= $item['image'] ?>" width="40" height="40" class="rounded border me-2 object-fit-cover">
                                        <?php endif; ?>
                                        <span class="fw-bold text-dark"><?= htmlspecialchars($item['product_name']) ?></span>
                                    </div>
                                </td>
                                <td class="text-center">$<?= number_format($item['price'], 2) ?></td>
                                <td class="text-center"><span class="badge bg-secondary"><?= $item['quantity'] ?></span></td>
                                <td class="text-end pe-3 fw-bold">$<?= number_format($item['price'] * $item['quantity'], 2) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot class="bg-white">
                            <tr>
                                <td colspan="3" class="text-end fw-bold pt-3">Grand Total:</td>
                                <td class="text-end pe-3 fw-bold text-primary fs-5 pt-3">$<?= number_format($viewOrder['total_amount'], 2) ?></td>
                            </tr>
                        </tfoot>
                    </table>
                  </div>
              </div>
          </div>
      </div>
      <div class="modal-footer">
        <a href="orders.php" class="btn btn-secondary">Close</a>
      </div>
    </div>
  </div>
</div>

<!-- Auto-trigger modal if view_order is set -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        var myModal = new bootstrap.Modal(document.getElementById('orderModal'));
        myModal.show();
    });
</script>
<?php endif; ?>

<!-- Closing divs matching the opening structure in header.php -->
</div></div></div>
</body>
</html>