<?php
require_once __DIR__ . '/../config.php';
requireAdmin();
$db     = getDB();
$view   = (int)($_GET['view'] ?? 0);
$msg    = '';

// Update status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_order'])) {
    $oid    = (int)$_POST['order_id'];
    $ostatus = $_POST['order_status'] ?? 'pending';
    $pstatus = $_POST['payment_status'] ?? 'pending';
    $db->prepare("UPDATE orders SET order_status=?,payment_status=? WHERE id=?")->execute([$ostatus,$pstatus,$oid]);
    $msg = 'Order updated.';
    $view = $oid;
}

// Single order view
$order = null; $items = [];
if ($view) {
    $order = $db->query("SELECT o.*,c.email AS cust_email,c.phone AS cust_phone FROM orders o LEFT JOIN customers c ON o.customer_id=c.id WHERE o.id=$view")->fetch();
    if ($order) $items = $db->query("SELECT * FROM order_items WHERE order_id=$view")->fetchAll();
}

// List
$orders = $db->query("SELECT o.*,c.name AS cust_name FROM orders o LEFT JOIN customers c ON o.customer_id=c.id ORDER BY o.created_at DESC")->fetchAll();

$page_title = 'Orders';
include __DIR__ . '/header.php';
?>
<?php if ($msg): ?><div class="alert alert-success"><?= h($msg) ?></div><?php endif; ?>

<?php if ($order): ?>
<!-- Single Order View -->
<div style="margin-bottom:14px;"><a href="orders.php" style="color:var(--blue-main);">← All Orders</a></div>
<div style="display:grid;grid-template-columns:1fr 340px;gap:20px;align-items:start;">
  <div>
    <div class="card" style="margin-bottom:16px;">
      <div class="card-header"><h2>Order #<?= h($order['order_no']) ?></h2><span class="badge badge-<?= $order['order_status']==='delivered'?'active':'new' ?>"><?= ucfirst($order['order_status']) ?></span></div>
      <div class="card-body">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;font-size:.88rem;">
          <?php $rows=['Customer'=>$order['name'],'Phone'=>$order['phone'],'Email'=>$order['email'],'Payment'=>ucwords(str_replace('_',' ',$order['payment_method'])),'City/State'=>$order['city'].', '.$order['state'],'PIN'=>$order['pincode'],'Date'=>date('d M Y H:i',strtotime($order['created_at'])),'Notes'=>$order['notes']]; ?>
          <?php foreach ($rows as $k=>$v): if(!$v) continue; ?>
          <div><span style="font-weight:600;color:var(--text-mid);"><?= h($k) ?>:</span><br><?= h($v) ?></div>
          <?php endforeach; ?>
        </div>
        <div style="margin-top:14px;padding-top:14px;border-top:1px solid #f1f5f9;font-size:.88rem;color:var(--text-mid);">
          <strong>Address:</strong> <?= h($order['address']) ?>
        </div>
      </div>
    </div>
    <div class="card">
      <div class="card-header"><h2>Order Items</h2></div>
      <div class="table-wrap">
        <table>
          <thead><tr><th>Image</th><th>Product</th><th>Price</th><th>Qty</th><th>Subtotal</th></tr></thead>
          <tbody>
            <?php foreach ($items as $it): ?>
            <tr>
              <td><img src="<?= SITE_URL ?>/assets/images/<?= h($it['product_image']) ?>" class="img-preview" alt=""></td>
              <td><strong><?= h($it['product_name']) ?></strong></td>
              <td><?= rupee($it['price']) ?></td>
              <td><?= $it['qty'] ?></td>
              <td><?= rupee($it['subtotal']) ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
          <tfoot>
            <tr><td colspan="4" style="text-align:right;font-weight:700;padding:10px 14px;">Subtotal</td><td><?= rupee($order['subtotal']) ?></td></tr>
            <tr><td colspan="4" style="text-align:right;font-weight:700;padding:4px 14px;">Shipping</td><td><?= rupee($order['shipping']) ?></td></tr>
            <tr style="background:#f8fafc;"><td colspan="4" style="text-align:right;font-weight:800;padding:10px 14px;color:var(--blue-dark);font-family:'Outfit',sans-serif;">TOTAL</td><td style="font-family:'Outfit',sans-serif;font-weight:800;color:var(--blue-main);font-size:1.05rem;"><?= rupee($order['total']) ?></td></tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>
  <!-- Update Status -->
  <div class="card">
    <div class="card-header"><h2>Update Status</h2></div>
    <div class="card-body">
      <form method="POST">
        <input type="hidden" name="update_order" value="1">
        <input type="hidden" name="order_id" value="<?= $order['id'] ?>">
        <div class="form-group">
          <label>Order Status</label>
          <select name="order_status">
            <?php foreach(['pending','confirmed','processing','shipped','delivered','cancelled'] as $s): ?>
            <option value="<?= $s ?>" <?= $order['order_status']===$s?'selected':'' ?>><?= ucfirst($s) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label>Payment Status</label>
          <select name="payment_status">
            <?php foreach(['pending','paid','failed'] as $s): ?>
            <option value="<?= $s ?>" <?= $order['payment_status']===$s?'selected':'' ?>><?= ucfirst($s) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <button type="submit" class="btn-primary" style="width:100%;justify-content:center;">Update Order</button>
      </form>
      <div style="margin-top:16px;padding-top:16px;border-top:1px solid #f1f5f9;">
        <a href="tel:<?= h($order['phone']) ?>" class="btn-primary" style="background:var(--success);width:100%;display:flex;justify-content:center;padding:10px;">📞 Call Customer</a>
      </div>
    </div>
  </div>
</div>

<?php else: ?>
<!-- Orders List -->
<div class="card">
  <div class="card-header">
    <h2>All Orders (<?= count($orders) ?>)</h2>
    <a href="customers.php" style="font-size:.82rem;color:var(--blue-main);">View Customers →</a>
  </div>
  <div class="table-wrap">
    <table>
      <thead><tr><th>Order No</th><th>Customer</th><th>Amount</th><th>Payment</th><th>Date</th><th>Order Status</th><th>Action</th></tr></thead>
      <tbody>
        <?php foreach ($orders as $o): ?>
        <tr>
          <td><strong style="color:var(--blue-main);"><?= h($o['order_no']) ?></strong></td>
          <td><?= h($o['cust_name']) ?><br><span style="font-size:.74rem;color:var(--text-light);"><?= h($o['phone']) ?></span></td>
          <td><strong><?= rupee($o['total']) ?></strong></td>
          <td><span style="font-size:.78rem;"><?= ucwords(str_replace('_',' ',$o['payment_method'])) ?></span></td>
          <td><?= date('d M Y', strtotime($o['created_at'])) ?></td>
          <td><span class="status-badge status-<?= $o['order_status'] ?>"><?= ucfirst($o['order_status']) ?></span></td>
          <td><a href="?view=<?= $o['id'] ?>" class="btn-action btn-view">View</a></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>

<?php include __DIR__ . '/footer.php'; ?>
