<?php
// ============================================================
// FILE: keranjang.php — Keranjang Belanja
// ============================================================
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';

$pdo = db();
$sid = session_id();

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

    if ($aksi === 'hapus') {
        $kid = (int)($_POST['keranjang_id'] ?? 0);
        $pdo->prepare("DELETE FROM keranjang WHERE id=? AND session_id=?")
            ->execute([$kid, $sid]);
        setFlash('info', 'Produk dihapus dari keranjang.');
        redirect(BASE_URL . '/keranjang.php');
    }

    if ($aksi === 'kosongkan') {
        $pdo->prepare("DELETE FROM keranjang WHERE session_id=?")->execute([$sid]);
        setFlash('warning', 'Keranjang dikosongkan.');
        redirect(BASE_URL . '/keranjang.php');
    }

    if ($aksi === 'update') {
        foreach (($_POST['jumlah'] ?? []) as $kid => $jml) {
            $kid = (int)$kid;
            $jml = (float) str_replace(',', '.', $jml);
            $row = $pdo->prepare(
                "SELECT p.stok FROM keranjang k JOIN produk p ON k.produk_id=p.id
                 WHERE k.id=? AND k.session_id=?"
            );
            $row->execute([$kid, $sid]);
            $stok = (float)($row->fetchColumn() ?: 0);
            if ($jml <= 0) {
                $pdo->prepare("DELETE FROM keranjang WHERE id=? AND session_id=?")
                    ->execute([$kid, $sid]);
            } else {
                $pdo->prepare("UPDATE keranjang SET jumlah=? WHERE id=? AND session_id=?")
                    ->execute([min($jml, $stok), $kid, $sid]);
            }
        }
        setFlash('success', 'Keranjang diperbarui.');
        redirect(BASE_URL . '/keranjang.php');
    }
}

// ── Ambil item ───────────────────────────────────────────────
$stmt = $pdo->prepare("
    SELECT k.id AS kid, k.jumlah,
           p.id AS produk_id, p.nama, p.slug, p.harga, p.satuan, p.stok,
           (k.jumlah * p.harga) AS subtotal,
           (SELECT nama_file FROM produk_foto
            WHERE produk_id=p.id ORDER BY urutan ASC LIMIT 1) AS foto
    FROM keranjang k JOIN produk p ON k.produk_id=p.id
    WHERE k.session_id=? ORDER BY k.created_at ASC
");
$stmt->execute([$sid]);
$items = $stmt->fetchAll();

$grandTotal = array_sum(array_column($items, 'subtotal'));
$adaErr = false;
foreach ($items as $it) {
    if ((float)$it['stok'] <= 0 || (float)$it['jumlah'] > (float)$it['stok']) {
        $adaErr = true; break;
    }
}

$pageTitle = 'Keranjang Belanja';
$activePage = '';
include __DIR__ . '/includes/header.php';
?>

<div class="container py-4">

  <div class="ck-page-header mb-4">
    <div>
      <h1 class="ck-page-title"><i class="bi bi-cart3 me-2"></i>Keranjang Belanja</h1>
      <?php if (!empty($items)): ?>
        <p class="ck-page-sub mb-0">
          <?= count($items) ?> produk &middot; total <strong class="text-primary"><?= formatRupiah($grandTotal) ?></strong>
        </p>
      <?php endif; ?>
    </div>
    <?php if (!empty($items)): ?>
      <a href="<?= BASE_URL ?>/katalog.php" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-plus-lg me-1"></i>Tambah Produk
      </a>
    <?php endif; ?>
  </div>

  <?= flashMessage() ?>

  <?php if (empty($items)): ?>
    <div class="ck-empty">
      <div class="ck-empty-icon"><i class="bi bi-cart-x"></i></div>
      <h3 class="mb-2">Keranjang Masih Kosong</h3>
      <p class="text-muted mb-4">Belum ada produk yang ditambahkan. Temukan produk terbaik untuk proyek Anda!</p>
      <a href="<?= BASE_URL ?>/katalog.php" class="btn-ck-primary">
        <i class="bi bi-grid me-2"></i>Lihat Katalog Produk
      </a>
    </div>

  <?php else: ?>

    <?php if ($adaErr): ?>
      <div class="alert alert-warning d-flex align-items-center gap-2 mb-4">
        <i class="bi bi-exclamation-triangle-fill fs-5 flex-shrink-0"></i>
        <div><strong>Perhatian!</strong> Beberapa produk stoknya bermasalah. Perbarui atau hapus sebelum checkout.</div>
      </div>
    <?php endif; ?>

    <form method="POST" id="formKeranjang">
      <div class="row g-4">

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

          <div class="ck-toolbar mb-3">
            <span class="ck-toolbar-count">
              <i class="bi bi-box-seam me-1 text-primary"></i><?= count($items) ?> item di keranjang
            </span>
            <button type="button" class="ck-btn-kosongkan"
                    onclick="if(confirm('Kosongkan seluruh keranjang?')){document.getElementById('frmKosong').submit();}">
              <i class="bi bi-trash3 me-1"></i>Kosongkan
            </button>
          </div>

          <div class="ck-list">
            <?php foreach ($items as $it):
              $foto   = $it['foto'] ? UPLOAD_URL.'/produk/'.e($it['foto'])
                                    : 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=200&q=60';
              $stokOk = (float)$it['jumlah'] <= (float)$it['stok'];
              $habis  = (float)$it['stok'] <= 0;
              $step   = $it['satuan'] === 'meter' ? '0.1' : '1';
            ?>
              <div class="ck-item <?= !$stokOk ? 'ck-item--warn' : '' ?>" id="ckRow_<?= $it['kid'] ?>">

                <a href="<?= BASE_URL ?>/produk.php?slug=<?= e($it['slug']) ?>" class="ck-item-foto">
                  <img src="<?= $foto ?>" alt="<?= e($it['nama']) ?>" loading="lazy">
                  <?php if ($habis): ?><div class="ck-foto-overlay">Habis</div><?php endif; ?>
                </a>

                <div class="ck-item-info">
                  <a href="<?= BASE_URL ?>/produk.php?slug=<?= e($it['slug']) ?>" class="ck-item-nama">
                    <?= e($it['nama']) ?>
                  </a>
                  <div class="ck-item-harga"><?= formatRupiah($it['harga']) ?> / <?= e($it['satuan']) ?></div>
                  <?php if (!$stokOk): ?>
                    <div class="ck-stok-err">
                      <i class="bi bi-exclamation-triangle-fill me-1"></i>
                      <?= $habis ? 'Stok habis — hapus item ini'
                                 : 'Sisa stok: '.number_format($it['stok'],2).' '.e($it['satuan']) ?>
                    </div>
                  <?php else: ?>
                    <div class="ck-stok-ok">
                      <i class="bi bi-check-circle-fill me-1"></i>Tersedia
                    </div>
                  <?php endif; ?>
                </div>

                <div class="ck-qty-wrap">
                  <div class="ck-qty-group">
                    <button type="button" class="ck-qty-btn" onclick="ckDelta(this,<?= -floatval($step) ?>)" aria-label="Kurangi">
                      <i class="bi bi-dash"></i>
                    </button>
                    <input type="number" class="ck-qty-input"
                           name="jumlah[<?= $it['kid'] ?>]"
                           value="<?= number_format($it['jumlah'], $it['satuan']==='meter'?1:0,'.','') ?>"
                           min="<?= $step ?>" max="<?= (float)$it['stok'] ?>" step="<?= $step ?>"
                           data-kid="<?= $it['kid'] ?>" data-harga="<?= (float)$it['harga'] ?>" data-max="<?= (float)$it['stok'] ?>"
                           oninput="ckRecalc(this)">
                    <button type="button" class="ck-qty-btn" onclick="ckDelta(this,<?= floatval($step) ?>)" aria-label="Tambah">
                      <i class="bi bi-plus"></i>
                    </button>
                  </div>
                  <div class="ck-qty-satuan"><?= e($it['satuan']) ?></div>
                </div>

                <div class="ck-item-sub">
                  <div class="ck-sub-label">Subtotal</div>
                  <div class="ck-sub-val" id="sub_<?= $it['kid'] ?>"><?= formatRupiah($it['subtotal']) ?></div>
                </div>

                <button type="button" class="ck-del-btn"
                        onclick="ckHapus(<?= $it['kid'] ?>,'<?= addslashes(e($it['nama'])) ?>')"
                        title="Hapus item">
                  <i class="bi bi-trash3"></i>
                </button>

              </div>
            <?php endforeach; ?>
          </div>

          <div class="ck-list-footer mt-3">
            <a href="<?= BASE_URL ?>/katalog.php" class="btn btn-outline-secondary">
              <i class="bi bi-arrow-left me-1"></i>Lanjut Belanja
            </a>
            <button type="submit" name="aksi" value="update" class="btn btn-outline-primary">
              <i class="bi bi-arrow-clockwise me-1"></i>Perbarui Keranjang
            </button>
          </div>
        </div>

        <!-- ══ KANAN: Ringkasan ══════════════════════════════ -->
        <div class="col-lg-4">
          <div class="ck-summary">
            <h5 class="ck-summary-title">Ringkasan Pesanan</h5>

            <div class="ck-sum-items">
              <?php foreach ($items as $it): ?>
                <div class="ck-sum-row" id="sumRow_<?= $it['kid'] ?>">
                  <span class="ck-sum-nama"><?= e(mb_strlen($it['nama'])>28?mb_substr($it['nama'],0,28).'…':$it['nama']) ?></span>
                  <span class="ck-sum-val" id="sumVal_<?= $it['kid'] ?>"><?= formatRupiah($it['subtotal']) ?></span>
                </div>
              <?php endforeach; ?>
            </div>

            <div class="ck-sum-divider"></div>

            <div class="ck-sum-row ck-sum-muted">
              <span>Subtotal Produk</span>
              <span id="dispSub"><?= formatRupiah($grandTotal) ?></span>
            </div>
            <div class="ck-sum-row ck-sum-muted">
              <span>Ongkos Kirim</span>
              <span class="fst-italic text-muted">Dikonfirmasi</span>
            </div>

            <div class="ck-sum-divider"></div>

            <div class="ck-sum-row ck-sum-total">
              <strong>Total Produk</strong>
              <strong class="ck-grand-total" id="dispTotal"><?= formatRupiah($grandTotal) ?></strong>
            </div>

            <div class="ck-ongkir-note">
              <i class="bi bi-info-circle me-1"></i>
              Ongkir dipilih saat checkout.
            </div>

            <a href="<?= BASE_URL ?>/checkout.php"
               class="btn-ck-checkout<?= $adaErr?' btn-ck-checkout--disabled':'' ?>"
               <?= $adaErr?'tabindex="-1" aria-disabled="true" onclick="return false;"':'' ?>>
              <i class="bi bi-bag-check-fill me-2"></i>
              <?= $adaErr ? 'Perbaiki Stok Dulu' : 'Lanjut ke Checkout' ?>
            </a>

            <?php if ($adaErr): ?>
              <p class="text-danger text-center small mt-2 mb-0">
                <i class="bi bi-exclamation-circle me-1"></i>Selesaikan masalah stok di atas.
              </p>
            <?php endif; ?>

            <div class="ck-secure">
              <i class="bi bi-shield-lock-fill text-success"></i>
              <small class="text-muted">Transaksi aman &amp; terpercaya</small>
            </div>

            <div class="ck-payment-info">
              <div class="ck-pi-label">Metode Pembayaran</div>
              <div class="ck-pi-badges">
                <span class="ck-pi-badge">Transfer BCA</span>
                <span class="ck-pi-badge">Transfer BRI</span>
                <span class="ck-pi-badge">Mandiri</span>
                <span class="ck-pi-badge">BNI</span>
              </div>
            </div>
          </div>
        </div>

      </div>
    </form>

    <form id="frmKosong" method="POST" style="display:none">
      <input type="hidden" name="aksi" value="kosongkan">
    </form>
    <form id="frmHapus" method="POST" style="display:none">
      <input type="hidden" name="aksi" value="hapus">
      <input type="hidden" name="keranjang_id" id="hapusKid">
    </form>

  <?php endif; ?>
</div>

<script>
const HARGA = {<?php echo implode(',', array_map(fn($it)=>$it['kid'].':'.(float)$it['harga'], $items)); ?>};

function formatRp(n){ return 'Rp\u00a0'+Math.round(n).toLocaleString('id-ID'); }

function ckRecalc(inp) {
  const kid  = +inp.dataset.kid;
  const max  = parseFloat(inp.dataset.max)||Infinity;
  let   jml  = parseFloat(inp.value)||0;
  if (jml<0)   { jml=0;   inp.value=0; }
  if (jml>max) { jml=max;  inp.value=max; }
  const sub = jml*(HARGA[kid]||0);
  const s1=document.getElementById('sub_'+kid); if(s1)s1.textContent=formatRp(sub);
  const s2=document.getElementById('sumVal_'+kid); if(s2)s2.textContent=formatRp(sub);
  let tot=0;
  document.querySelectorAll('.ck-qty-input').forEach(i=>{ tot+=(parseFloat(i.value)||0)*(HARGA[+i.dataset.kid]||0); });
  ['dispSub','dispTotal'].forEach(id=>{ const el=document.getElementById(id); if(el)el.textContent=formatRp(tot); });
}

function ckDelta(btn,delta) {
  const inp=btn.closest('.ck-qty-group').querySelector('.ck-qty-input');
  const max=parseFloat(inp.dataset.max)||9999;
  const min=parseFloat(inp.min)||0.1;
  let   val=Math.round((parseFloat(inp.value||0)+delta)*1000)/1000;
  inp.value=Math.max(min,Math.min(max,val));
  ckRecalc(inp);
}

function ckHapus(kid,nama) {
  if(!confirm('Hapus "'+nama+'" dari keranjang?'))return;
  document.getElementById('hapusKid').value=kid;
  document.getElementById('frmHapus').submit();
}
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>