<?php
// ============================================================
// FILE: admin/pesanan.php — Daftar Semua Pesanan
// Fitur:
//  - Filter tab per status (dengan jumlah badge per tab)
//  - Search: kode, nama pembeli, nomor HP
//  - Sort: terbaru/terlama/total tertinggi
//  - Pagination 25/hal
//  - Highlight baris yang butuh aksi (pending/dibayar)
//  - Quick-action tombol verifikasi langsung dari daftar
// ============================================================
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
requireAdmin();

$pdo = db();

// ── Proses Hapus Pesanan ──────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['aksi'] ?? '') === 'hapus_pesanan') {
    $hapusId = (int)($_POST['pesanan_id'] ?? 0);
    if ($hapusId) {
        // Hanya boleh hapus pesanan dibatalkan atau pending
        $cek = $pdo->prepare("SELECT status FROM pesanan WHERE id=? LIMIT 1");
        $cek->execute([$hapusId]);
        $cekStatus = $cek->fetchColumn();
        if (in_array($cekStatus, ['dibatalkan', 'pending'], true)) {
            // Kembalikan stok kalau masih pending (belum sempat dikembalikan)
            if ($cekStatus === 'pending') {
                $itemsCek = $pdo->prepare("SELECT produk_id, jumlah FROM pesanan_item WHERE pesanan_id=?");
                $itemsCek->execute([$hapusId]);
                foreach ($itemsCek->fetchAll() as $it) {
                    $pdo->prepare("UPDATE produk SET stok = stok + ? WHERE id=?")
                        ->execute([$it['jumlah'], $it['produk_id']]);
                }
            }
            $pdo->prepare("DELETE FROM pesanan WHERE id=?")->execute([$hapusId]);
            setFlash('success', 'Pesanan berhasil dihapus.');
        } else {
            setFlash('danger', 'Hanya pesanan berstatus <strong>Pending</strong> atau <strong>Dibatalkan</strong> yang bisa dihapus.');
        }
    }
    redirect(BASE_URL . '/admin/pesanan.php?' . http_build_query(['status'=>$_POST['redirect_status']??'','q'=>$_POST['redirect_q']??'','sort'=>$_POST['redirect_sort']??'terbaru']));
}

$status  = $_GET['status'] ?? '';
$q       = trim($_GET['q'] ?? '');
$sort    = $_GET['sort'] ?? 'terbaru';
$page    = max(1, (int)($_GET['page'] ?? 1));
$perPage = 25;
$offset  = ($page - 1) * $perPage;

// Build WHERE
$where  = ['1=1'];
$params = [];
if ($status) { $where[] = 'p.status = ?'; $params[] = $status; }
if ($q) {
    $where[] = '(p.kode_pesanan LIKE ? OR p.nama_pembeli LIKE ? OR p.no_hp LIKE ?)';
    $params  = array_merge($params, ["%$q%", "%$q%", "%$q%"]);
}
$whereSQL = implode(' AND ', $where);

$orderSQL = match($sort) {
    'terlama'   => 'p.created_at ASC',
    'total_asc' => 'p.total_harga ASC',
    'total_dsc' => 'p.total_harga DESC',
    default     => 'p.created_at DESC',
};

// Count per status untuk tab badge
$countPerStatus = [];
foreach (['pending','diverifikasi','diproses','selesai','dibatalkan'] as $s) {
    $row = $pdo->prepare("SELECT COUNT(*) FROM pesanan WHERE status = ?");
    $row->execute([$s]);
    $countPerStatus[$s] = (int)$row->fetchColumn();
}
$countSemua = (int)$pdo->query("SELECT COUNT(*) FROM pesanan")->fetchColumn();

// Main query
$total = (int)$pdo->prepare("SELECT COUNT(*) FROM pesanan p WHERE $whereSQL")->execute($params)
       ? $pdo->prepare("SELECT COUNT(*) FROM pesanan p WHERE $whereSQL") : 0;
$stmtCount = $pdo->prepare("SELECT COUNT(*) FROM pesanan p WHERE $whereSQL");
$stmtCount->execute($params);
$total = (int)$stmtCount->fetchColumn();
$totalPage = (int)ceil($total / $perPage);

$stmt = $pdo->prepare("
    SELECT p.*,
           pay.diverifikasi AS bukti_verified,
           pay.id AS pembayaran_id,
           pay.midtrans_status
    FROM pesanan p
    LEFT JOIN pembayaran pay ON pay.pesanan_id = p.id
    WHERE $whereSQL
    ORDER BY $orderSQL
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$list = $stmt->fetchAll();

$pageTitle = 'Manajemen Pesanan';
include __DIR__ . '/admin_layout.php';
?>

<!-- ── Page Header ─────────────────────────────────────── -->
<div class="adm-page-header mb-4">
  <div>
    <h4 class="adm-page-title">
      <i class="bi bi-receipt-cutoff me-2"></i>Manajemen Pesanan
    </h4>
    <p class="adm-page-sub mb-0">
      <?= $total ?> pesanan
      <?= $q ? '· hasil pencarian "<strong>'.e($q).'</strong>"' : '' ?>
    </p>
  </div>
</div>

<!-- ── Tab Status ──────────────────────────────────────── -->
<div class="adm-tabs mb-3">
  <?php
  $tabs = [
    ''             => ['label'=>'Semua',    'cnt'=>$countSemua],
    'pending'      => ['label'=>'Pending',  'cnt'=>$countPerStatus['pending']],
    'diverifikasi' => ['label'=>'Dibayar',  'cnt'=>$countPerStatus['diverifikasi']],
    'diproses'     => ['label'=>'Diproses', 'cnt'=>$countPerStatus['diproses']],
    'selesai'      => ['label'=>'Selesai',  'cnt'=>$countPerStatus['selesai']],
    'dibatalkan'   => ['label'=>'Dibatalkan','cnt'=>$countPerStatus['dibatalkan']],
  ];
  foreach ($tabs as $s => $t):
    $isActive = $status === $s;
    $href = '?' . http_build_query(['status'=>$s,'q'=>$q,'sort'=>$sort]);
  ?>
    <a href="<?= $href ?>" class="adm-tab <?= $isActive ? 'adm-tab--active' : '' ?>">
      <?= $t['label'] ?>
      <?php if ($t['cnt'] > 0): ?>
        <span class="adm-tab-badge <?= $s==='pending'&&$t['cnt']>0?'adm-tab-badge--urgent':'' ?>">
          <?= $t['cnt'] ?>
        </span>
      <?php endif; ?>
    </a>
  <?php endforeach; ?>
</div>

<!-- ── Toolbar: search + sort ─────────────────────────── -->
<div class="admin-card mb-3">
  <form class="adm-toolbar" method="GET">
    <input type="hidden" name="status" value="<?= e($status) ?>">
    <div class="adm-search-wrap">
      <i class="bi bi-search adm-search-icon"></i>
      <input type="text" name="q" class="adm-search-input"
             placeholder="Cari kode pesanan, nama pembeli, no. HP…"
             value="<?= e($q) ?>">
    </div>
    <select name="sort" class="form-select form-select-sm adm-sort-sel" onchange="this.form.submit()">
      <option value="terbaru"   <?= $sort==='terbaru'  ?'selected':'' ?>>Terbaru</option>
      <option value="terlama"   <?= $sort==='terlama'  ?'selected':'' ?>>Terlama</option>
      <option value="total_dsc" <?= $sort==='total_dsc'?'selected':'' ?>>Total ↑</option>
      <option value="total_asc" <?= $sort==='total_asc'?'selected':'' ?>>Total ↓</option>
    </select>
    <button type="submit" class="btn btn-sm btn-primary">
      <i class="bi bi-search me-1"></i>Cari
    </button>
    <?php if ($q || $status): ?>
      <a href="<?= BASE_URL ?>/admin/pesanan.php" class="btn btn-sm btn-outline-secondary">Reset</a>
    <?php endif; ?>
  </form>
</div>

<!-- ── Tabel Pesanan ───────────────────────────────────── -->
<div class="admin-card">
  <div class="table-responsive">
    <table class="table table-hover admin-table mb-0">
      <thead>
        <tr>
          <th>Kode Pesanan</th>
          <th>Pembeli</th>
          <th>No. HP</th>
          <th>Total</th>
          <th>Tgl Pesan</th>
          <th>Status</th>
          <th>Bukti</th>
          <th class="text-center">Aksi</th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($list)): ?>
          <tr>
            <td colspan="8" class="text-center py-5">
              <i class="bi bi-inbox fs-2 text-muted d-block mb-2"></i>
              <span class="text-muted">Tidak ada pesanan<?= $q ? ' yang cocok dengan pencarian.' : '.' ?></span>
            </td>
          </tr>
        <?php endif; ?>
        <?php foreach ($list as $p):
          $isUrgent = in_array($p['status'], ['pending','dibayar']);
        ?>
          <tr class="<?= $isUrgent ? 'adm-row--urgent' : '' ?>">
            <td>
              <a href="<?= BASE_URL ?>/admin/pesanan_detail.php?id=<?= $p['id'] ?>"
                 class="adm-kode-link">
                <code><?= e($p['kode_pesanan']) ?></code>
              </a>
            </td>
            <td>
              <div class="fw-semibold"><?= e($p['nama_pembeli']) ?></div>
              <?php if ($p['catatan']): ?>
                <small class="text-muted" title="<?= e($p['catatan']) ?>">
                  <i class="bi bi-chat-text me-1"></i>Ada catatan
                </small>
              <?php endif; ?>
            </td>
            <td>
              <a href="#" class="text-decoration-none">
                <?= e($p['no_hp']) ?>
              </a>
            </td>
            <td class="fw-bold"><?= formatRupiah($p['total_harga']) ?></td>
            <td class="small text-muted">
              <?= date('d/m/y', strtotime($p['created_at'])) ?><br>
              <span class="text-muted"><?= date('H:i', strtotime($p['created_at'])) ?> WIB</span>
            </td>
            <td><?= statusBadge($p['status']) ?></td>
            <td class="text-center">
              <?php
                // Status lunas berdasarkan midtrans_status ATAU diverifikasi manual
                $statusLunas = ['capture', 'settlement', 'success'];
                $sudahBayar  = $p['pembayaran_id'] && (
                    in_array($p['midtrans_status'], $statusLunas, true)
                    || (bool)$p['bukti_verified']
                );
              ?>
              <?php if ($p['pembayaran_id']): ?>
                <?php if ($sudahBayar): ?>
                  <span class="badge bg-success-subtle text-success border border-success-subtle">
                    <i class="bi bi-patch-check-fill me-1"></i>LUNAS
                  </span>
                <?php else: ?>
                  <span class="badge bg-danger-subtle text-danger border border-danger-subtle">
                    <i class="bi bi-x-circle me-1"></i>Belum Bayar
                  </span>
                <?php endif; ?>
              <?php else: ?>
                <span class="badge bg-secondary-subtle text-secondary border border-secondary-subtle">
                  <i class="bi bi-dash-circle me-1"></i>Belum Bayar
                </span>
              <?php endif; ?>
            </td>
            <td class="text-center">
              <div class="d-flex gap-1 justify-content-center">
                <a href="<?= BASE_URL ?>/admin/pesanan_detail.php?id=<?= $p['id'] ?>"
                   class="btn btn-xs btn-primary" title="Lihat Detail">
                  <i class="bi bi-eye"></i>
                </a>
                <?php if (in_array($p['status'], ['dibatalkan','pending'], true)): ?>
                  <form method="POST" action="<?= BASE_URL ?>/admin/pesanan.php">
                    <input type="hidden" name="aksi" value="hapus_pesanan">
                    <input type="hidden" name="pesanan_id" value="<?= $p['id'] ?>">
                    <input type="hidden" name="redirect_status" value="<?= e($status) ?>">
                    <input type="hidden" name="redirect_q" value="<?= e($q) ?>">
                    <input type="hidden" name="redirect_sort" value="<?= e($sort) ?>">
                    <button type="button" class="btn btn-xs btn-danger" title="Hapus Pesanan"
                            onclick="konfirmasiHapus(this, '<?= e($p['kode_pesanan']) ?>')">
                      <i class="bi bi-trash"></i>
                    </button>
                  </form>
                <?php endif; ?>
              </div>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <!-- Pagination -->
  <?php if ($totalPage > 1): ?>
    <div class="d-flex justify-content-between align-items-center px-4 py-3 border-top">
      <small class="text-muted">
        Menampilkan <?= ($offset+1) ?>–<?= min($offset+$perPage,$total) ?> dari <?= $total ?>
      </small>
      <nav>
        <ul class="pagination pagination-sm mb-0">
          <li class="page-item <?= $page<=1?'disabled':'' ?>">
            <a class="page-link" href="?<?= http_build_query(array_merge($_GET,['page'=>$page-1])) ?>">
              <i class="bi bi-chevron-left"></i>
            </a>
          </li>
          <?php
          $start = max(1, $page-2); $end = min($totalPage, $page+2);
          if ($start > 1): ?><li class="page-item disabled"><span class="page-link">…</span></li><?php endif;
          for ($i = $start; $i <= $end; $i++): ?>
            <li class="page-item <?= $i===$page?'active':'' ?>">
              <a class="page-link" href="?<?= http_build_query(array_merge($_GET,['page'=>$i])) ?>"><?= $i ?></a>
            </li>
          <?php endfor;
          if ($end < $totalPage): ?><li class="page-item disabled"><span class="page-link">…</span></li><?php endif; ?>
          <li class="page-item <?= $page>=$totalPage?'disabled':'' ?>">
            <a class="page-link" href="?<?= http_build_query(array_merge($_GET,['page'=>$page+1])) ?>">
              <i class="bi bi-chevron-right"></i>
            </a>
          </li>
        </ul>
      </nav>
    </div>
  <?php endif; ?>
</div>

<script>
function konfirmasiHapus(btn, kode) {
  if (confirm('Hapus pesanan ' + kode + '?\nTindakan ini tidak bisa dibatalkan.')) {
    btn.closest('form').submit();
  }
}
</script>

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