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

// Filters & pagination
$per_page    = 25;
$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.type_name LIKE :q OR o.account_number LIKE :q2 OR o.account_name LIKE :q3 OR u.email LIKE :q4 OR u.username LIKE :q5)";
    $params[':q']  = "%{$search}%";
    $params[':q2'] = "%{$search}%";
    $params[':q3'] = "%{$search}%";
    $params[':q4'] = "%{$search}%";
    $params[':q5'] = "%{$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 sell_giftcard_orders o LEFT JOIN users u ON u.id = o.user_id {$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, u.phone AS user_phone
    FROM sell_giftcard_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='pending')  AS pending,
           SUM(status='approved') AS approved,
           SUM(status='rejected') AS rejected,
           SUM(CASE WHEN status='approved' THEN ngn_payout ELSE 0 END) AS revenue
    FROM sell_giftcard_orders")->fetch(PDO::FETCH_ASSOC);
?>

<title>Sell 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">🏷️ Sell Gift Card Orders</h1>
    <ol class="breadcrumb mb-0">
      <li class="breadcrumb-item"><a href="dashboard">Home</a></li>
      <li class="breadcrumb-item"><a href="sell-giftcard-types-admin">Card Types</a></li>
      <li class="breadcrumb-item active">Orders</li>
    </ol>
  </div>

  <!-- Quick nav -->
  <div class="mb-3">
    <a href="sell-giftcard-types-admin" class="btn btn-outline-primary btn-sm mr-2">
      <i class="fas fa-tags mr-1"></i>Manage Card Types
    </a>
  </div>

  <!-- Stats -->
  <div class="row mb-4">
    <?php foreach ([
      ['Total', $stats['total'], 'primary'], ['Pending', $stats['pending'], 'warning'],
      ['Approved', $stats['approved'], 'success'], ['Rejected', $stats['rejected'], 'danger'],
    ] as [$l,$v,$c]): ?>
    <div class="col-xl-3 col-md-6 mb-3">
      <div class="card border-left-<?php echo $c; ?> shadow h-100 py-2">
        <div class="card-body py-2">
          <div class="text-xs font-weight-bold text-<?php echo $c; ?> text-uppercase mb-1"><?php echo $l; ?></div>
          <div class="h5 mb-0 font-weight-bold"><?php echo number_format($v ?? 0); ?></div>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <div class="alert alert-success d-flex align-items-center mb-4">
    <i class="fas fa-naira-sign mr-2"></i>
    <strong>Total Approved Payout:&nbsp;</strong>₦<?php echo number_format($stats['revenue'] ?? 0, 2); ?>
  </div>

  <!-- Orders Table -->
  <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,#6f42c1,#4e2d8e);color:#fff;">
      <h6 class="m-0 font-weight-bold">
        <i class="fas fa-list mr-2"></i>Sale Orders
        <span class="badge badge-light ml-2"><?php echo number_format($total_rows); ?> records</span>
      </h6>
    </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="Card type, account, user…" 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="approved" <?php echo $filter_stat==='approved' ? 'selected':'' ?>>Approved</option>
            <option value="rejected" <?php echo $filter_stat==='rejected' ? 'selected':'' ?>>Rejected</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="sell-giftcard-admin" 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>Card Type</th>
              <th>Value</th><th>Rate</th><th>Payout (NGN)</th>
              <th>Bank Details</th><th>Snapshot</th><th>Status</th><th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($orders)): ?>
              <tr><td colspan="11" class="text-center text-muted py-4">
                <i class="fas fa-inbox fa-2x d-block mb-2"></i>No sell orders found.
              </td></tr>
            <?php else: ?>
              <?php foreach ($orders as $i => $o):
                $badge = match($o['status']) {
                    'approved' => 'badge-success',
                    'rejected' => 'badge-danger',
                    default    => 'badge-warning',
                };
              ?>
              <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['type_name']); ?></strong></td>
                <td><?php echo htmlspecialchars($o['usd_amount']); ?> <?php echo htmlspecialchars($o['card_currency']); ?></td>
                <td>₦<?php echo number_format($o['ngn_rate'], 2); ?></td>
                <td><strong class="text-success">₦<?php echo number_format($o['ngn_payout'], 2); ?></strong></td>
                <td>
                  <small>
                    <strong><?php echo htmlspecialchars($o['bank_name']); ?></strong><br>
                    <?php echo htmlspecialchars($o['account_number']); ?><br>
                    <span class="text-muted"><?php echo htmlspecialchars($o['account_name']); ?></span>
                  </small>
                </td>
                <td>
                  <?php if (!empty($o['image_path'])): ?>
                  <img src="<?php echo htmlspecialchars($o['image_path']); ?>"
                       width="50" height="38" style="object-fit:cover;border-radius:4px;cursor:pointer"
                       onclick="viewSnap('<?php echo htmlspecialchars($o['image_path']); ?>')"
                       title="View snapshot">
                  <?php else: ?>
                  <span class="text-muted">—</span>
                  <?php endif; ?>
                </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="approveOrder(<?php echo $o['id']; ?>)" title="Approve & Pay">
                    <i class="fas fa-check"></i>
                  </button>
                  <button class="btn btn-xs btn-danger mb-1"
                          onclick="rejectOrder(<?php echo $o['id']; ?>)" title="Reject">
                    <i class="fas fa-times"></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,#6f42c1,#4e2d8e);color:#fff;">
        <h5 class="modal-title"><i class="fas fa-tags mr-2"></i>Sell Order Details</h5>
        <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body" id="orderDetailBody"></div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- Snapshot lightbox -->
<div id="snapModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.9);z-index:99999;align-items:center;justify-content:center;padding:16px" onclick="closeSnap()">
  <img id="snapFull" src="" style="max-width:90vw;max-height:90vh;border-radius:8px;object-fit:contain">
  <button onclick="closeSnap()" style="position:fixed;top:14px;right:14px;background:rgba(255,255,255,.15);border:none;color:#fff;width:36px;height:36px;border-radius:50%;font-size:1.1rem;cursor:pointer">
    <i class="fas fa-times"></i>
  </button>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>

function viewSnap(src) {
    document.getElementById('snapFull').src = src;
    document.getElementById('snapModal').style.display = 'flex';
}
function closeSnap() { document.getElementById('snapModal').style.display = 'none'; }
document.addEventListener('keydown', function(e){ if(e.key==='Escape') closeSnap(); });

function viewOrder(o) {
    var badge = {approved:'success', pending:'warning', rejected:'danger'};
    var snap  = o.image_path
        ? '<br><img src="' + o.image_path + '" style="max-width:100%;max-height:260px;border-radius:8px;object-fit:contain;margin-top:8px;cursor:pointer" onclick="viewSnap(\'' + o.image_path + '\')" title="Click to enlarge">'
        : '<em class="text-muted">No snapshot uploaded</em>';

    var html = '<div class="row">'
        + '<div class="col-md-6"><table class="table table-sm table-bordered">'
        + '<tr><th>Order #</th><td>#' + o.id + '</td></tr>'
        + '<tr><th>Card Type</th><td><strong>' + o.type_name + '</strong></td></tr>'
        + '<tr><th>Card Value</th><td>' + o.usd_amount + ' ' + o.card_currency + '</td></tr>'
        + '<tr><th>NGN Rate</th><td>₦' + parseFloat(o.ngn_rate).toLocaleString('en-NG') + '</td></tr>'
        + '<tr><th>Payout</th><td><strong class="text-success">₦' + parseFloat(o.ngn_payout).toLocaleString('en-NG',{minimumFractionDigits:2}) + '</strong></td></tr>'
        + '<tr><th>Status</th><td><span class="badge badge-' + (badge[o.status]||'secondary') + '">' + o.status + '</span></td></tr>'
        + '<tr><th>Submitted</th><td>' + o.created_at + '</td></tr>'
        + '</table></div>'
        + '<div class="col-md-6"><table class="table table-sm table-bordered">'
        + '<tr><th>Username</th><td>' + (o.username||'—') + '</td></tr>'
        + '<tr><th>User Email</th><td>' + (o.user_email||'—') + '</td></tr>'
        + '<tr><th>Phone</th><td>' + (o.phone||'—') + '</td></tr>'
        + '<tr><th>Bank</th><td>' + (o.bank_name||'—') + '</td></tr>'
        + '<tr><th>Account No.</th><td><strong>' + (o.account_number||'—') + '</strong></td></tr>'
        + '<tr><th>Account Name</th><td>' + (o.account_name||'—') + '</td></tr>'
        + '</table></div></div>'
        + '<hr><h6>Card Code</h6>'
        + '<div class="alert alert-secondary"><code style="font-size:.9rem;word-break:break-all">' + (o.card_code||'—') + '</code>'
        + (o.card_pin ? '<br><strong>PIN:</strong> <code>' + o.card_pin + '</code>' : '')
        + '</div>'
        + '<h6>Snapshot</h6>' + snap
        + (o.rejection_reason ? '<div class="alert alert-danger mt-3"><strong>Rejection Reason:</strong> ' + o.rejection_reason + '</div>' : '')
        + (o.admin_note ? '<div class="alert alert-light border mt-2"><strong>Admin Note:</strong> ' + o.admin_note + '</div>' : '');

    document.getElementById('orderDetailBody').innerHTML = html;
    $('#viewOrderModal').modal('show');
}

function approveOrder(id) {
    Swal.fire({
        title: 'Approve & Mark as Paid?',
        html: 'Confirm you have sent the payment to the user\'s bank account.',
        icon: 'question', showCancelButton: true,
        confirmButtonColor: '#1cc88a', confirmButtonText: 'Yes, Approve'
    }).then(r => {
        if (!r.isConfirmed) return;
        $.post('ajax/sell-giftcard-admin-ajax.php', { action: 'approve_sell_order', id: id }, function(res) {
            if (res.status === '1') {
                Swal.fire({ icon: 'success', title: 'Approved!', timer: 1500, showConfirmButton: false })
                    .then(() => location.reload());
            } else { Swal.fire('Error', res.msg, 'error'); }
        }, 'json').fail(() => Swal.fire('Error', 'Server error.', 'error'));
    });
}

function rejectOrder(id) {
    Swal.fire({
        title: 'Reject this order?',
        html: '<p class="text-muted mb-2">Please provide a reason for rejection (required):</p>'
            + '<textarea id="rejectReason" class="swal2-textarea" placeholder="e.g. Invalid card code, card already used…" style="height:90px"></textarea>',
        icon: 'warning', showCancelButton: true,
        confirmButtonColor: '#e74a3b', confirmButtonText: 'Reject Order',
        preConfirm: () => {
            var reason = document.getElementById('rejectReason').value.trim();
            if (!reason) { Swal.showValidationMessage('Please enter a rejection reason.'); return false; }
            return reason;
        }
    }).then(r => {
        if (!r.isConfirmed) return;
        $.post('ajax/sell-giftcard-admin-ajax.php',
            { action: 'reject_sell_order', id: id, reason: r.value },
            function(res) {
                if (res.status === '1') {
                    Swal.fire({ icon: 'success', title: 'Rejected', timer: 1500, showConfirmButton: false })
                        .then(() => location.reload());
                } else { Swal.fire('Error', res.msg, 'error'); }
            }, 'json').fail(() => Swal.fire('Error', 'Server error.', 'error'));
    });
}
</script>

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