<?php
// cart.php — سلة التسوق مع PRG لتجنّب "headers already sent"
if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . "/config/db.php";
require_once __DIR__ . "/config/price.php";

$pdo    = db();
$prices = getPrices();

// --- توحيد شكل السلة: [id => qty] (ندعم الشكل القديم [id=>['qty'=>..]])
if (!isset($_SESSION['cart']) || !is_array($_SESSION['cart'])) $_SESSION['cart'] = [];
foreach ($_SESSION['cart'] as $k => $v) {
  if (is_array($v)) $_SESSION['cart'][$k] = (int)($v['qty'] ?? 0);
  $_SESSION['cart'][$k] = max(0, (int)$_SESSION['cart'][$k]);
  if ($_SESSION['cart'][$k] === 0) unset($_SESSION['cart'][$k]);
}

// CSRF بسيط
if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));

// --- معالجة POST (قبل أي إخراج) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $csrf = $_POST['csrf'] ?? '';
  if (!hash_equals($_SESSION['csrf'], $csrf)) {
    // رمز غير صالح => ارجع لنفس الصفحة برسالة
    header("Location: cart.php?err=csrf");
    exit;
  }

  // تحديث كميات
  if (isset($_POST['update']) && isset($_POST['qty']) && is_array($_POST['qty'])) {
    foreach ($_POST['qty'] as $pid => $q) {
      $pid = (int)$pid;
      $q   = max(0, min(999, (int)$q));
      if ($q <= 0) unset($_SESSION['cart'][$pid]);
      else $_SESSION['cart'][$pid] = $q;
    }
    header("Location: cart.php?updated=1");
    exit;
  }

  // حذف عنصر واحد
  if (isset($_POST['remove'])) {
    $pid = (int)($_POST['remove'] ?? 0);
    unset($_SESSION['cart'][$pid]);
    header("Location: cart.php?removed=1");
    exit;
  }

  // تفريغ السلة
  if (isset($_POST['clear_all'])) {
    $_SESSION['cart'] = [];
    header("Location: cart.php?cleared=1");
    exit;
  }

  // إتمام الطلب
  if (isset($_POST['checkout'])) {
    // بإمكانك التحقق من العناوين/الدفع هنا
    header("Location: bank-transfer.php");
    exit;
  }

  // fallback
  header("Location: cart.php");
  exit;
}

// --- جمع بيانات المنتجات المعروضة ---
$cart = $_SESSION['cart'];
$items = [];
$total = 0.0;

if ($cart) {
  $ids = array_map('intval', array_keys($cart));
  $in  = implode(',', array_fill(0, count($ids), '?'));
  $q   = $pdo->prepare("SELECT id,name,image,weight,karat,metal FROM products WHERE id IN ($in)");
  $q->execute($ids);
  $dbrows = $q->fetchAll(PDO::FETCH_ASSOC);

  // مساعد المسار
  $img_or_placeholder = function($path) {
    if (!$path) return "assets/img/placeholder-hero.jpg";
    $rel = (strpos($path,'uploads/')===0) ? $path : "uploads/products/".ltrim($path,'/');
    return is_file(__DIR__ . "/".$rel) ? $rel : "assets/img/placeholder-hero.jpg";
  };

  foreach ($dbrows as $p) {
    $pid   = (int)$p['id'];
    $qty   = (int)($cart[$pid] ?? 0);
    if ($qty <= 0) continue;

    $isGold= ($p['metal'] ?? 'gold') === 'gold';
    $karat = (int)($p['karat'] ?? 24);
    $wt    = (float)($p['weight'] ?? 0);
    $key   = $isGold ? ("gold_".$karat) : "silver";
    $unit  = (isset($prices[$key]) && is_numeric($prices[$key])) ? (float)$prices[$key] : 0.0; // ر.س/جم
    $piece = $unit * $wt;                 // سعر القطعة
    $sum   = $piece * $qty;               // مجمل العنصر
    $total += $sum;

    $items[] = [
      'id'    => $pid,
      'name'  => $p['name'],
      'image' => $img_or_placeholder($p['image'] ?? ''),
      'weight'=> $wt,
      'karat' => $karat,
      'metal' => $p['metal'],
      'qty'   => $qty,
      'unit'  => $unit,
      'piece' => $piece,
      'sum'   => $sum,
    ];
  }
}

include __DIR__ . "/includes/header.php";
?>
<style>
.cart-wrap{padding:50px 0;width:90%;margin:0 auto}
.section-title{text-align:center;color:#eaeaea;font-size:28px;margin:0 0 18px;position:relative}
.section-title:after{content:'';display:block;width:60px;height:3px;background:var(--primary-color,#d4af37);margin:10px auto;border-radius:10px}
.tbl{width:100%;border-collapse:separate;border-spacing:0 10px}
.tbl thead th{color:#d4af37;font-weight:800;text-align:right;padding:10px;border-bottom:1px solid rgba(212,175,55,.25)}
.tbl tbody tr{background:#121212;border:1px solid rgba(212,175,55,.25);border-radius:14px;box-shadow:0 8px 20px rgba(0,0,0,.35)}
.tbl tbody td{padding:10px;vertical-align:middle}
.tbl tbody tr > td:first-child{border-radius:14px 0 0 14px}
.tbl tbody tr > td:last-child{border-radius:0 14px 14px 0}
.thumb{width:80px;height:70px;object-fit:cover;border-radius:10px;border:1px solid rgba(212,175,55,.25);background:#000}
.qty{width:80px;height:40px;background:#0b0b0b;color:#eaeaea;border:1px solid rgba(212,175,55,.35);border-radius:10px;text-align:center}
.chips{display:flex;gap:8px;flex-wrap:wrap}
.chip{padding:6px 10px;border-radius:999px;font-weight:800;font-size:.85rem;color:#0f0f0f;background:linear-gradient(145deg,#b68f2a,#d4af37,#c8a951)}
.chip.gray{background:#0b0b0b;color:#eaeaea;border:1px solid rgba(212,175,55,.35)}
.row-actions{display:flex;gap:6px}
.icon-btn{width:36px;height:36px;border-radius:10px;border:0;cursor:pointer;display:inline-grid;place-items:center}
.icon-btn.del{background:linear-gradient(145deg,#ef4444,#f87171);color:#0f0f0f}
.icon-btn.upd{background:linear-gradient(145deg,#22c55e,#86efac);color:#0b1d10}
.summary{margin-top:18px;text-align:center;color:#eaeaea;font-size:20px;font-weight:900}
.actions{display:flex;gap:10px;justify-content:center;margin-top:14px;flex-wrap:wrap}
.btn{display:inline-flex;align-items:center;gap:8px;padding:12px 16px;border-radius:12px;font-weight:800;border:0;cursor:pointer;text-decoration:none}
.btn-primary{background:linear-gradient(145deg,#b68f2a,#d4af37,#c8a951);color:#0f0f0f}
.btn-ghost{background:#0b0b0b;color:#eaeaea;border:1px solid rgba(212,175,55,.35)}
.notice{margin:10px auto;color:#9de1a9;text-align:center}
.err{margin:10px auto;color:#fecaca;text-align:center}
</style>

<section class="cart-wrap" dir="rtl">
  <h2 class="section-title"><i class="fa-solid fa-cart-shopping"></i> سلة التسوق</h2>

  <?php if(isset($_GET['err']) && $_GET['err']==='csrf'): ?>
    <div class="err">رمز التأكيد غير صالح. أعد المحاولة.</div>
  <?php endif; ?>
  <?php if(isset($_GET['updated'])): ?><div class="notice">تم تحديث الكميات.</div><?php endif; ?>
  <?php if(isset($_GET['removed'])): ?><div class="notice">تم حذف المنتج من السلة.</div><?php endif; ?>
  <?php if(isset($_GET['cleared'])): ?><div class="notice">تم تفريغ السلة.</div><?php endif; ?>

  <?php if (!$items): ?>
    <div class="summary" style="font-weight:600">🛒 سلتك فارغة.</div>
    <div class="actions">
      <a class="btn btn-primary" href="gold.php"><i class="fa-solid fa-store"></i> تسوّق الذهب</a>
      <a class="btn btn-ghost" href="silver.php"><i class="fa-regular fa-gem"></i> تسوّق الفضة</a>
    </div>
  <?php else: ?>
    <form method="post">
      <input type="hidden" name="csrf" value="<?= htmlspecialchars($_SESSION['csrf']) ?>">
      <div style="overflow:auto">
        <table class="tbl" aria-label="عناصر السلة">
          <thead>
            <tr>
              <th>#</th>
              <th>الصورة</th>
              <th>الاسم</th>
              <th>البيانات</th>
              <th>سعر القطعة</th>
              <th>الكمية</th>
              <th>المجموع</th>
              <th>إجراء</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($items as $i => $it): ?>
              <tr>
                <td><?= $i+1 ?></td>
                <td><img class="thumb" src="<?= htmlspecialchars($it['image']) ?>" alt=""></td>
                <td><?= htmlspecialchars($it['name']) ?></td>
                <td>
                  <div class="chips">
                    <span class="chip"><?= $it['metal']==='gold' ? ('ذهب عيار '.$it['karat']) : 'فضة' ?></span>
                    <span class="chip gray"><?= number_format($it['weight'],2) ?> جم</span>
                    <span class="chip gray"><?= number_format($it['unit'],2) ?> ر.س/جم</span>
                  </div>
                </td>
                <td><?= number_format($it['piece'],2) ?> ر.س</td>
                <td>
                  <input class="qty" type="number" name="qty[<?= (int)$it['id'] ?>]" value="<?= (int)$it['qty'] ?>" min="1" max="999" inputmode="numeric">
                </td>
                <td><strong><?= number_format($it['sum'],2) ?> ر.س</strong></td>
                <td class="row-actions">
                  <button class="icon-btn upd" type="submit" name="update" value="1" title="تحديث الكميات"><i class="fa fa-rotate"></i></button>
                  <button class="icon-btn del" type="submit" name="remove" value="<?= (int)$it['id'] ?>" title="حذف"><i class="fa fa-trash"></i></button>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <div class="summary">الإجمالي الكلي: <?= number_format($total,2) ?> ر.س</div>

      <div class="actions">
        <button class="btn btn-primary" type="submit" name="checkout"><i class="fa-solid fa-cash-register"></i> إتمام الطلب</button>
        <button class="btn btn-ghost" type="submit" name="clear_all" onclick="return confirm('تفريغ السلة؟');"><i class="fa fa-broom"></i> تفريغ السلة</button>
        <a class="btn btn-ghost" href="gold.php"><i class="fa-solid fa-store"></i> متابعة التسوّق</a>
      </div>
    </form>
  <?php endif; ?>
</section>

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