<?php
// admin/product_edit.php
session_start();
require_once __DIR__ . '/../config/db.php';
include __DIR__ . "/partials/header.php";

/* ========== رفع الصور ========== */
function ensure_upload_dir(): array {
  $publicRel = 'uploads';
  $diskDir   = __DIR__ . '/../' . $publicRel;
  if (!is_dir($diskDir)) @mkdir($diskDir, 0775, true);
  return [$diskDir, $publicRel];
}
function safe_filename(string $name, string $prefix='product_'): string {
  $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
  $ext = preg_replace('/[^a-z0-9]+/i', '', $ext);
  if ($ext === '') $ext = 'jpg';
  return $prefix . time() . '_' . bin2hex(random_bytes(3)) . '.' . $ext;
}
function validate_image_upload(array $file, int $maxMB=8): ?string {
  if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) return "فشل الرفع (الكود {$file['error']}).";
  if (($file['size'] ?? 0) > $maxMB * 1024 * 1024) return "حجم الصورة يتجاوز {$maxMB}MB.";
  $fi = new finfo(FILEINFO_MIME_TYPE);
  $mime = $fi->file($file['tmp_name']);
  $ok = ['image/jpeg','image/png','image/webp','image/gif'];
  if (!in_array($mime, $ok, true)) return "نوع الملف غير مدعوم: $mime";
  return null;
}

/* ========== حمل الصفحة ========== */
$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { http_response_code(400); exit('معرّف غير صحيح'); }

$pdo = db();
$stmt = $pdo->prepare("SELECT * FROM products WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$product) { http_response_code(404); exit('المنتج غير موجود'); }

/* ========== CSRF ========== */
if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
$csrf = $_SESSION['csrf'];

/* ========== معالجة التحديث ========== */
$errors = [];
$okMsg  = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    $errors[] = "فشل التحقق الأمني. أعد المحاولة.";
  } else {
    $title   = trim($_POST['title'] ?? ($product['title'] ?? ''));
    $price   = trim($_POST['price'] ?? ($product['price'] ?? ''));
    $metal   = ($_POST['metal'] ?? ($product['metal'] ?? 'gold')) === 'silver' ? 'silver' : 'gold';
    $karat   = (int)($_POST['karat'] ?? ($product['karat'] ?? 24));
    $finen   = trim($_POST['fineness'] ?? ($product['fineness'] ?? '999'));
    $weight  = (float)($_POST['weight'] ?? ($product['weight'] ?? 0));
    $sku     = trim($_POST['sku'] ?? ($product['sku'] ?? ''));
    $brand   = trim($_POST['brand'] ?? ($product['brand'] ?? ''));
    $madein  = trim($_POST['made_in'] ?? ($product['made_in'] ?? ''));
    $stock   = (int)($_POST['stock'] ?? ($product['stock'] ?? 0));
    $status  = (int)($_POST['status'] ?? ($product['status'] ?? 1));
    $desc    = trim($_POST['description'] ?? ($product['description'] ?? ''));

    $attr_keys = $_POST['attr_key'] ?? [];
    $attr_vals = $_POST['attr_val'] ?? [];
    $attributes = [];
    if (is_array($attr_keys) && is_array($attr_vals)) {
      foreach ($attr_keys as $i=>$k) {
        $k = trim((string)$k);
        $v = trim((string)($attr_vals[$i] ?? ""));
        if ($k !== "" || $v !== "") $attributes[] = ["key"=>$k, "value"=>$v];
      }
    }

    if ($title === "")  $errors[] = "الاسم مطلوب.";
    if ($weight < 0)    $errors[] = "الوزن غير صالح.";
    if ($metal === 'gold'   && ($karat < 18 || $karat > 24)) $errors[] = "العيار (ذهب) بين 18 و24.";
    if ($metal === 'silver' && !preg_match('~^\d{3}$~', $finen)) $errors[] = "النقاوة (فضة) ثلاث خانات مثل 925 أو 999.";

    [$diskDir, $publicRel] = ensure_upload_dir();
    if (!is_dir($diskDir) || !is_writable($diskDir)) {
      $errors[] = "مجلد الرفع غير موجود أو غير قابل للكتابة: " . $diskDir;
    }

    // الصورة الرئيسية (اختياري)
    $imagePublic = $product['image'] ?? null;
    if (!$errors && isset($_FILES['image']) && $_FILES['image']['name'] !== '') {
      if ($msg = validate_image_upload($_FILES['image'])) $errors[] = $msg;
      if (!$errors) {
        $name = safe_filename($_FILES['image']['name']);
        $destDisk = $diskDir . DIRECTORY_SEPARATOR . $name;
        if (!move_uploaded_file($_FILES['image']['tmp_name'], $destDisk)) {
          $errors[] = "تعذر حفظ الصورة الرئيسية.";
        } else {
          $imagePublic = $publicRel . '/' . $name;
        }
      }
    }

    // معرض الصور (دمج مع الموجود)
    $gallery = [];
    if (!empty($product['images'])) {
      $tmp = json_decode($product['images'], true);
      if (is_array($tmp)) $gallery = $tmp;
    }
    if (!$errors && !empty($_FILES['gallery']['name'][0])) {
      foreach ($_FILES['gallery']['name'] as $i => $n) {
        if (($_FILES['gallery']['error'][$i] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) continue;
        $fileArr = [
          'name'     => $_FILES['gallery']['name'][$i],
          'type'     => $_FILES['gallery']['type'][$i],
          'tmp_name' => $_FILES['gallery']['tmp_name'][$i],
          'error'    => $_FILES['gallery']['error'][$i],
          'size'     => $_FILES['gallery']['size'][$i],
        ];
        if ($msg = validate_image_upload($fileArr)) { $errors[] = "صورة المعرض ($i): $msg"; continue; }
        $name = safe_filename($n, 'product_');
        $destDisk = $diskDir . DIRECTORY_SEPARATOR . $name;
        if (!move_uploaded_file($fileArr['tmp_name'], $destDisk)) {
          $errors[] = "تعذر حفظ صورة المعرض رقم ".($i+1);
        } else {
          $gallery[] = $publicRel . '/' . $name;
        }
      }
      // إزالة التكرار
      $gallery = array_values(array_unique($gallery));
    }

    if (!$errors) {
      try {
        $stmt = $pdo->prepare("UPDATE products SET
          title=?, description=?, price=?, metal=?, karat=?, fineness=?, weight=?, sku=?, brand=?, made_in=?, stock=?, status=?, image=?, images=?, attributes=?
          WHERE id=?");
        $stmt->execute([
          $title, $desc, $price, $metal, $karat, $finen, $weight, $sku, $brand, $madein, $stock, $status,
          $imagePublic,
          json_encode($gallery, JSON_UNESCAPED_UNICODE),
          json_encode($attributes, JSON_UNESCAPED_UNICODE),
          $id
        ]);

        // مزامنة اختيارية مع عمود name (إن وجد)
        try {
          $pdo->query("SELECT name FROM products LIMIT 1");
          $upd = $pdo->prepare("UPDATE products SET name=? WHERE id=?");
          $upd->execute([$title, $id]);
        } catch (Throwable $e) { /* تجاهل إذا لا يوجد عمود name */ }

        // تحديث الكائن
        $product = array_merge($product, [
          'title'=>$title,'description'=>$desc,'price'=>$price,'metal'=>$metal,'karat'=>$karat,'fineness'=>$finen,'weight'=>$weight,'sku'=>$sku,'brand'=>$brand,'made_in'=>$madein,'stock'=>$stock,'status'=>$status,
          'image'=>$imagePublic,'images'=>json_encode($gallery, JSON_UNESCAPED_UNICODE),'attributes'=>json_encode($attributes, JSON_UNESCAPED_UNICODE)
        ]);

        $okMsg = "تم حفظ التعديلات بنجاح.";
      } catch (Throwable $e) {
        $errors[] = "خطأ في الحفظ: " . $e->getMessage();
      }
    }
  }
}

// تحويل JSON لعرضه في الحقول
$gallery = [];
if (!empty($product['images'])) {
  $tmp = json_decode($product['images'], true);
  if (is_array($tmp)) $gallery = $tmp;
}
$attributes = [];
if (!empty($product['attributes'])) {
  $tmp = json_decode($product['attributes'], true);
  if (is_array($tmp)) $attributes = $tmp;
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;600;800&display=swap" rel="stylesheet">
<title>تعديل منتج</title>
<style>
:root{
  --gold-2:#b68f2a; --gold-3:#d4af37; --gold-4:#c8a951;
  --surface:#0f0f0f; --ink:#eaeaea; --muted:#9aa7b1;
  --ok:#112d1a; --okb:#1f7a33; --err:#3f1d1d; --errb:#7f1d1d;
  --line:rgba(212,175,55,.35);
}
*{box-sizing:border-box}
body{margin:0;background:#0f0f0f;color:var(--ink);font-family:Cairo,Arial}
.wrap{width:min(1100px,92%);margin:22px auto 90px}
h1{margin:0 0 14px;font-weight:900}
.card{background:linear-gradient(180deg,#141414 0%,#0f0f0f 100%);border:1px solid var(--line);border-radius:16px;padding:18px;box-shadow:0 14px 30px rgba(0,0,0,.35);margin-bottom:16px}
.grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}
@media(max-width:860px){.grid{grid-template-columns:1fr}}
.input,.select,.textarea{background:#0b0b0b;color:#eaeaea;border:1px solid var(--line);border-radius:12px;padding:12px;outline:0}
.input:focus,.select:focus,.textarea:focus{border-color:var(--gold-3);box-shadow:0 0 0 3px rgba(212,175,55,.12)}
.textarea{min-height:140px;resize:vertical}
.btn{border:0;border-radius:12px;padding:12px 18px;font-weight:900;cursor:pointer}
.btn-gold{background:linear-gradient(145deg,#b68f2a,#d4af37,#c8a951);color:#0f0f0f}
.alert{border-radius:12px;padding:12px 14px;margin-bottom:12px}
.alert-ok{background:var(--ok);border:1px solid var(--okb);color:#b8f7c8}
.alert-err{background:var(--err);border:1px solid var(--errb);color:#fee2e2}
.gallery{display:flex;gap:10px;flex-wrap:wrap}
.gallery img{width:100px;height:100px;object-fit:cover;border:1px solid var(--line);border-radius:10px}
.attrs{display:grid;grid-template-columns:1fr 1fr auto;gap:10px}
@media(max-width:680px){.attrs{grid-template-columns:1fr 1fr}}
.attr-row{display:contents}
.attr-del{border:0;border-radius:10px;padding:10px 12px;background:#2b2b2b;color:#fff;cursor:pointer}
</style>
</head>
<body>
<div class="wrap">
  <h1>تعديل منتج: <?= htmlspecialchars($product['title'] ?? $product['name'] ?? '—') ?></h1>

  <?php if ($okMsg): ?><div class="alert alert-ok"><?= htmlspecialchars($okMsg) ?></div><?php endif; ?>
  <?php if ($errors): ?><div class="alert alert-err"><?php foreach($errors as $e){echo "• ".htmlspecialchars($e)."<br>";} ?></div><?php endif; ?>

  <form method="post" enctype="multipart/form-data" class="card">
    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf) ?>">

    <div class="grid">
      <div><label>الاسم</label><input class="input" name="title" value="<?= htmlspecialchars($product['title'] ?? '') ?>" required></div>
      <div><label>السعر</label><input class="input" type="number" step="0.01" name="price" value="<?= htmlspecialchars($product['price'] ?? '') ?>"></div>

      <div>
        <label>نوع المنتج</label>
        <select class="select" name="metal" id="metalSel">
          <option value="gold"   <?= (($product['metal'] ?? 'gold')==='gold'?'selected':'') ?>>ذهب</option>
          <option value="silver" <?= (($product['metal'] ?? '')==='silver'?'selected':'') ?>>فضة</option>
        </select>
      </div>
      <div id="karatWrap"><label>العيار (ذهب)</label>
        <select class="select" name="karat">
          <?php foreach([24,22,21,20,18] as $k){ $sel=((int)($product['karat'] ?? 24)===$k)?'selected':''; echo "<option value='$k' $sel>$k</option>"; } ?>
        </select>
      </div>

      <div id="finenessWrap" style="display:none"><label>النقاوة (فضة)</label><input class="input" name="fineness" value="<?= htmlspecialchars($product['fineness'] ?? '999') ?>"></div>

      <div><label>الوزن (جم)</label><input class="input" type="number" step="0.01" name="weight" value="<?= htmlspecialchars($product['weight'] ?? '0') ?>"></div>
      <div><label>SKU</label><input class="input" name="sku" value="<?= htmlspecialchars($product['sku'] ?? '') ?>"></div>
      <div><label>العلامة التجارية</label><input class="input" name="brand" value="<?= htmlspecialchars($product['brand'] ?? '') ?>"></div>
      <div><label>بلد الصنع</label><input class="input" name="made_in" value="<?= htmlspecialchars($product['made_in'] ?? '') ?>"></div>
      <div><label>المخزون</label><input class="input" type="number" name="stock" min="0" value="<?= htmlspecialchars($product['stock'] ?? '0') ?>"></div>
      <div><label>الحالة</label>
        <select class="select" name="status">
          <option value="1" <?= (($product['status'] ?? 1)==1?'selected':'') ?>>منشور</option>
          <option value="0" <?= (($product['status'] ?? 1)==0?'selected':'') ?>>مسودة</option>
        </select>
      </div>

      <div style="grid-column:1/-1">
        <label>الوصف</label>
        <textarea class="textarea" name="description"><?= htmlspecialchars($product['description'] ?? '') ?></textarea>
      </div>
    </div>

    <div class="card">
      <h3 style="margin-top:0">الصورة الحالية</h3>
      <div class="gallery">
        <?php
          $img = $product['image'] ?? '';
          if ($img) {
            $src = (strpos($img,'uploads/')===0) ? '../'.$img : '../uploads/'.$img;
            echo '<img src="'.htmlspecialchars($src).'" alt="">';
          } else {
            echo '<em>لا توجد صورة رئيسية</em>';
          }
        ?>
      </div>
      <label style="display:block;margin-top:10px">استبدال الصورة الرئيسية (اختياري)
        <input type="file" name="image" accept="image/*">
      </label>
    </div>

    <div class="card">
      <h3 style="margin-top:0">معرض الصور الحالي</h3>
      <div class="gallery">
        <?php if ($gallery): foreach ($gallery as $g):
          $src = (strpos($g,'uploads/')===0) ? '../'.$g : '../uploads/'.$g; ?>
          <img src="<?= htmlspecialchars($src) ?>" alt="">
        <?php endforeach; else: ?>
          <em>لا يوجد معرض صور</em>
        <?php endif; ?>
      </div>
      <label style="display:block;margin-top:10px">إضافة صور جديدة للمعرض
        <input type="file" name="gallery[]" accept="image/*" multiple>
      </label>
    </div>

    <div class="card">
      <h3 style="margin-top:0">خصائص إضافية</h3>
      <div class="attrs" id="attrsBox">
        <?php if ($attributes): foreach ($attributes as $row): ?>
          <div class="attr-row">
            <input class="input" name="attr_key[]" placeholder="المفتاح" value="<?= htmlspecialchars($row['key'] ?? '') ?>">
            <input class="input" name="attr_val[]" placeholder="القيمة" value="<?= htmlspecialchars($row['value'] ?? '') ?>">
            <button type="button" class="attr-del" onclick="this.closest('.attr-row').remove()">حذف</button>
          </div>
        <?php endforeach; else: ?>
          <div class="attr-row">
            <input class="input" name="attr_key[]" placeholder="المفتاح">
            <input class="input" name="attr_val[]" placeholder="القيمة">
            <button type="button" class="attr-del" onclick="this.closest('.attr-row').remove()">حذف</button>
          </div>
        <?php endif; ?>
      </div>
      <div style="margin-top:10px"><button class="btn btn-gold" type="button" onclick="addAttr()">+ إضافة سطر</button></div>
    </div>

    <div style="display:flex;gap:10px;justify-content:flex-end">
      <button class="btn btn-gold" type="submit">حفظ</button>
    </div>
  </form>
</div>

<script>
const metalSel=document.getElementById('metalSel'), karatWrap=document.getElementById('karatWrap'), finenessWrap=document.getElementById('finenessWrap');
function toggleMetal(){ const m=metalSel.value; karatWrap.style.display=(m==='gold')?'':'none'; finenessWrap.style.display=(m==='silver')?'':'none'; }
if(metalSel){ metalSel.addEventListener('change',toggleMetal); toggleMetal(); }
function addAttr(){ const box=document.getElementById('attrsBox'); const row=document.createElement('div'); row.className='attr-row';
  row.innerHTML=`<input class="input" name="attr_key[]" placeholder="المفتاح"><input class="input" name="attr_val[]" placeholder="القيمة"><button type="button" class="attr-del" onclick="this.closest('.attr-row').remove()">حذف</button>`;
  box.appendChild(row);
}
</script>
</body>
</html>
