<?php
// admin/products.php (نسخة مُحسّنة — صف واحد لكل منتج + محرّر وصف منسّق)
session_start();
require_once "../config/db.php";
require_once "../includes/auth.php";
include "partials/header.php";

// (اختياري) حماية بسيطة — غيّرها بنظامك الحقيقي لاحقًا
if (!isset($_SESSION['is_admin'])) { $_SESSION['is_admin'] = true; }

// مجلد الرفع للمنتجات
$uploadDir = __DIR__ . "/../uploads/products";
if (!is_dir($uploadDir)) { @mkdir($uploadDir, 0777, true); }

/* =========================================================
   1) ضمان وجود جدول المنتجات + عمود metal (ذهب/فضة)
   ========================================================= */
try {
  db()->exec("CREATE TABLE IF NOT EXISTS products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    image VARCHAR(190) DEFAULT NULL,
    name VARCHAR(200) NOT NULL,
    description TEXT,
    weight DECIMAL(10,3) DEFAULT 0,
    karat TINYINT DEFAULT NULL,
    status TINYINT(1) DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

  $col = db()->query("SHOW COLUMNS FROM products LIKE 'metal'")->fetch();
  if (!$col) {
    db()->exec("ALTER TABLE products
      ADD COLUMN metal ENUM('gold','silver') NOT NULL DEFAULT 'gold' AFTER karat");
    db()->exec("ALTER TABLE products ADD KEY idx_metal (metal)");
    db()->exec("UPDATE products SET metal='silver' WHERE karat IS NULL OR karat=0");
    db()->exec("UPDATE products SET metal='gold'   WHERE karat IN (18,20,21,22,24)");
  }
} catch (Throwable $e) {
  // error_log('Schema upgrade error: '.$e->getMessage());
}

/* =========================================================
   2) أدوات مساعدة
   ========================================================= */
function save_image($field, $uploadDir) {
  if (!isset($_FILES[$field]) || $_FILES[$field]['error'] !== UPLOAD_ERR_OK) return null;
  $ext = strtolower(pathinfo($_FILES[$field]['name'], PATHINFO_EXTENSION));
  if (!in_array($ext, ['jpg','jpeg','png','webp','gif','svg'])) return null;
  $name = "product_".time()."_".mt_rand(100,999).".".$ext;
  $to   = rtrim($uploadDir,'/\\')."/".$name;
  if (move_uploaded_file($_FILES[$field]['tmp_name'], $to)) {
    return "uploads/products/".$name;
  }
  return null;
}

$msg = ''; $err = '';

/* =========================================================
   3) معالجة الطلبات (إضافة / تعديل / حذف)
   ========================================================= */
if ($_SERVER['REQUEST_METHOD']==='POST') {
  $action = $_POST['action'] ?? '';
  $name   = trim($_POST['name'] ?? '');
  // استلام الوصف كـ HTML من textarea المخفية "description"
  $desc   = trim($_POST['description'] ?? '');
  $weight = (float)($_POST['weight'] ?? 0);
  $karat  = strlen($_POST['karat'] ?? '') ? (int)$_POST['karat'] : null;
  $metal  = ($_POST['metal'] ?? 'gold') === 'silver' ? 'silver' : 'gold';
  $status = isset($_POST['status']) ? 1 : 0;

  if ($action === 'create') {
    if ($name === '') { $err = 'الاسم مطلوب.'; }
    else {
      $img = save_image('image', $uploadDir);
      $st = db()->prepare("INSERT INTO products(image,name,description,weight,karat,metal,status)
                           VALUES(?,?,?,?,?,?,?)");
      $st->execute([$img, $name, $desc, $weight, $karat, $metal, $status]);
      $msg = 'تمت إضافة المنتج بنجاح.';
    }
  }

  if ($action === 'update') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id <= 0) { $err = 'معرّف غير صالح.'; }
    else if ($name === '') { $err = 'الاسم مطلوب.'; }
    else {
      $img = save_image('image', $uploadDir);
      if ($img) {
        $st = db()->prepare("UPDATE products
          SET image=?, name=?, description=?, weight=?, karat=?, metal=?, status=?
          WHERE id=?");
        $st->execute([$img, $name, $desc, $weight, $karat, $metal, $status, $id]);
      } else {
        $st = db()->prepare("UPDATE products
          SET name=?, description=?, weight=?, karat=?, metal=?, status=?
          WHERE id=?");
        $st->execute([$name, $desc, $weight, $karat, $metal, $status, $id]);
      }
      $msg = 'تم تحديث المنتج.';
    }
  }
}

if ($_SERVER['REQUEST_METHOD']==='GET' && isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];
  $st = db()->prepare("DELETE FROM products WHERE id=?");
  $st->execute([$id]);
  $msg = 'تم حذف المنتج.';
}

/* =========================================================
   4) قراءة البيانات
   ========================================================= */
$rows = db()->query("SELECT * FROM products ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);

/* =========================================================
   5) ترويسة/تذييل
   ========================================================= */
function admin_header($title='إدارة المنتجات'){
  $file = __DIR__ . "/header.php";
  if (is_file($file)) { include $file; return; }
  echo "<!DOCTYPE html><html lang='ar' dir='rtl'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'>";
  echo "<title>".htmlspecialchars($title)."</title>";
  echo "<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css'>";
  echo "<style>
  @import url('https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;600;800&display=swap');
  :root{--gold:#d4af37;--ink:#eaeaea;--muted:#9aa7b1;--bg:#0f0f0f;--card:#121212;--line:rgba(212,175,55,.35)}
  *{box-sizing:border-box}
  body{font-family:'Cairo',Tahoma,Arial;background:var(--bg);color:var(--ink);margin:0}
  .wrap{width:min(1250px,96%);margin:24px auto}
  .h{display:flex;justify-content:space-between;align-items:center;margin-bottom:14px}
  .card{background:var(--card);border:1px solid var(--line);border-radius:14px;box-shadow:0 10px 24px rgba(0,0,0,.35);padding:14px}
  .row{display:grid;grid-template-columns:repeat(12,1fr);gap:14px}
  .row > div{grid-column:span 6}
  .row > div:nth-child(-n+4){grid-column:span 3}
  .row > div:nth-child(5){grid-column:span 6}
  .row > div:nth-child(6){grid-column:span 3}
  @media(max-width:900px){.row > div{grid-column:span 12}}

  input,select,textarea{width:100%;background:#0b0b0b;color:var(--ink);border:1px solid var(--line);border-radius:10px;padding:10px}
  label{display:block;margin-bottom:6px;color:#ddd}
  .actions{display:flex;gap:10px;margin-top:12px}
  .btn{display:inline-flex;align-items:center;gap:8px;padding:10px 14px;border-radius:10px;background:linear-gradient(145deg,#b68f2a,#d4af37,#c8a951);color:#0f0f0f;text-decoration:none;border:0;cursor:pointer;font-weight:800}
  .btn.secondary{background:#1f2937;color:#e5e7eb;border:1px solid #374151}
  .alert{padding:10px;border-radius:10px;margin:10px 0;font-weight:700}
  .ok{background:#112d1a;border:1px solid #1f7a33}
  .er{background:#3f1d1d;border:1px solid #7f1d1d}

  /* ===== جدول كوْمباكت بصف واحد لكل منتج ===== */
  .tbl{width:100%;border-collapse:separate;border-spacing:0 8px}
  .tbl thead th{
    color:var(--gold); font-weight:800; text-align:right; padding:8px 10px;
    border-bottom:1px solid rgba(212,175,55,.25);
    white-space:nowrap;
  }
  .tbl tbody tr{
    background:#121212; border:1px solid rgba(212,175,55,.25);
    box-shadow:0 6px 16px rgba(0,0,0,.25); border-radius:12px;
  }
  .tbl tbody td{
    padding:10px; vertical-align:middle; white-space:nowrap;
  }
  .tbl tbody tr > td:first-child{border-radius:12px 0 0 12px}
  .tbl tbody tr > td:last-child{border-radius:0 12px 12px 0}

  /* صور، نصوص مختصرة، شارات، وأزرار أيقونية */
  .thumb{width:64px;height:54px;object-fit:cover;border-radius:8px;border:1px solid rgba(212,175,55,.3);background:#000;display:block}
  .name{max-width:260px;overflow:hidden;text-overflow:ellipsis}
  .desc{max-width:380px;overflow:hidden;text-overflow:ellipsis}
  .chip{display:inline-block;padding:6px 10px;border-radius:999px;font-weight:800;font-size:.85rem;color:#0f0f0f;background:linear-gradient(145deg,#b68f2a,#d4af37,#c8a951)}
  .chip.gray{background:#30353b;color:#e5e7eb;font-weight:600}
  .chip.ghost{background:#0b0b0b;color:#e5e7eb;border:1px solid var(--line)}

  .row-actions{display:flex;gap:6px;align-items:center}
  .icon-btn{
    width:36px;height:36px;border-radius:10px;border:0;cursor:pointer;
    display:inline-grid;place-items:center;
    background:linear-gradient(145deg,#b68f2a,#d4af37,#c8a951); color:#0f0f0f;
  }
  .icon-btn.view{background:#0b0b0b;color:#e5e7eb;border:1px solid var(--line)}
  .icon-btn.edit{background:linear-gradient(145deg,#f59e0b,#fbbf24);color:#0f0f0f}
  .icon-btn.del{background:linear-gradient(145deg,#ef4444,#f87171);color:#0f0f0f}

  /* ===== محرّر الوصف ===== */
  .editor-wrap{border:1px solid var(--line);border-radius:12px;background:#0b0b0b}
  .editor-toolbar{
    display:flex;flex-wrap:wrap;gap:6px;padding:8px;border-bottom:1px solid var(--line);
    background:#0e0e0e;border-radius:12px 12px 0 0
  }
  .tbtn{
    display:inline-flex;align-items:center;justify-content:center;gap:6px;
    min-width:34px;height:34px;padding:0 10px;border-radius:8px;border:1px solid #2a2a2a;
    background:#121212;color:#eaeaea;cursor:pointer;font-weight:700
  }
  .tbtn:hover{background:#161616}
  .tbtn.active{outline:2px solid rgba(212,175,55,.35)}
  .editor-area{
    min-height:110px;max-height:360px;overflow:auto;padding:10px;background:#0b0b0b;color:#eaeaea;border-radius:0 0 12px 12px
  }
  .editor-area:focus{outline:none;box-shadow:inset 0 0 0 2px rgba(212,175,55,.2)}
  .editor-area p{margin:0 0 8px}
  </style></head><body><div class='wrap'>";
  echo "<div class='h'><h2 style='margin:0'>إدارة المنتجات</h2><a class='btn' href='products.php' title='تحديث'><i class='fa fa-rotate'></i> تحديث</a></div>";
}
function admin_footer(){
  $f = __DIR__ . "/footer.php";
  if (is_file($f)) include $f; else echo "</div></body></html>";
}

admin_header('إدارة المنتجات');
?>

<div class="card">
  <?php if(!empty($msg)): ?><div class="alert ok"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
  <?php if(!empty($err)): ?><div class="alert er"><?= htmlspecialchars($err) ?></div><?php endif; ?>

  <form method="post" enctype="multipart/form-data" id="productForm" style="margin-bottom:14px">
    <h3 style="margin:6px 0 12px">إضافة / تعديل منتج</h3>
    <input type="hidden" name="action" value="create" id="formAction">
    <input type="hidden" name="id" id="pid">

    <div class="row">
      <div>
        <label>الاسم *</label>
        <input type="text" name="name" id="pname" required>
      </div>
      <div>
        <label>النوع</label>
        <div style="display:flex;gap:14px;align-items:center">
          <label><input type="radio" name="metal" value="gold" checked> سبائك ذهب</label>
          <label><input type="radio" name="metal" value="silver"> سبائك فضة</label>
        </div>
      </div>
      <div>
        <label>العيار (18/20/21/22/24) — اتركه فارغًا للفضة</label>
        <input type="number" name="karat" id="pkarat" min="0" max="24" step="1" placeholder="مثال: 24">
      </div>
      <div>
        <label>الوزن (جم)</label>
        <input type="number" name="weight" id="pweight" min="0" step="0.001" placeholder="0.000">
      </div>
      <div>
        <label>الصورة (jpg/png/webp...)</label>
        <input type="file" name="image" accept=".jpg,.jpeg,.png,.webp,.gif,.svg">
      </div>
      <div>
        <label>الحالة</label>
        <label style="display:flex;align-items:center;gap:8px"><input type="checkbox" name="status" id="pstatus" checked> نشط</label>
      </div>

      <!-- ===== محرّر الوصف ===== -->
      <div style="grid-column:1/-1">
        <label>الوصف (منسق)</label>
        <div class="editor-wrap" dir="rtl">
          <div class="editor-toolbar" id="editorToolbar">
            <button type="button" class="tbtn" data-cmd="formatBlock" data-val="p" title="نص عادي"><i class="fa fa-paragraph"></i></button>
            <button type="button" class="tbtn" data-cmd="formatBlock" data-val="h3" title="عنوان فرعي"><i class="fa fa-heading"></i></button>
            <span style="width:1px;height:24px;background:#2a2a2a;margin:0 6px"></span>
            <button type="button" class="tbtn" data-cmd="bold" title="غامق"><i class="fa fa-bold"></i></button>
            <button type="button" class="tbtn" data-cmd="italic" title="مائل"><i class="fa fa-italic"></i></button>
            <button type="button" class="tbtn" data-cmd="underline" title="تحته خط"><i class="fa fa-underline"></i></button>
            <button type="button" class="tbtn" data-cmd="removeFormat" title="مسح التنسيق"><i class="fa fa-eraser"></i></button>
            <span style="width:1px;height:24px;background:#2a2a2a;margin:0 6px"></span>
            <button type="button" class="tbtn" data-cmd="insertUnorderedList" title="قائمة نقطية"><i class="fa fa-list-ul"></i></button>
            <button type="button" class="tbtn" data-cmd="insertOrderedList" title="قائمة رقمية"><i class="fa fa-list-ol"></i></button>
            <span style="width:1px;height:24px;background:#2a2a2a;margin:0 6px"></span>
            <button type="button" class="tbtn" data-cmd="justifyRight" title="محاذاة يمين"><i class="fa fa-align-right"></i></button>
            <button type="button" class="tbtn" data-cmd="justifyCenter" title="محاذاة وسط"><i class="fa fa-align-center"></i></button>
            <button type="button" class="tbtn" data-cmd="justifyLeft" title="محاذاة يسار"><i class="fa fa-align-left"></i></button>
            <span style="width:1px;height:24px;background:#2a2a2a;margin:0 6px"></span>
            <button type="button" class="tbtn" id="lnk" title="إضافة رابط"><i class="fa fa-link"></i></button>
            <button type="button" class="tbtn" data-cmd="unlink" title="إزالة رابط"><i class="fa fa-unlink"></i></button>
            <span style="width:1px;height:24px;background:#2a2a2a;margin:0 6px"></span>
            <button type="button" class="tbtn" data-cmd="undo" title="تراجع"><i class="fa fa-rotate-left"></i></button>
            <button type="button" class="tbtn" data-cmd="redo" title="إعادة"><i class="fa fa-rotate-right"></i></button>
            <span style="width:1px;height:24px;background:#2a2a2a;margin:0 6px"></span>
            <button type="button" class="tbtn" id="rtlBtn" title="اتجاه عربي (يمين→يسار)"><i class="fa fa-language"></i> RTL</button>
            <button type="button" class="tbtn" id="ltrBtn" title="اتجاه إنجليزي (يسار→يمين)">LTR</button>
          </div>
          <div class="editor-area" id="pdesc_editor" contenteditable="true"></div>
        </div>
        <!-- الحقل الذي يُرسل فعليًا إلى السيرفر -->
        <textarea name="description" id="pdesc" rows="3" style="display:none"></textarea>
      </div>
    </div>

    <div class="actions">
      <button class="btn" type="submit" title="حفظ"><i class="fa fa-check"></i> حفظ</button>
      <button class="btn secondary" type="button" onclick="resetForm()" title="تفريغ"><i class="fa fa-broom"></i> تفريغ</button>
    </div>
  </form>
</div>

<div class="card" style="margin-top:14px">
  <div style="overflow:auto">
    <table class="tbl" dir="rtl" aria-label="جدول المنتجات">
      <thead>
        <tr>
          <th>#</th>
          <th>الصورة</th>
          <th>الاسم</th>
          <th>الوصف</th>
          <th>الوزن</th>
          <th>العيار</th>
          <th>النوع</th>
          <th>الحالة</th>
          <th>إجراءات</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($rows as $r): ?>
          <?php
            $img = $r['image'] ? (strpos($r['image'],'uploads/')===0 ? $r['image'] : 'uploads/products/'.$r['image']) : '';
            $img = (is_file(__DIR__."/../".$img)) ? $img : 'assets/img/placeholder-hero.jpg';
            $isGold = ($r['metal'] ?? 'gold') === 'gold';
            $karat  = $isGold ? ((int)$r['karat'] ?: '-') : '—';
          ?>
          <tr>
            <td><?= (int)$r['id'] ?></td>
            <td><img class="thumb" src="../<?= htmlspecialchars($img) ?>" alt=""></td>
            <td class="name" title="<?= htmlspecialchars($r['name']) ?>"><?= htmlspecialchars($r['name']) ?></td>
            <td class="desc" title="<?= htmlspecialchars(strip_tags($r['description'] ?? '')) ?>">
              <?= htmlspecialchars(mb_strimwidth((string)strip_tags($r['description'] ?? ''),0,120,'...','UTF-8')) ?>
            </td>
            <td><span class="chip gray"><?= number_format((float)$r['weight'],3) ?> جم</span></td>
            <td><span class="chip ghost"><?= $karat ?></span></td>
            <td><span class="chip"><?= $isGold ? 'سبائك ذهب' : 'سبائك فضة' ?></span></td>
            <td>
              <span class="chip <?= ((int)$r['status']===1?'':'gray') ?>">
                <?= ((int)$r['status']===1 ? 'نشط' : 'موقوف') ?>
              </span>
            </td>
            <td>
              <div class="row-actions">
                <a class="icon-btn view" href="../product.php?id=<?= (int)$r['id'] ?>" target="_blank" title="عرض"><i class="fa fa-eye"></i></a>
                <button class="icon-btn edit" title="تعديل"
                  onclick='editRow(<?= json_encode([
                    "id"=>$r["id"],
                    "name"=>$r["name"],
                    "description"=>$r["description"],
                    "weight"=>$r["weight"],
                    "karat"=>$r["karat"],
                    "metal"=>$r["metal"] ?? "gold",
                    "status"=>$r["status"]
                  ], JSON_UNESCAPED_UNICODE) ?>)'><i class="fa fa-pen"></i></button>
                <a class="icon-btn del" href="?delete=<?= (int)$r['id'] ?>" title="حذف"
                   onclick="return confirm('تأكيد حذف المنتج؟');"><i class="fa fa-trash"></i></a>
              </div>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if(!$rows): ?>
          <tr><td colspan="9" style="text-align:center;color:var(--muted)">لا توجد منتجات بعد.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<script>
// ===== محرّر الوصف: تنفيذ الأوامر =====
(function initEditor(){
  const editor = document.getElementById('pdesc_editor');
  const hidden = document.getElementById('pdesc');
  const form   = document.getElementById('productForm');

  // تهيئة اتجاه افتراضي عربي
  editor.setAttribute('dir','rtl');

  // تنفيذ الأوامر العامة من الأزرار
  document.getElementById('editorToolbar').addEventListener('click', function(e){
    const btn = e.target.closest('.tbtn');
    if(!btn) return;
    const cmd = btn.dataset.cmd;
    if(!cmd) return;

    // روابط
    if (btn.id === 'lnk') {
      const url = prompt('أدخل الرابط (https://...)');
      if (url) document.execCommand('createLink', false, url);
      return;
    }

    // تنفيذ مباشر
    const val = btn.dataset.val || null;
    document.execCommand(cmd, false, val);
    editor.focus();
  });

  // أزرار تغيير الاتجاه
  document.getElementById('rtlBtn').addEventListener('click', ()=>{
    editor.setAttribute('dir','rtl');
  });
  document.getElementById('ltrBtn').addEventListener('click', ()=>{
    editor.setAttribute('dir','ltr');
  });

  // مزامنة: عند الكتابة وفي الإرسال
  const sync = ()=> hidden.value = editor.innerHTML.trim();
  editor.addEventListener('input', sync);
  form.addEventListener('submit', sync);

  // لصق كنص منسّق خفيف (نزيل تنسيقات زائدة من أوفيس/الويب)
  editor.addEventListener('paste', function(e){
    e.preventDefault();
    const text = (e.clipboardData || window.clipboardData).getData('text/plain');
    document.execCommand('insertText', false, text);
  });
})();

// ===== تعبئة النموذج من الصف
function editRow(data){
  document.getElementById('formAction').value='update';
  document.getElementById('pid').value=data.id||'';
  document.getElementById('pname').value=data.name||'';
  document.getElementById('pweight').value=data.weight||'';
  document.getElementById('pkarat').value=data.karat||'';
  (document.querySelector('input[name="metal"][value="silver"]')||{}).checked = (data.metal==='silver');
  (document.querySelector('input[name="metal"][value="gold"]')||{}).checked   = (data.metal!=='silver');
  document.getElementById('pstatus').checked = (String(data.status)==='1');

  // الوصف المنسّق
  const editor = document.getElementById('pdesc_editor');
  const hidden = document.getElementById('pdesc');
  editor.innerHTML = (data.description||'');
  hidden.value = (data.description||'');

  window.scrollTo({top:0,behavior:'smooth'});
}

function resetForm(){
  document.getElementById('formAction').value='create';
  document.getElementById('pid').value='';
  document.getElementById('pname').value='';
  document.getElementById('pweight').value='';
  document.getElementById('pkarat').value='';
  (document.querySelector('input[name="metal"][value="gold"]')||{}).checked = true;
  (document.querySelector('input[name="metal"][value="silver"]')||{}).checked = false;
  document.getElementById('pstatus').checked=true;

  // تفريغ المحرّر والوصف
  const editor = document.getElementById('pdesc_editor');
  const hidden = document.getElementById('pdesc');
  editor.innerHTML = '';
  hidden.value = '';
}
</script>
<?php admin_footer(); ?>
<?php include "partials/footer.php"; ?>
