<?php
include('../includes/session.php');
include('../includes/config.php');
include('trick_buy_common.php');
include('../template/ahkweb/header.php');

header('Content-Type: text/html; charset=UTF-8');

$userPhone = $udata['phone'] ?? '';
$userId    = isset($udata['id']) ? (int)$udata['id'] : 0;

if ($userPhone !== '') {
    $stmt = mysqli_prepare($ahk_conn,
        "SELECT * FROM trick_orders WHERE user_phone=? " . ($userId > 0 ? "OR user_id={$userId}" : '') . " ORDER BY id DESC");
    mysqli_stmt_bind_param($stmt, 's', $userPhone);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $orders = [];
    while ($row = mysqli_fetch_assoc($result)) $orders[] = $row;
    mysqli_stmt_close($stmt);
} else {
    $orders = [];
}

$submitted = isset($_GET['submitted']) ? (int)$_GET['submitted'] === 1 : false;
?>
  <div class="page-wrapper">
    <div class="page-content">
      <div class="row justify-content-center">
        <div class="col-12">
          <div class="card border-0 shadow">
            <div class="card-body p-3 p-md-4">
              <div class="d-flex justify-content-between align-items-center flex-wrap mb-3">
                <h3 class="mb-0">My Trick Orders</h3>
                <a href="trick_buy.php" class="btn btn-primary"><i class="bi bi-plus me-1"></i> New Order</a>
              </div>

              <div class="table-responsive">
                <table class="table table-hover align-middle">
                  <thead class="table-light">
                    <tr>
                      <th>#</th>
                      <th>App No.</th>
                      <th>Service</th>
                      <th>WhatsApp</th>
                      <th>AnyDesk</th>
                      <th>Note</th>
                      <th>Amount</th>
                      <th>Status</th>
                      <th>Date</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php if (!$orders): ?>
                      <tr><td colspan="10" class="text-center py-5 text-muted"><i class="bi bi-inbox"></i> No orders yet. Place your first order!</td></tr>
                    <?php
                    endif;
                    $idx = 0;
                    foreach ($orders as $row):
                        $idx++;
                        $statusBadge = match($row['status']) {
                            'pending'    => '<span class="badge bg-warning text-dark">PENDING</span>',
                            'processing' => '<span class="badge bg-info text-white">PROCESSING</span>',
                            'completed'  => '<span class="badge bg-success">COMPLETED</span>',
                            'rejected'   => '<span class="badge bg-danger">REJECTED</span>',
                            'refunded'   => '<span class="badge bg-secondary">REFUNDED</span>',
                            'cancelled'  => '<span class="badge bg-dark">CANCELLED</span>',
                            default      => '<span class="badge bg-light text-dark">'.htmlspecialchars($row['status']).'</span>',
                        };
                        $download = '';
                        if ($row['attachment_path']) {
                            $download = '<a class="btn btn-sm btn-outline-success" href="uploads/trick_orders/' . htmlspecialchars($row['attachment_path']) . '" target="_blank"><i class="bi bi-download"></i> Download</a>';
                        }
                    ?>
                      <tr>
                        <td><?= $idx ?></td>
                        <td class="font-monospace small"><?= htmlspecialchars($row['application_no']) ?></td>
                        <td><?= htmlspecialchars($row['service_label']) ?></td>
                        <td><?= htmlspecialchars($row['whatsapp_number']) ?></td>
                        <td><?= htmlspecialchars($row['anydesk_id']) ?></td>
                        <td class="small text-muted"><?= htmlspecialchars(mb_substr($row['customer_note'] ?? '', 0, 60)) ?>
                            <?php if ($row['rejection_reason']): ?><br><span class="text-danger">Reason: <?= htmlspecialchars($row['rejection_reason']) ?></span><?php endif; ?>
                            <?php if ($row['admin_note']): ?><br><span class="text-primary">Admin: <?= htmlspecialchars(mb_substr($row['admin_note'],0,60)) ?></span><?php endif; ?>
                        </td>
                        <td>₹<?= number_format((float)$row['amount'], 2) ?></td>
                        <td><?= $statusBadge ?></td>
                        <td class="small text-muted"><?= htmlspecialchars($row['created_at']) ?></td>
                        <td><?= $download ?></td>
                      </tr>
                    <?php endforeach; ?>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

<?php include('footers.php');
if ($submitted) trickAlert('Order Submitted', 'Amount deducted from wallet. Admin will review and deliver soon.', 'success');
?>
