<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include('include/header.php');
$page_title = WEB_NAME . " | Gift Card Orders";

// ── Filters & Pagination ──────────────────────────────────────
$per_page    = 30;
$current_pg  = max(1, (int)($_GET['page'] ?? 1));
$offset      = ($current_pg - 1) * $per_page;
$search      = trim($_GET['q']      ?? '');
$filter_stat = trim($_GET['status'] ?? '');
$filter_date = trim($_GET['date']   ?? '');

$where  = [];
$params = [];

if ($search !== '') {
    $where[]      = "(o.recipient_email LIKE :q OR o.product_name LIKE :q2 OR o.custom_identifier LIKE :q3 OR o.reloadly_txn_id LIKE :q4)";
    $params[':q']  = "%{$search}%";
    $params[':q2'] = "%{$search}%";
    $params[':q3'] = "%{$search}%";
    $params[':q4'] = "%{$search}%";
}
if ($filter_stat !== '') {
    $where[]       = "o.status = :st";
    $params[':st'] = $filter_stat;
}
if ($filter_date !== '') {
    $where[]       = "DATE(o.created_at) = :dt";
    $params[':dt'] = $filter_date;
}

$sql_where = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$total_stmt = $pdo->prepare("SELECT COUNT(*) FROM gift_card_orders o {$sql_where}");
$total_stmt->execute($params);
$total_rows  = (int)$total_stmt->fetchColumn();
$total_pages = max(1, ceil($total_rows / $per_page));

$orders_stmt = $pdo->prepare("
    SELECT o.*, u.email AS user_email, u.username
    FROM gift_card_orders o
    LEFT JOIN users u ON u.id = o.user_id
    {$sql_where}
    ORDER BY o.created_at DESC
    LIMIT {$per_page} OFFSET {$offset}
");
$orders_stmt->execute($params);
$orders = $orders_stmt->fetchAll(PDO::FETCH_ASSOC);

// Summary stats
$stats = $pdo->query("
    SELECT
        COUNT(*) AS total,
        SUM(status = 'completed') AS completed,
        SUM(status = 'pending')   AS pending,
        SUM(status = 'failed')    AS failed,
        SUM(status = 'refunded')  AS refunded,
        SUM(CASE WHEN status='completed' THEN charge ELSE 0 END) AS revenue
    FROM gift_card_orders
")->fetch(PDO::FETCH_ASSOC);
?>

<title>Gift Card Orders | <?php echo htmlspecialchars($GLOBALS['site_data']['web_name'] ?? ''); ?></title>

<div class="container-fluid" id="container-wrapper">
  <div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">🎁 Gift Card Orders</h1>
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="dashboard">Home</a></li>
      <li class="breadcrumb-item"><a href="reloadly-settings">Reloadly</a></li>
      <li class="breadcrumb-item active">Orders</li>
    </ol>
  </div>

  <!-- ── Stat Cards ────────────────────────────────────────── -->
  <div class="row mb-4">
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
      <div class="card border-left-primary shadow h-100 py-2">
        <div class="card-body py-2">
          <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Orders</div>
          <div class="h5 mb-0 font-weight-bold"><?php echo number_format($stats['total']); ?></div>
        </div>
      </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
      <div class="card border-left-success shadow h-100 py-2">
        <div class="card-body py-2">
          <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Completed</div>
          <div class="h5 mb-0 font-weight-bold text-success"><?php echo number_format($stats['completed']); ?></div>
        </div>
      </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
      <div class="card border-left-warning shadow h-100 py-2">
        <div class="card-body py-2">
          <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Pending</div>
          <div class="h5 mb-0 font-weight-bold text-warning"><?php echo number_format($stats['pending']); ?></div>
        </div>
      </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
      <div class="card border-left-danger shadow h-100 py-2">
        <div class="card-body py-2">
          <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">Failed</div>
          <div class="h5 mb-0 font-weight-bold text-danger"><?php echo number_format($stats['failed']); ?></div>
        </div>
      </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
      <div class="card border-left-info shadow h-100 py-2">
        <div class="card-body py-2">
          <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Refunded</div>
          <div class="h5 mb-0 font-weight-bold text-info"><?php echo number_format($stats['refunded']); ?></div>
        </div>
      </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
      <div class="card border-left-success shadow h-100 py-2">
        <div class="card-body py-2">
          <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Revenue (NGN)</div>
          <div class="h5 mb-0 font-weight-bold text-success">₦<?php echo number_format($stats['revenue'] ?? 0, 2); ?></div>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Orders Table Card ──────────────────────────────────── -->
  <div class="card shadow mb-4">
    <div class="card-header py-3 d-flex align-items-center justify-content-between" style="background:linear-gradient(135deg,#1cc88a,#17a673);color:#fff;">
      <h6 class="m-0 font-weight-bold"><i class="fas fa-list mr-2"></i>Orders
        <span class="badge badge-light ml-2"><?php echo number_format($total_rows); ?> records</span>
      </h6>
      <a href="gift-card-orders?export=csv<?php echo $search ? '&q=' . urlencode($search) : ''; ?>" class="btn btn-sm btn-light">
        <i class="fas fa-file-csv mr-1"></i> Export CSV
      </a>
    </div>
    <div class="card-body pb-2">

      <!-- Filters -->
      <form method="GET" action="" class="row mb-3">
        <div class="col-md-4 mb-2">
          <div class="input-group">
            <div class="input-group-prepend"><span class="input-group-text"><i class="fas fa-search"></i></span></div>
            <input type="text" class="form-control" name="q" placeholder="Email, product, txn ID…" value="<?php echo htmlspecialchars($search); ?>">
          </div>
        </div>
        <div class="col-md-2 mb-2">
          <select class="form-control" name="status">
            <option value="">All Status</option>
            <option value="pending"   <?php echo $filter_stat === 'pending'   ? 'selected' : ''; ?>>Pending</option>
            <option value="completed" <?php echo $filter_stat === 'completed' ? 'selected' : ''; ?>>Completed</option>
            <option value="failed"    <?php echo $filter_stat === 'failed'    ? 'selected' : ''; ?>>Failed</option>
            <option value="refunded"  <?php echo $filter_stat === 'refunded'  ? 'selected' : ''; ?>>Refunded</option>
          </select>
        </div>
        <div class="col-md-2 mb-2">
          <input type="date" class="form-control" name="date" value="<?php echo htmlspecialchars($filter_date); ?>">
        </div>
        <div class="col-md-4 mb-2">
          <button type="submit" class="btn btn-primary mr-2"><i class="fas fa-filter mr-1"></i>Filter</button>
          <a href="gift-card-orders" class="btn btn-secondary">Reset</a>
        </div>
      </form>

      <!-- Table -->
      <div class="table-responsive">
        <table class="table table-hover table-sm table-bordered">
          <thead class="thead-dark">
            <tr>
              <th>#</th>
              <th>Date</th>
              <th>User</th>
              <th>Product</th>
              <th>Amount</th>
              <th>Charge (NGN)</th>
              <th>Recipient</th>
              <th>Txn ID</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($orders)): ?>
              <tr><td colspan="10" class="text-center text-muted py-4">
                <i class="fas fa-inbox fa-2x d-block mb-2"></i>No orders found.
              </td></tr>
            <?php else: ?>
              <?php foreach ($orders as $i => $o): ?>
                <?php
                  $badge = match($o['status']) {
                    'completed' => 'badge-success',
                    'pending'   => 'badge-warning',
                    'failed'    => 'badge-danger',
                    'refunded'  => 'badge-info',
                    default     => 'badge-secondary',
                  };
                ?>
                <tr>
                  <td><?php echo $offset + $i + 1; ?></td>
                  <td><small><?php echo date('d M Y H:i', strtotime($o['created_at'])); ?></small></td>
                  <td>
                    <small>
                      <?php echo htmlspecialchars($o['username'] ?? 'N/A'); ?><br>
                      <span class="text-muted"><?php echo htmlspecialchars($o['user_email'] ?? ''); ?></span>
                    </small>
                  </td>
                  <td>
                    <strong><?php echo htmlspecialchars($o['product_name']); ?></strong>
                    <br><small class="text-muted"><?php echo htmlspecialchars($o['brand_name'] ?? ''); ?> · <?php echo $o['country_code']; ?></small>
                  </td>
                  <td><?php echo $o['unit_price']; ?> <?php echo $o['currency_code']; ?></td>
                  <td><strong>₦<?php echo number_format($o['charge'], 2); ?></strong></td>
                  <td>
                    <small><?php echo htmlspecialchars($o['recipient_email']); ?></small>
                  </td>
                  <td>
                    <small class="text-monospace">
                      <?php echo $o['reloadly_txn_id'] ? '#' . $o['reloadly_txn_id'] : '—'; ?>
                    </small>
                  </td>
                  <td><span class="badge <?php echo $badge; ?>"><?php echo ucfirst($o['status']); ?></span></td>
                  <td>
                    <button class="btn btn-xs btn-info mb-1" onclick="viewOrder(<?php echo htmlspecialchars(json_encode($o)); ?>)" title="View Details">
                      <i class="fas fa-eye"></i>
                    </button>
                    <?php if ($o['status'] === 'pending'): ?>
                    <button class="btn btn-xs btn-success mb-1" onclick="markComplete(<?php echo $o['id']; ?>)" title="Mark Completed">
                      <i class="fas fa-check"></i>
                    </button>
                    <button class="btn btn-xs btn-danger mb-1" onclick="markFailed(<?php echo $o['id']; ?>)" title="Mark Failed">
                      <i class="fas fa-times"></i>
                    </button>
                    <?php endif; ?>
                    <?php if ($o['status'] === 'completed' && $o['reloadly_txn_id']): ?>
                    <button class="btn btn-xs btn-warning mb-1" onclick="fetchCard(<?php echo $o['id']; ?>, <?php echo $o['reloadly_txn_id']; ?>)" title="Fetch Card Code">
                      <i class="fas fa-key"></i>
                    </button>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <?php if ($total_pages > 1): ?>
      <nav>
        <ul class="pagination pagination-sm flex-wrap">
          <?php
          $qs = http_build_query(['q' => $search, 'status' => $filter_stat, 'date' => $filter_date]);
          for ($pg = 1; $pg <= $total_pages; $pg++):
          ?>
            <li class="page-item <?php echo $pg === $current_pg ? 'active' : ''; ?>">
              <a class="page-link" href="?<?php echo $qs; ?>&page=<?php echo $pg; ?>"><?php echo $pg; ?></a>
            </li>
          <?php endfor; ?>
        </ul>
      </nav>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- ══════════════════════════════════════════
     VIEW ORDER MODAL
══════════════════════════════════════════ -->
<div class="modal fade" id="viewOrderModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header" style="background:linear-gradient(135deg,#4e73df,#224abe);color:#fff;">
        <h5 class="modal-title"><i class="fas fa-receipt mr-2"></i>Order Details</h5>
        <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body" id="orderDetailBody">
        <!-- Populated by JS -->
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- ═══════ JS ═══════ -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// ── View Order Details ────────────────────────────────────────
function viewOrder(o) {
  var statusBadge = {completed:'success', pending:'warning', failed:'danger', refunded:'info'};
  var badge = statusBadge[o.status] || 'secondary';
  var card = o.card_number
    ? '<div class="alert alert-success mb-2"><strong>Card Code:</strong> <code>' + o.card_number + '</code>'
      + (o.card_pin ? '<br><strong>PIN:</strong> <code>' + o.card_pin + '</code>' : '')
      + (o.redeem_url ? '<br><a href="' + o.redeem_url + '" target="_blank">Redeem URL</a>' : '')
      + '</div>'
    : '<div class="alert alert-light border">No card code recorded yet.</div>';

  var html = `
    <div class="row">
      <div class="col-md-6">
        <table class="table table-sm table-bordered">
          <tr><th>Order ID</th><td>#${o.id}</td></tr>
          <tr><th>Product</th><td>${o.product_name}</td></tr>
          <tr><th>Brand</th><td>${o.brand_name || '—'}</td></tr>
          <tr><th>Country</th><td>${o.country_code}</td></tr>
          <tr><th>Unit Price</th><td>${o.unit_price} ${o.currency_code}</td></tr>
          <tr><th>Quantity</th><td>${o.quantity}</td></tr>
          <tr><th>NGN Rate</th><td>₦${parseFloat(o.ngn_rate).toLocaleString()}</td></tr>
          <tr><th>Charge (NGN)</th><td><strong>₦${parseFloat(o.charge).toLocaleString('en-NG',{minimumFractionDigits:2})}</strong></td></tr>
        </table>
      </div>
      <div class="col-md-6">
        <table class="table table-sm table-bordered">
          <tr><th>Status</th><td><span class="badge badge-${badge}">${o.status}</span></td></tr>
          <tr><th>Reloadly Txn ID</th><td>${o.reloadly_txn_id ? '#' + o.reloadly_txn_id : '—'}</td></tr>
          <tr><th>Reloadly Status</th><td>${o.reloadly_status || '—'}</td></tr>
          <tr><th>Recipient Email</th><td>${o.recipient_email}</td></tr>
          <tr><th>Sender Name</th><td>${o.sender_name || '—'}</td></tr>
          <tr><th>Custom ID</th><td><code>${o.custom_identifier}</code></td></tr>
          <tr><th>Created</th><td>${o.created_at}</td></tr>
          <tr><th>Updated</th><td>${o.updated_at}</td></tr>
        </table>
      </div>
    </div>
    ${card}
    ${o.notes ? '<div class="alert alert-light border"><strong>Notes:</strong> ' + o.notes + '</div>' : ''}
  `;
  document.getElementById('orderDetailBody').innerHTML = html;
  $('#viewOrderModal').modal('show');
}

// ── Mark Order Completed ──────────────────────────────────────
function markComplete(id) {
  Swal.fire({
    title: 'Mark as Completed?', icon: 'question',
    showCancelButton: true, confirmButtonColor: '#1cc88a',
    confirmButtonText: 'Yes, Complete'
  }).then(r => {
    if (!r.isConfirmed) return;
    $.post('ajax/reloadly_ajax.php', { action: 'update_order_status', id: id, status: 'completed' }, function(res) {
      if (res.status === '1') {
        Swal.fire({ icon: 'success', title: 'Done!', timer: 1500, showConfirmButton: false }).then(() => location.reload());
      } else { Swal.fire('Error', res.msg, 'error'); }
    }, 'json').fail(() => Swal.fire('Error', 'Server error.', 'error'));
  });
}

// ── Mark Order Failed ─────────────────────────────────────────
function markFailed(id) {
  Swal.fire({
    title: 'Mark as Failed?', icon: 'warning',
    showCancelButton: true, confirmButtonColor: '#e74a3b',
    confirmButtonText: 'Yes, Mark Failed'
  }).then(r => {
    if (!r.isConfirmed) return;
    $.post('ajax/reloadly_ajax.php', { action: 'update_order_status', id: id, status: 'failed' }, function(res) {
      if (res.status === '1') {
        Swal.fire({ icon: 'success', title: 'Done!', timer: 1500, showConfirmButton: false }).then(() => location.reload());
      } else { Swal.fire('Error', res.msg, 'error'); }
    }, 'json').fail(() => Swal.fire('Error', 'Server error.', 'error'));
  });
}

// ── Fetch Redeem Code from Reloadly ──────────────────────────
function fetchCard(orderId, txnId) {
  Swal.fire({ title: 'Fetching card code…', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
  $.post('ajax/reloadly_ajax.php', { action: 'fetch_card_code', order_id: orderId, txn_id: txnId }, function(res) {
    Swal.close();
    if (res.status === '1') {
      Swal.fire({
        icon: 'success', title: 'Card Code Retrieved!',
        html: '<div class="text-left">'
          + '<p><strong>Code:</strong> <code>' + res.card_number + '</code></p>'
          + (res.card_pin ? '<p><strong>PIN:</strong> <code>' + res.card_pin + '</code></p>' : '')
          + '</div>',
        confirmButtonColor: '#1cc88a'
      }).then(() => location.reload());
    } else { Swal.fire('Error', res.msg, 'error'); }
  }, 'json').fail(() => { Swal.close(); Swal.fire('Error', 'Server error.', 'error'); });
}
</script>

<?php include('include/footer.php'); ?>