<?php
// ============================================================
// FILE: admin/pesanan_detail.php — Detail & Kelola Pesanan
// Fitur:
//  - Tampilkan semua info pesanan, item, bukti transfer
//  - Preview bukti transfer + lightbox zoom
//  - Verifikasi pembayaran → status 'diverifikasi'
//  - Update status (diproses/selesai/dibatalkan/pending)
//  - Catatan admin
//  - Kembalikan stok otomatis jika dibatalkan
//  - Print/export pesanan
// ============================================================
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();
$id  = (int)($_GET['id'] ?? 0);
if (!$id) redirect(BASE_URL . '/admin/pesanan.php');

function fetchPesanan($pdo, $id) {
    $s = $pdo->prepare("SELECT * FROM pesanan WHERE id=? LIMIT 1");
    $s->execute([$id]); return $s->fetch();
}
function fetchBukti($pdo, $id) {
    $s = $pdo->prepare("SELECT * FROM pembayaran WHERE pesanan_id=? LIMIT 1");
    $s->execute([$id]); return $s->fetch();
}

$pesanan = fetchPesanan($pdo, $id);
if (!$pesanan) redirect(BASE_URL . '/admin/pesanan.php');

$items = $pdo->prepare("SELECT * FROM pesanan_item WHERE pesanan_id=? ORDER BY id");
$items->execute([$id]); $items = $items->fetchAll();
$bukti = fetchBukti($pdo, $id);

// ── Proses POST ──────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $aksi = $_POST['aksi'] ?? '';

    // 1. Verifikasi pembayaran
    if ($aksi === 'verifikasi_bayar' && $bukti && !$bukti['diverifikasi']) {
        $pdo->prepare("UPDATE pembayaran SET diverifikasi=1, verified_at=NOW() WHERE id=?")
            ->execute([$bukti['id']]);
        $pdo->prepare("UPDATE pesanan SET status='diverifikasi', updated_at=NOW() WHERE id=?")
            ->execute([$id]);
        setFlash('success', 'Pembayaran berhasil diverifikasi. Status pesanan → <strong>Diverifikasi</strong>.');
        redirect(BASE_URL . '/admin/pesanan_detail.php?id=' . $id);
    }

    // 2. Update status manual
    if ($aksi === 'update_status') {
        $newStatus    = $_POST['status_baru'] ?? '';
        $catatanAdmin = trim($_POST['catatan_admin'] ?? '');
        $allowed = ['pending','dibayar','diverifikasi','diproses','selesai','dibatalkan'];
        if (in_array($newStatus, $allowed, true)) {
            $pdo->prepare("UPDATE pesanan SET status=?, catatan_admin=?, updated_at=NOW() WHERE id=?")
                ->execute([$newStatus, $catatanAdmin ?: null, $id]);

            // Kembalikan stok jika dibatalkan (dan sebelumnya bukan dibatalkan)
            if ($newStatus === 'dibatalkan' && $pesanan['status'] !== 'dibatalkan') {
                foreach ($items as $it) {
                    $pdo->prepare("UPDATE produk SET stok = stok + ? WHERE id=?")
                        ->execute([$it['jumlah'], $it['produk_id']]);
                }
                setFlash('warning', 'Pesanan <strong>dibatalkan</strong>. Stok produk telah dikembalikan.');
            } else {
                setFlash('success', 'Status pesanan diperbarui ke <strong>' . e($newStatus) . '</strong>.');
            }
        }
        redirect(BASE_URL . '/admin/pesanan_detail.php?id=' . $id);
    }
}

// Re-fetch setelah aksi
$pesanan = fetchPesanan($pdo, $id);
$bukti   = fetchBukti($pdo, $id);

$langkahTracking = [
    'pending'      => ['label'=>'Menunggu Bayar',    'warna'=>'warning', 'ikon'=>'clock-history'],
    'dibayar'      => ['label'=>'Bukti Dikirim',      'warna'=>'info',    'ikon'=>'upload'],
    'diverifikasi' => ['label'=>'Bayar Dikonfirmasi', 'warna'=>'primary', 'ikon'=>'check-circle-fill'],
    'diproses'     => ['label'=>'Sedang Diproses',    'warna'=>'secondary','ikon'=>'gear-wide-connected'],
    'selesai'      => ['label'=>'Selesai',             'warna'=>'success', 'ikon'=>'house-check-fill'],
    'dibatalkan'   => ['label'=>'Dibatalkan',          'warna'=>'danger',  'ikon'=>'x-circle-fill'],
];

$pageTitle = 'Detail Pesanan — ' . $pesanan['kode_pesanan'];
include __DIR__ . '/admin_layout.php';
?>

<!-- Breadcrumb + Header -->
<div class="adm-page-header mb-4">
  <div>
    <nav aria-label="breadcrumb" class="mb-1">
      <ol class="breadcrumb small mb-0">
        <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/admin/pesanan.php">Pesanan</a></li>
        <li class="breadcrumb-item active"><?= e($pesanan['kode_pesanan']) ?></li>
      </ol>
    </nav>
    <h4 class="adm-page-title">
      <code class="fs-5"><?= e($pesanan['kode_pesanan']) ?></code>
    </h4>
    <p class="adm-page-sub mb-0">
      Dibuat: <?= date('d M Y, H:i', strtotime($pesanan['created_at'])) ?> WIB
      &nbsp;·&nbsp; <?= statusBadge($pesanan['status']) ?>
    </p>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= BASE_URL ?>/admin/pesanan.php" class="btn btn-outline-secondary btn-sm">
      <i class="bi bi-arrow-left me-1"></i>Kembali
    </a>
    <button onclick="window.print()" class="btn btn-outline-secondary btn-sm">
      <i class="bi bi-printer me-1"></i>Cetak
    </button>
  </div>
</div>

<div class="row g-4">

  <!-- ═══ KIRI: Info + Item ═══════════════════════════════ -->
  <div class="col-lg-8">

    <!-- Info Pemesan -->
    <div class="admin-card mb-4">
      <div class="admin-card-header">
        <h6 class="mb-0"><i class="bi bi-person-lines-fill me-2"></i>Informasi Pemesan</h6>
      </div>
      <div class="p-0">
        <div class="adm-info-table">
          <div class="adm-info-row">
            <span class="adm-info-key">Nama Pembeli</span>
            <span class="adm-info-val fw-semibold"><?= e($pesanan['nama_pembeli']) ?></span>
          </div>
          <div class="adm-info-row">
            <span class="adm-info-key">Nomor HP</span>
            <span class="adm-info-val">
              <?= e($pesanan['no_hp']) ?>
            </span>
          </div>
          <div class="adm-info-row">
            <span class="adm-info-key">Alamat</span>
            <span class="adm-info-val"><?= e($pesanan['alamat'] ?? '-') ?></span>
          </div>
          <?php if ($pesanan['catatan']): ?>
            <div class="adm-info-row">
              <span class="adm-info-key">Catatan</span>
              <span class="adm-info-val text-warning-emphasis">
                <i class="bi bi-chat-text me-1"></i><?= e($pesanan['catatan']) ?>
              </span>
            </div>
          <?php endif; ?>
          <?php if ($pesanan['catatan_admin']): ?>
            <div class="adm-info-row">
              <span class="adm-info-key">Catatan Admin</span>
              <span class="adm-info-val text-muted fst-italic"><?= e($pesanan['catatan_admin']) ?></span>
            </div>
          <?php endif; ?>
        </div>
      </div>
    </div>

    <!-- Item Pesanan -->
    <div class="admin-card mb-4">
      <div class="admin-card-header">
        <h6 class="mb-0"><i class="bi bi-box-seam me-2"></i>Item Pesanan</h6>
        <span class="badge bg-secondary"><?= count($items) ?> produk</span>
      </div>
      <div class="table-responsive">
        <table class="table table-sm admin-table mb-0">
          <thead>
            <tr>
              <th>Produk</th>
              <th class="text-center">Jumlah</th>
              <th class="text-end">Harga Satuan</th>
              <th class="text-end">Subtotal</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($items as $it): ?>
              <tr>
                <td class="fw-semibold"><?= e($it['nama_produk']) ?></td>
                <td class="text-center">
                  <?= number_format($it['jumlah'], 2) ?>
                </td>
                <td class="text-end"><?= formatRupiah($it['harga_satuan']) ?></td>
                <td class="text-end fw-bold text-primary"><?= formatRupiah($it['subtotal']) ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
          <tfoot>
            <tr class="table-light fw-bold">
              <td colspan="3" class="text-end">Total Produk</td>
              <td class="text-end fs-5 text-primary"><?= formatRupiah($pesanan['total_harga']) ?></td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>

    <!-- Bukti Pembayaran (Midtrans) -->
    <div class="admin-card mb-4">
      <div class="admin-card-header">
        <h6 class="mb-0">
          <i class="bi bi-credit-card me-2"></i>Status Pembayaran
        </h6>
        <?php
          $statusLunas = ['capture', 'settlement', 'success'];
          $sudahLunas  = $bukti && in_array($bukti['midtrans_status'], $statusLunas, true);
        ?>
        <?php if ($bukti): ?>
          <?php if ($sudahLunas): ?>
            <span class="badge bg-success">
              <i class="bi bi-patch-check-fill me-1"></i>LUNAS
            </span>
          <?php else: ?>
            <span class="badge bg-danger">
              <i class="bi bi-x-circle me-1"></i>Belum Lunas
            </span>
          <?php endif; ?>
        <?php else: ?>
          <span class="badge bg-secondary">
            <i class="bi bi-dash-circle me-1"></i>Belum Ada Data
          </span>
        <?php endif; ?>
      </div>
      <div class="p-4">
        <?php if ($bukti): ?>
          <div class="adm-info-table">
            <div class="adm-info-row">
              <span class="adm-info-key">Order ID Midtrans</span>
              <span class="adm-info-val"><code><?= e($bukti['midtrans_order_id'] ?? '-') ?></code></span>
            </div>
            <div class="adm-info-row">
              <span class="adm-info-key">Status Midtrans</span>
              <span class="adm-info-val">
                <?php
                  $mtStatus = $bukti['midtrans_status'] ?? '-';
                  $mtColor  = match($mtStatus) {
                    'settlement', 'capture', 'success' => 'success',
                    'pending'    => 'warning',
                    'deny', 'cancel', 'expire', 'failure' => 'danger',
                    default      => 'secondary',
                  };
                ?>
                <span class="badge bg-<?= $mtColor ?>"><?= e(ucfirst($mtStatus)) ?></span>
              </span>
            </div>
            <div class="adm-info-row">
              <span class="adm-info-key">Metode Bayar</span>
              <span class="adm-info-val"><?= e($bukti['payment_type'] ?? '-') ?></span>
            </div>
            <div class="adm-info-row">
              <span class="adm-info-key">Total Pesanan</span>
              <span class="adm-info-val fw-bold text-primary"><?= formatRupiah($pesanan['total_harga']) ?></span>
            </div>
            <div class="adm-info-row">
              <span class="adm-info-key">Transaksi Dibuat</span>
              <span class="adm-info-val"><?= date('d M Y H:i', strtotime($bukti['created_at'])) ?> WIB</span>
            </div>
          </div>

          <?php if ($sudahLunas): ?>
            <div class="alert alert-success d-flex align-items-center gap-2 mt-3 mb-0">
              <i class="bi bi-check-circle-fill flex-shrink-0 fs-5"></i>
              <div>Pembayaran <strong>LUNAS</strong> — dikonfirmasi otomatis oleh Midtrans.</div>
            </div>
          <?php else: ?>
            <div class="alert alert-warning d-flex align-items-center gap-2 mt-3 mb-0">
              <i class="bi bi-hourglass-split flex-shrink-0 fs-5"></i>
              <div>Pembayaran <strong>belum selesai</strong>. Menunggu konfirmasi dari Midtrans.</div>
            </div>
          <?php endif; ?>

        <?php else: ?>
          <div class="text-center text-muted py-3">
            <i class="bi bi-clock-history fs-3 d-block mb-2 text-warning"></i>
            <p class="mb-0">Pelanggan belum melakukan pembayaran.</p>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div><!-- /col kiri -->

  <!-- ═══ KANAN: Status & Aksi ════════════════════════════ -->
  <div class="col-lg-4">

    <!-- Progress Status -->
    <div class="admin-card mb-4">
      <div class="admin-card-header">
        <h6 class="mb-0"><i class="bi bi-activity me-2"></i>Status Pesanan</h6>
      </div>
      <div class="p-4">
        <div class="adm-status-progress">
          <?php
          $statusOrder = ['pending','dibayar','diverifikasi','diproses','selesai'];
          $currentIdx  = array_search($pesanan['status'], $statusOrder);
          $isBatal     = $pesanan['status'] === 'dibatalkan';
          ?>
          <?php if ($isBatal): ?>
            <div class="adm-status-batal">
              <i class="bi bi-x-circle-fill text-danger fs-4"></i>
              <span class="fw-semibold text-danger ms-2">Pesanan Dibatalkan</span>
            </div>
          <?php else: ?>
            <?php foreach ($statusOrder as $i => $s):
              $isDone    = $currentIdx !== false && $i < $currentIdx;
              $isCurrent = $currentIdx === $i;
              $info      = $langkahTracking[$s];
            ?>
              <div class="adm-progress-row <?= $isCurrent?'adm-progress-row--current':($isDone?'adm-progress-row--done':'') ?>">
                <div class="adm-progress-dot">
                  <?php if ($isDone): ?>
                    <i class="bi bi-check-lg"></i>
                  <?php elseif ($isCurrent): ?>
                    <i class="bi bi-<?= $info['ikon'] ?>"></i>
                  <?php else: ?>
                    <span class="adm-progress-num"><?= $i+1 ?></span>
                  <?php endif; ?>
                </div>
                <div class="adm-progress-label">
                  <?= $info['label'] ?>
                  <?php if ($isCurrent): ?>
                    <span class="badge bg-primary ms-1" style="font-size:.65rem">Saat Ini</span>
                  <?php endif; ?>
                </div>
              </div>
              <?php if ($i < count($statusOrder)-1): ?>
                <div class="adm-progress-line <?= $isDone?'adm-progress-line--done':'' ?>"></div>
              <?php endif; ?>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
      </div>
    </div>

    <!-- Update Status -->
    <div class="admin-card mb-4">
      <div class="admin-card-header">
        <h6 class="mb-0"><i class="bi bi-pencil-square me-2"></i>Update Status</h6>
      </div>
      <div class="p-4">
        <form method="POST" id="frmStatus">
          <input type="hidden" name="aksi" value="update_status">

          <div class="mb-3">
            <label class="ck-label" for="selStatus">Status Baru</label>
            <select name="status_baru" id="selStatus" class="form-select">
              <?php
              $opts = ['pending','dibayar','diverifikasi','diproses','selesai','dibatalkan'];
              foreach ($opts as $s): ?>
                <option value="<?= $s ?>" <?= $pesanan['status']===$s?'selected':'' ?>>
                  <?= ucfirst($s) ?> <?= $s==='dibatalkan'?'⚠️':'' ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="mb-3">
            <label class="ck-label" for="catatanAdmin">Catatan Admin <span class="text-muted small">(opsional)</span></label>
            <textarea name="catatan_admin" id="catatanAdmin" class="form-control" rows="3"
                      placeholder="Pesan internal atau keterangan untuk pelanggan…"><?= e($pesanan['catatan_admin'] ?? '') ?></textarea>
          </div>

          <div class="adm-cancel-warn d-none" id="cancelWarn">
            <i class="bi bi-exclamation-triangle-fill me-2"></i>
            Membatalkan pesanan akan mengembalikan stok semua produk secara otomatis.
          </div>

          <button type="submit" class="btn btn-primary w-100 mt-2" id="btnUpdateStatus">
            <i class="bi bi-arrow-repeat me-2"></i>Perbarui Status
          </button>
        </form>
      </div>
    </div>

    <!-- Ringkasan Pembayaran -->
    <div class="admin-card">
      <div class="admin-card-header">
        <h6 class="mb-0"><i class="bi bi-wallet2 me-2"></i>Ringkasan</h6>
      </div>
      <div class="p-4">
        <div class="adm-info-row">
          <span class="adm-info-key">Total Produk</span>
          <span class="fw-bold text-primary"><?= formatRupiah($pesanan['total_harga']) ?></span>
        </div>
        <div class="adm-info-row">
          <span class="adm-info-key">Ongkos Kirim</span>
          <span class="text-muted fst-italic">Konfirmasi terpisah</span>
        </div>
        <?php if ($bukti && in_array($bukti['midtrans_status'] ?? '', ['capture','settlement','success'], true)): ?>
          <div class="adm-info-row">
            <span class="adm-info-key">Status Bayar</span>
            <span class="fw-bold text-success">
              <i class="bi bi-patch-check-fill me-1"></i>LUNAS
            </span>
          </div>
        <?php elseif ($bukti): ?>
          <div class="adm-info-row">
            <span class="adm-info-key">Status Bayar</span>
            <span class="fw-bold text-danger">Belum Lunas</span>
          </div>
        <?php endif; ?>
        <div class="mt-3">
          <a href="<?= BASE_URL ?>/admin/chat.php?pesanan_id=<?= $pesanan['id'] ?>"
             class="btn btn-primary w-100">
            <i class="bi bi-chat-dots me-2"></i>Chat Pelanggan
          </a>
        </div>
      </div>
    </div>
  </div><!-- /col kanan -->

</div><!-- /row -->

<script>
document.getElementById('selStatus')?.addEventListener('change', function() {
  const warn = document.getElementById('cancelWarn');
  if (warn) {
    warn.classList.toggle('d-none', this.value !== 'dibatalkan');
  }
});
document.getElementById('frmStatus')?.addEventListener('submit', function(e) {
  const sel = document.getElementById('selStatus');
  if (sel.value === 'dibatalkan') {
    if (!confirm('Batalkan pesanan ini? Stok akan dikembalikan otomatis.')) {
      e.preventDefault();
    }
  }
});
</script>

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