<?php
// admin/product_add.php  (لوحة: إضافة منتج)
session_start();
require_once __DIR__ . "/../config/db.php";
include __DIR__ . "/partials/header.php";

/* ====== أدوات مساعدة ====== */
function e($v): string { return htmlspecialchars((string)($v ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

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;
}

/* ===== 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'] ?? ""); // سنكتب في عمود name
    $price   = (string)($_POST['price'] ?? "");
    $metal   = ($_POST['metal'] ?? 'gold') === 'silver' ? 'silver' : 'gold';
    $karat   = (int)($_POST['karat'] ?? 24);
    $finen   = trim($_POST['fineness'] ?? '999');
    $weight  = (float)($_POST['weight'] ?? 0);
    $sku     = trim($_POST['sku'] ?? "");
    $brand   = trim($_POST['brand'] ?? "");
    $madein  = trim($_POST['madein'] ?? "");
    $stock   = (int)($_POST['stock'] ?? 0);
    $status  = (int)($_POST['status'] ?? 1);
    $desc    = trim($_POST['description'] ?? "");

    // خصائص إضافية (Repeater) => JSON
    $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 = 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; // نخزنه بهذا الشكل في DB
        }
      }
    } else {
      $errors[] = "الصورة الرئيسية مطلوبة.";
    }

    // معرض الصور
    $galleryPublic = [];
    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 {
          $galleryPublic[] = $publicRel . '/' . $name;
        }
      }
    }

    if (!$errors) {
      try {
        // نكتب في عمود name (متوافق مع جدولك الحالي)
        $stmt = db()->prepare("INSERT INTO products
          (`name`, description, price, metal, karat, fineness, weight, sku, brand, made_in, stock, status, image, images, attributes)
          VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        $stmt->execute([
          $title, $desc, $price, $metal, $karat, $finen, $weight, $sku, $brand, $madein, $stock, $status,
          $imagePublic,
          json_encode($galleryPublic, JSON_UNESCAPED_UNICODE),
          json_encode($attributes,   JSON_UNESCAPED_UNICODE)
        ]);

        $okMsg = "تم إضافة المنتج وحفظ الصور في: $publicRel/";
        $_POST = [];
      } catch (Throwable $e) {
        $errors[] = "خطأ في الحفظ: " . $e->getMessage();
      }
    }
  }
}
?>
<!-- ======= CSS من تعليماتك ======= -->
<style>
@import url('https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;600;700;800&display=swap');
:root{
  --gold-2:#b68f2a; --gold-3:#d4af37; --gold-4:#c8a951;
  --surface:#0f0f0f; --surface-2:#121212; --ink:#eaeaea; --muted:#9aa7b1;
  --ok:#112d1a; --okb:#1f7a33; --err:#3f1d1d; --errb:#7f1d1d;
}
html,body,button,input,select,textarea{font-family:'Cairo','Segoe UI',Tahoma,Geneva,Verdana,sans-serif!important}
*,*::before,*::after{box-sizing:border-box}
.admin-wrap{width:min(1100px,92%);margin:22px auto 90px}
.h-title{margin:0 0 14px;font-weight:900;font-size:28px;color:#eaeaea}
.card{background:linear-gradient(180deg,#141414 0%,#0f0f0f 100%);border:1px solid rgba(212,175,55,.45);border-radius:16px;padding:18px;box-shadow:0 14px 30px rgba(0,0,0,.35);margin-bottom:16px}
.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}
@media(max-width:860px){.form-grid{grid-template-columns:1fr}}
.field{display:flex;flex-direction:column;gap:6px}
.label{color:#eaeaea;font-weight:800}
.input,.select,.textarea{background:#0b0b0b;color:#eaeaea;border:1px solid rgba(212,175,55,.35);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}
.helper{color:#9aa7b1;font-size:.9rem}
.actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:8px}
.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;box-shadow:0 12px 28px rgba(212,175,55,.25),inset 0 1px 0 rgba(255,255,255,.25)}
.btn-ghost{background:#121212;color:#eaeaea;border:1px solid rgba(212,175,55,.35)}
.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}
/* رفع الصور */
.uploader{border:1px dashed rgba(212,175,55,.5);border-radius:14px;padding:14px;background:#0b0b0b;color:#cbd5e1;text-align:center}
.uploader.drag{background:#0e0e0e;border-color:var(--gold-3)}
.preview{margin-top:10px;display:grid;grid-template-columns:repeat(6,1fr);gap:10px}
.prev{position:relative;background:#101010;border:1px solid rgba(212,175,55,.25);border-radius:12px;height:80px;overflow:hidden}
.prev img{width:100%;height:100%;object-fit:cover}
.prev button{position:absolute;inset:6px auto auto 6px;border:0;border-radius:10px;padding:6px 8px;background:#2b2b2b;color:#fff;cursor:pointer}
@media(max-width:680px){.preview{grid-template-columns:repeat(4,1fr)}}
/* خصائص ديناميكية */
.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}
.add-attr{margin-top:10px}
</style>

<div class="admin-wrap" dir="rtl">
  <h1 class="h-title">إضافة منتج</h1>

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

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

    <div class="form-grid">
      <div class="field"><label class="label">اسم المنتج</label><input class="input" name="title" required value="<?= e($_POST['title'] ?? '') ?>"></div>
      <div class="field"><label class="label">السعر (اختياري)</label><input class="input" name="price" type="number" step="0.01" value="<?= e($_POST['price'] ?? '') ?>"></div>

      <div class="field">
        <label class="label">نوع المنتج</label>
        <select class="select" name="metal" id="metalSel">
          <option value="gold"   <?= (($_POST['metal'] ?? 'gold')==='gold'?'selected':'') ?>>ذهب</option>
          <option value="silver" <?= (($_POST['metal'] ?? '')==='silver'?'selected':'') ?>>فضة</option>
        </select>
      </div>

      <div class="field" id="karatWrap">
        <label class="label">العيار (ذهب)</label>
        <select class="select" name="karat">
          <?php foreach([24,22,21,20,18] as $k){ $sel=((int)($_POST['karat'] ?? 24)===$k)?'selected':''; echo "<option value='$k' $sel>$k</option>"; } ?>
        </select>
      </div>

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

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

      <div class="field" style="grid-column:1/-1">
        <label class="label">الوصف</label>
        <textarea class="textarea" name="description" maxlength="2000" id="desc"><?= e($_POST['description'] ?? '') ?></textarea>
        <div class="helper"><span id="descCount"><?= strlen((string)($_POST['description'] ?? '')) ?></span>/2000 حرف</div>
      </div>
    </div>

    <div class="card">
      <h3 class="label" style="margin:0 0 10px">خصائص إضافية</h3>
      <div class="attrs" id="attrsBox">
        <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>
      </div>
      <div class="actions add-attr"><button type="button" class="btn btn-ghost" onclick="addAttr()">إضافة سطر</button></div>
    </div>

    <div class="card">
      <h3 class="label" style="margin:0 0 10px">الصورة الرئيسية</h3>
      <div class="uploader" id="upMain">اسحب وأفلت هنا أو اختر<input type="file" name="image" id="imageMain" accept="image/*" style="display:none"></div>
      <div class="preview" id="prevMain"></div>
    </div>

    <div class="card">
      <h3 class="label" style="margin:0 0 10px">معرض الصور</h3>
      <div class="uploader" id="upGallery">اسحب وأفلت هنا (متعدد) أو اختر<input type="file" name="gallery[]" id="imageGallery" accept="image/*" multiple style="display:none"></div>
      <div class="preview" id="prevGallery"></div>
    </div>

    <div class="actions">
      <button class="btn btn-gold" type="submit">حفظ المنتج</button>
      <button class="btn btn-ghost" type="reset">إعادة تعيين</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'; }
metalSel.addEventListener('change',toggleMetal); toggleMetal();
const desc=document.getElementById('desc'), dc=document.getElementById('descCount'); if(desc&&dc){ desc.addEventListener('input',()=>dc.textContent=desc.value.length); }

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);
}
function setupUploader(boxId,inputId,prevId,single=false){
  const box=document.getElementById(boxId), inp=document.getElementById(inputId), prev=document.getElementById(prevId);
  if(!box||!inp||!prev) return;
  box.addEventListener('click',()=>inp.click());
  ['dragenter','dragover'].forEach(e=>box.addEventListener(e,ev=>{ev.preventDefault();box.classList.add('drag');}));
  ['dragleave','drop'].forEach(e=>box.addEventListener(e,ev=>{ev.preventDefault();box.classList.remove('drag');}));
  box.addEventListener('drop',e=>{ if(single){inp.files=e.dataTransfer.files; render();} else { const dt=new DataTransfer(); [...inp.files,...e.dataTransfer.files].forEach(f=>dt.items.add(f)); inp.files=dt.files; render(); }});
  inp.addEventListener('change',render);
  function render(){
    prev.innerHTML='';
    const files=inp.files;
    [...files].forEach((f,i)=>{
      const url=URL.createObjectURL(f);
      const d=document.createElement('div');
      d.className='prev';
      d.innerHTML=`<img src="${url}"><button type="button">حذف</button>`;
      d.querySelector('button').onclick=()=>{
        if(single){inp.value='';prev.innerHTML='';}
        else { const dt=new DataTransfer(); [...files].forEach((ff,ii)=>{if(ii!==i)dt.items.add(ff)}); inp.files=dt.files; render(); }
      };
      prev.appendChild(d);
    });
  }
}
setupUploader('upMain','imageMain','prevMain',true);
setupUploader('upGallery','imageGallery','prevGallery',false);
</script>

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