<?php
$active = 'user_orders';
$pageTitle = 'User Order Detail';
require_once __DIR__ . '/partials/top.php';
$pdo = db();

try { $pdo->query("SELECT 1 FROM user_orders LIMIT 1"); } catch (Exception $e) {
  echo "<div class='alert alert-warning'>User tables not found.</div>";
  require_once __DIR__ . '/partials/bottom.php';
  exit;
}

$id = (int)($_GET['id'] ?? 0);
if (!$id) { echo "<div class='alert alert-danger'>Order ID required</div>"; require_once __DIR__.'/partials/bottom.php'; exit; }

$stmt = $pdo->prepare("
  SELECT o.*, u.name user_name, u.phone user_phone, u.email user_email,
         a.label addr_label, a.address_line1, a.address_line2, a.city, a.state, a.pincode, a.phone addr_phone
  FROM user_orders o
  JOIN users u ON u.id=o.user_id
  LEFT JOIN user_addresses a ON a.id=o.address_id
  WHERE o.id=?
");
$stmt->execute([$id]);
$order = $stmt->fetch();
if (!$order) { echo "<div class='alert alert-danger'>Order not found</div>"; require_once __DIR__.'/partials/bottom.php'; exit; }

$items = $pdo->prepare("SELECT * FROM user_order_items WHERE order_id=? ORDER BY id");
$items->execute([$id]);
$items = $items->fetchAll();

$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
  $newStatus = $_POST['status'] ?? '';
  if (in_array($newStatus, ['pending','confirmed','in_progress','completed','cancelled'])) {
    $stmt = $pdo->prepare("UPDATE user_orders SET status=? WHERE id=?");
    $stmt->execute([$newStatus, $id]);
    $order['status'] = $newStatus;
    $msg = "<div class='alert alert-success'>Status updated.</div>";
  }
}

function orderStatusBadge($s) {
  $map = ['pending'=>'warning','confirmed'=>'info','in_progress'=>'primary','completed'=>'success','cancelled'=>'danger'];
  return '<span class="badge bg-' . ($map[$s] ?? 'secondary') . '">' . htmlspecialchars($s) . '</span>';
}
function paymentBadge($s) {
  $map = ['pending'=>'warning','paid'=>'success','refunded'=>'secondary'];
  return '<span class="badge bg-' . ($map[$s] ?? 'secondary') . '">' . htmlspecialchars($s) . '</span>';
}
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="fw-bold mb-0">Order <?php echo htmlspecialchars($order['order_number']); ?></h4>
    <div class="text-muted small">Placed <?php echo date('M d, Y H:i', strtotime($order['created_at'])); ?></div>
  </div>
  <a class="btn btn-outline-dark" href="user_orders.php">Back to Orders</a>
</div>

<?php echo $msg; ?>

<div class="row g-4">
  <div class="col-lg-8">
    <div class="card">
      <div class="card-header">Order Items</div>
      <div class="card-body p-0">
        <table class="table mb-0">
          <thead><tr><th>Service</th><th>Qty</th><th>Price</th><th>Total</th><th>Time Slot</th></tr></thead>
          <tbody>
            <?php foreach ($items as $i): ?>
            <tr>
              <td><?php echo htmlspecialchars($i['service_title']); ?></td>
              <td><?php echo (int)$i['quantity']; ?></td>
              <td>₹<?php echo number_format($i['price']); ?></td>
              <td>₹<?php echo number_format((int)$i['price'] * (int)$i['quantity']); ?></td>
              <td class="small"><?php echo htmlspecialchars($i['time_slot'] ?? '-'); ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="card">
      <div class="card-header">Summary</div>
      <div class="card-body">
        <table class="table table-sm mb-0">
          <tr><td>Subtotal</td><td class="text-end">₹<?php echo number_format($order['subtotal']); ?></td></tr>
          <?php if ((int)$order['discount_amount'] > 0): ?>
          <tr><td>Discount</td><td class="text-end text-success">-₹<?php echo number_format($order['discount_amount']); ?></td></tr>
          <?php endif; ?>
          <tr><td class="fw-bold">Total</td><td class="text-end fw-bold">₹<?php echo number_format($order['total_amount']); ?></td></tr>
        </table>
      </div>
    </div>

    <div class="card mt-3">
      <div class="card-header">Customer</div>
      <div class="card-body">
        <div><strong><?php echo htmlspecialchars($order['user_name']); ?></strong></div>
        <div class="small"><?php echo htmlspecialchars($order['user_phone']); ?></div>
        <div class="small"><?php echo htmlspecialchars($order['user_email'] ?? '-'); ?></div>
        <a class="btn btn-sm btn-outline-dark mt-2" href="users.php?q=<?php echo urlencode($order['user_phone']); ?>">View User</a>
      </div>
    </div>

    <div class="card mt-3">
      <div class="card-header">Delivery Address</div>
      <div class="card-body">
        <?php if ($order['address_line1']): ?>
        <div><?php echo htmlspecialchars($order['addr_label'] ?? 'Address'); ?></div>
        <div><?php echo htmlspecialchars($order['address_line1']); ?></div>
        <?php if ($order['address_line2']): ?><div><?php echo htmlspecialchars($order['address_line2']); ?></div><?php endif; ?>
        <div><?php echo htmlspecialchars($order['city'] . ', ' . $order['state'] . ' - ' . $order['pincode']); ?></div>
        <?php if ($order['addr_phone']): ?><div class="small"><?php echo htmlspecialchars($order['addr_phone']); ?></div><?php endif; ?>
        <?php else: ?>
        <div class="text-muted">No address</div>
        <?php endif; ?>
      </div>
    </div>

    <div class="card mt-3">
      <div class="card-header">Status & Payment</div>
      <div class="card-body">
        <div class="mb-2">Order: <?php echo orderStatusBadge($order['status']); ?></div>
        <div class="mb-3">Payment: <?php echo paymentBadge($order['payment_status']); ?> (<?php echo htmlspecialchars($order['payment_mode'] ?? 'online'); ?>)</div>
        <form method="post">
          <input type="hidden" name="update_status" value="1">
          <div class="mb-2">
            <select class="form-select form-select-sm" name="status">
              <option value="pending" <?php echo $order['status']==='pending'?'selected':''; ?>>Pending</option>
              <option value="confirmed" <?php echo $order['status']==='confirmed'?'selected':''; ?>>Confirmed</option>
              <option value="in_progress" <?php echo $order['status']==='in_progress'?'selected':''; ?>>In Progress</option>
              <option value="completed" <?php echo $order['status']==='completed'?'selected':''; ?>>Completed</option>
              <option value="cancelled" <?php echo $order['status']==='cancelled'?'selected':''; ?>>Cancelled</option>
            </select>
          </div>
          <button class="btn btn-dark btn-sm" type="submit">Update Status</button>
        </form>
      </div>
    </div>
  </div>
</div>
<?php require_once __DIR__ . '/partials/bottom.php'; ?>
