<?php
require_once __DIR__ . "/config/db.php";
require_once __DIR__ . "/config/price.php";
include __DIR__ . "/includes/header.php";
/* ===== جلب "من نحن" للواجهة من نفس جدول صفحة من نحن ===== */
$intro = db()->query("SELECT * FROM about_intro WHERE id=1")->fetch(PDO::FETCH_ASSOC);

/* ===== جلب بيانات أساسية ===== */
$products = db()->query("SELECT * FROM products ORDER BY id DESC")->fetchAll();
$prices   = getPrices();

/* شرائح السلايدر العلوي */
$slides = db()->query("SELECT * FROM sliders WHERE status=1 ORDER BY sort, id")->fetchAll();
if (!$slides) {
  $slides = [
    ['image'=>'uploads/hero1.jpg','title'=>'الكندي للذهب والمجوهرات','subtitle'=>'نقدّم أجود أنواع الذهب الخالص بمعايير الجودة والنقاء 999.9 وخدمة متميزة','button_text'=>'اكتشف المجموعة','link'=>'gold.php'],
    ['image'=>'uploads/hero2.jpg','title'=>'سبائك واستثمار بثقة','subtitle'=>'خيارات مدروسة مع تحديث أسعار لحظي وشفافية كاملة','button_text'=>'تعرّف على السبائك','link'=>'gold.php'],
    ['image'=>'uploads/hero3.jpg','title'=>'PAMP سويسرا – موزع معتمد','subtitle'=>'نفخر بكوننا الموزع الرئيسي المعتمد لسبائك PAMP السويسرية بالمملكة','button_text'=>'تعرف على الاعتماد','link'=>'about.php'],
  ];
}

/* إنشاء جدول السلايدر السفلي (اختياري) */
db()->exec("
CREATE TABLE IF NOT EXISTS home_banners (
  id INT AUTO_INCREMENT PRIMARY KEY,
  image VARCHAR(255) NOT NULL,
  link  VARCHAR(255) DEFAULT NULL,
  sort INT DEFAULT 0,
  status TINYINT(1) DEFAULT 1,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/* شرائح السلايدر السفلي (بلا عبارات) */
$bottomSlides = [];
try {
  $bottomSlides = db()->query("SELECT * FROM home_banners WHERE status=1 ORDER BY sort, id")->fetchAll();
} catch (Throwable $e) { /* تجاهل */ }
/* إن لم توجد بيانات سنعيد استخدام صور العلوي دون عناوين */
if (!$bottomSlides) {
  $bottomSlides = array_map(function($s){
    return ['image' => $s['image'] ?? 'assets/img/placeholder-hero.jpg', 'link' => $s['link'] ?? ''];
  }, $slides);
}

/* المدونة — آخر 4 للواجهة */
$blog4 = db()->query("SELECT id,title,summary,image,created_at FROM blog_posts WHERE status=1 ORDER BY created_at DESC, id DESC LIMIT 4")->fetchAll();

/* ===== قسم ما يميزنا (ديناميكي) ===== */
db()->exec("
CREATE TABLE IF NOT EXISTS features (
  id INT AUTO_INCREMENT PRIMARY KEY,
  title VARCHAR(200) NOT NULL,
  description TEXT,
  items TEXT,
  icon VARCHAR(80) DEFAULT 'fa-gem',
  sort INT DEFAULT 0,
  status TINYINT(1) DEFAULT 1,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");
$features = db()->query("SELECT * FROM features WHERE status=1 ORDER BY sort, id")->fetchAll();

/* ===== تواصل: تجهيز البيانات ومعالجة النموذج ===== */
db()->exec("
CREATE TABLE IF NOT EXISTS contact_messages (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(120) NOT NULL,
  email VARCHAR(160) DEFAULT NULL,
  phone VARCHAR(60) DEFAULT NULL,
  subject VARCHAR(200) DEFAULT NULL,
  message TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

$contact_ok = false; $contact_err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['__contact_token'])) {
  $name    = trim($_POST['name'] ?? '');
  $email   = trim($_POST['email'] ?? '');
  $phone   = trim($_POST['phone'] ?? '');
  $subject = trim($_POST['subject'] ?? '');
  $message = trim($_POST['message'] ?? '');
  if ($name === '' || $message === '') {
    $contact_err = 'الرجاء تعبئة الاسم والرسالة.';
  } else {
    $stmt = db()->prepare("INSERT INTO contact_messages(name,email,phone,subject,message) VALUES(?,?,?,?,?)");
    $stmt->execute([$name,$email,$phone,$subject,$message]);
    $contact_ok = true;
  }
}

/* شعارات الشركاء */
$partners = [];
try {
  $partners = db()->query("SELECT name, logo, url FROM partners WHERE status=1 ORDER BY sort, id")->fetchAll();
} catch (Throwable $e) { /* تجاهل */ }
if (!$partners) {
  $dir = __DIR__ . '/uploads/partners';
  if (is_dir($dir)) {
    foreach (glob($dir.'/*.{png,jpg,jpeg,webp,svg}', GLOB_BRACE) as $p) {
      $partners[] = ['name'=>pathinfo($p,PATHINFO_FILENAME),'logo'=>'uploads/partners/'.basename($p),'url'=>''];
    }
  }
}

/* ===== دوال مساعدة ===== */
function fix_image_url($p){
  $p = trim((string)$p);
  if ($p !== '' && (stripos($p,'http://')===0 || stripos($p,'https://')===0 || stripos($p,'data:')===0)) return $p;
  if ($p !== '' && strpos($p,'/')===false) $p = 'uploads/'.$p;
  $abs = __DIR__ . '/' . ltrim($p,'/');
  return is_file($abs) ? $p : 'assets/img/placeholder-hero.jpg';
}
function fix_logo($path){
  $path = trim((string)$path);
  if ($path === '') return 'assets/img/placeholder-hero.jpg';
  if (stripos($path,'http://')===0 || stripos($path,'https://')===0) return $path;
  $rel = (strpos($path,'/')===false) ? 'uploads/'.$path : $path;
  return is_file(__DIR__ . '/' . ltrim($rel,'/')) ? $rel : 'assets/img/placeholder-hero.jpg';
}
function product_img($path){
  $path = trim((string)$path);
  if ($path === '') return 'assets/img/placeholder-hero.jpg';
  $rel = (strpos($path,'uploads/')===0) ? $path : 'uploads/products/'.ltrim($path,'/');
  return is_file(__DIR__ . '/' . ltrim($rel,'/')) ? $rel : 'assets/img/placeholder-hero.jpg';
}

/* ===== تنقية/تهيئة وصف المنتج للعرض الأمامي ===== */
function sanitize_desc_full($html){
  $html = (string)$html;

  // إزالة سكربت/ستايل
  $html = preg_replace('#<(script|style)[^>]*>.*?</\1>#is','',$html);

  // تحويل فواصل p/div إلى <br>
  $html = preg_replace('#</?(p|div)[^>]*>#i','<br>',$html);

  // تحويل القوائم إلى نقاط
  $html = preg_replace('#</?ul[^>]*>#i','',$html);
  $html = preg_replace('#</?ol[^>]*>#i','',$html);
  $html = preg_replace('#<li[^>]*>(.*?)</li>#is','• $1<br>',$html);

  // السماح بالوسوم الأساسية فقط
  $allowed = '<br><b><strong><i><em><u><a>';
  $html = strip_tags($html, $allowed);

  // تحسين الروابط (target+rel) + منع javascript:
  $html = preg_replace_callback('/<a\s([^>]*?)href=(["\'])(.*?)\2([^>]*)>/iu', function($m){
    $attrs = trim($m[1].' '.$m[4]);
    $href  = trim($m[3]);

    // منع مخططات غير آمنة
    if (preg_match('/^\s*javascript:/i',$href)) { $href = '#'; }

    if (!preg_match('/\btarget\s*=/i',$attrs)) $attrs .= ' target="_blank"';
    if (!preg_match('/\brel\s*=/i',$attrs))    $attrs .= ' rel="nofollow noopener"';

    // تهريب آمن لقيمة href داخل الوسم فقط
    $href = htmlspecialchars($href, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');

    return '<a href="'.$href.'" '.$attrs.'>';
  }, $html);

  // إزالة تكرار <br>
  $html = preg_replace('/(\s*<br>\s*){3,}/i','<br><br>',$html);

  return trim($html);
}

function plain_excerpt($html, $len=160){
  $txt = trim(preg_replace('/\s+/u',' ', strip_tags((string)$html)));
  if (mb_strlen($txt,'UTF-8') > $len) $txt = mb_substr($txt,0,$len,'UTF-8').'…';
  return $txt;
}

/* جهّز حقول الوصف المنسّق لكل منتج لاستخدامها لاحقًا في الواجهة */
foreach ($products as &$__p) {
  $full = sanitize_desc_full($__p['description'] ?? '');
  $__p['_desc_html']  = $full;                 // لعرضه داخل البطاقة/التفاصيل
  $__p['_desc_plain'] = plain_excerpt($full);  // لخصائص title/alt أو بديل نصّي
}
unset($__p);
?>

<style>
/* ===== Cairo + قاعدة عامة ===== */
@import url('https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap');
html,body,button,input,select,textarea{font-family:'Cairo','Segoe UI',Tahoma,Geneva,Verdana,sans-serif!important}

/* ===== HERO SLIDER (علوي) ===== */
.hero-slider{position:relative;height:520px;overflow:hidden;z-index:1;background:#000;margin:0}
.hero-track{height:100%;position:relative}
.hero-slide{position:absolute;inset:0;background-image:var(--bg);background-size:cover;background-position:center;opacity:0;transform:scale(1.02);transition:opacity .8s,transform 1.2s}
.hero-slide.is-active{opacity:1;transform:scale(1)}
.hero-overlay{position:absolute;inset:0;background:linear-gradient(to bottom,rgba(0,0,0,.55),rgba(0,0,0,.55))}
.hero-content{position:relative;z-index:2;height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:0 20px;max-width:1100px;margin-inline:auto}
.hero-title{color:var(--primary-color);font-size:48px;line-height:1.2;margin:0 0 16px;font-weight:800;text-shadow:0 2px 8px rgba(0,0,0,.35)}
.hero-subtitle{color:#eee;font-size:20px;line-height:1.7;margin:0 0 26px;text-shadow:0 2px 6px rgba(0,0,0,.35)}
.hero-btn{display:inline-block;background:var(--primary-color);color:#000!important;text-decoration:none!important;padding:12px 26px;border-radius:8px;font-weight:700;box-shadow:0 8px 20px rgba(0,0,0,.25);transition:transform .2s,box-shadow .2s,background .2s}
.hero-btn:hover{background:#ffd700;transform:translateY(-2px);box-shadow:0 10px 24px rgba(0,0,0,.35)}
.hero-arrow{position:absolute;top:50%;transform:translateY(-50%);width:44px;height:44px;border-radius:50%;border:0;cursor:pointer;background:rgba(0,0,0,.45);color:#fff;display:flex;align-items:center;justify-content:center;z-index:3;transition:background .2s,transform .2s}
.hero-prev{right:18px}.hero-next{left:18px}
.hero-arrow:hover{background:rgba(0,0,0,.65);transform:translateY(-50%) scale(1.06)}
.hero-dots{position:absolute;inset-inline:0;bottom:18px;display:flex;gap:8px;align-items:center;justify-content:center;z-index:3}
.hero-dot{width:10px;height:10px;border-radius:50%;border:0;cursor:pointer;background:rgba(255,255,255,.45);transition:transform .2s,background .2s}
.hero-dot.active{background:var(--primary-color);transform:scale(1.15)}
@media (max-width:992px){.hero-slider{height:440px}.hero-title{font-size:36px}.hero-subtitle{font-size:18px}}
@media (max-width:576px){.hero-slider{height:380px}.hero-title{font-size:28px}.hero-subtitle{font-size:16px}}

/* ===== HERO SLIDER (سفلي مصغّر بلا عبارات) ===== */
.hero-slider--mini{height:360px;margin:34px 0 0}
.hero-slider--mini .hero-overlay{background:linear-gradient(to bottom,rgba(0,0,0,.35),rgba(0,0,0,.35))}
.hero-slider--mini .hero-content{display:none} /* لا نعرض العناوين */
@media (max-width:992px){.hero-slider--mini{height:300px}}
@media (max-width:576px){.hero-slider--mini{height:240px}}

/* ===== About (Home) ===== */
:root{ --gold-1:#7a5c1e; --gold-2:#b68f2a; --gold-3:#d4af37; --gold-4:#c8a951; --gold-5:#8d6b21; }
.about-section{padding:60px 0}
.about-wrap{width:min(1100px,95%);margin:0 auto;padding-inline:12px}
.about-card{position:relative;isolation:isolate;background:
  radial-gradient(1200px 400px at 100% -50%, rgba(212,175,55,.10), transparent 60%),
  linear-gradient(180deg,#121212 0%,#0f0f0f 100%);
color:var(--text-color);border-radius:16px;padding:clamp(18px,3vw,28px) clamp(18px,3vw,32px);
display:grid;grid-template-columns:84px 1fr;gap:clamp(14px,2.4vw,24px);box-shadow:0 8px 28px rgba(0,0,0,.35);overflow:hidden}
.about-border{position:absolute;inset:-1px;border-radius:18px;pointer-events:none;z-index:0;background:conic-gradient(from 180deg,var(--gold-1),var(--gold-2),var(--gold-3),var(--gold-4),var(--gold-2),var(--gold-1));filter:blur(10px) saturate(1.2);opacity:.18;animation:about-rotate 6s linear infinite}
@keyframes about-rotate{to{transform:rotate(360deg)}}
.about-icon{align-self:start;width:84px;height:84px;border-radius:50%;background:
  radial-gradient(circle at 30% 30%, rgba(255,255,255,.15), transparent 35%),
  linear-gradient(145deg,var(--gold-2),var(--gold-3),var(--gold-4));box-shadow:inset 0 2px 8px rgba(255,255,255,.12),0 8px 24px rgba(0,0,0,.45);display:grid;place-items:center;position:relative;z-index:1}
.about-icon i{font-size:32px;color:#1a1a1a;text-shadow:0 1px 0 rgba(255,255,255,.25)}
.about-content{position:relative;z-index:1}
.about-title{font-size:clamp(22px,2.4vw,28px);margin:4px 0 10px;letter-spacing:.3px;background:linear-gradient(90deg,var(--gold-2),var(--gold-3),var(--gold-4));-webkit-background-clip:text;background-clip:text;color:transparent}
.about-text{color:var(--dark-gray);line-height:1.9;font-size:16px}
.about-btn{margin-top:14px;display:inline-block;padding:10px 18px;border-radius:10px;font-weight:700;text-decoration:none;color:#0d0d0d;background:linear-gradient(145deg,var(--gold-2),var(--gold-3),var(--gold-4));box-shadow:inset 0 1px 0 rgba(255,255,255,.25),0 10px 24px rgba(212,175,55,.25);transition:transform .2s ease,box-shadow .2s ease,filter .2s ease}
.about-btn:hover{transform:translateY(-2px);filter:saturate(1.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.25),0 14px 30px rgba(212,175,55,.32)}
.reveal{opacity:0;transform:translateY(18px) scale(.98);transition:opacity .6s ease,transform .6s ease}
.reveal.is-visible{opacity:1;transform:translateY(0) scale(1)}
.about-card:hover{box-shadow:0 10px 30px rgba(0,0,0,.45)}
.about-card:hover .about-border{opacity:.24}
@media (max-width:640px){.about-card{grid-template-columns:64px 1fr;padding:18px}.about-icon{width:64px;height:64px}}
@media (prefers-reduced-motion:reduce){.about-border{animation:none}.reveal{transition:none;opacity:1;transform:none}.about-btn{transition:none}}

/* ===== ما يميزنا ===== */
.features-dark{padding:60px 0;width:90%;margin:0 auto}
.features-dark .section-title{margin-bottom:26px}
.features-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:24px}
@media(max-width:768px){.features-grid{grid-template-columns:1fr}}
.fcard{position:relative;isolation:isolate;overflow:hidden;border-radius:18px;padding:22px 22px 20px;background:linear-gradient(180deg,#141414 0%,#0f0f0f 100%);color:#eaeaea;border:1px solid rgba(212,175,55,.45);box-shadow:0 14px 30px rgba(0,0,0,.35);transition:transform .35s, box-shadow .35s, border-color .35s, filter .35s}
.fcard:hover{transform:translateY(-6px);box-shadow:0 20px 44px rgba(0,0,0,.45);border-color:rgba(212,175,55,.7);filter:saturate(1.05)}
.fcard::after{content:"";position:absolute;inset:-40%;background:radial-gradient(circle at 75% 30%, rgba(212,175,55,.18), transparent 45%),radial-gradient(circle at 25% 80%, rgba(212,175,55,.10), transparent 45%);pointer-events:none;z-index:0;animation:shineSpin 14s linear infinite;opacity:.6}
@keyframes shineSpin{to{transform:rotate(360deg)}}
.fhead{display:flex;align-items:center;justify-content:space-between;gap:16px;position:relative;z-index:1}
.ftitle{margin:0;font-size:22px;font-weight:900;letter-spacing:.2px;background:linear-gradient(90deg,#b68f2a,#d4af37,#c8a951);-webkit-background-clip:text;background-clip:text;color:transparent}
.ficon{flex:0 0 66px;width:66px;height:66px;border-radius:50%;display:grid;place-items:center;font-size:22px;color:#0f0f0f;background:linear-gradient(145deg,#b68f2a,#d4af37,#c8a951);box-shadow:inset 0 2px 8px rgba(255,255,255,.35),0 10px 24px rgba(0,0,0,.22);border:1px solid rgba(212,175,55,.6);transform:translateZ(0)}
.fdesc{margin:10px 0 12px;color:#cbd5e1;line-height:1.9}
.flist{list-style:none;padding:0;margin:0}
.flist li{position:relative;padding-right:28px;margin:10px 0;color:#e5e7eb}
.flist li::before{content:"\f058";font-family:"Font Awesome 6 Free";font-weight:900;position:absolute;right:0;top:1px;color:#d4af37}
.fcard.reveal{opacity:0;transform:translateY(16px) scale(.98)}
.fcard.reveal.is-visible{opacity:1;transform:translateY(0) scale(1)}
.fcard[data-tilt]{transform-style:preserve-3d;will-change:transform}

/* ===== Products (8) ===== */
.featured-products{padding:60px 0;width:90%;margin:0 auto}
.products-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:24px}
.product-card{position:relative;background:linear-gradient(180deg,#141414 0%,#0f0f0f 100%);border:1px solid rgba(212,175,55,.12);border-radius:14px;overflow:hidden;box-shadow:0 10px 22px rgba(0,0,0,.35);transform:translateZ(0);transition:transform .3s,box-shadow .3s,border-color .3s}
.product-card:hover{transform:translateY(-6px);box-shadow:0 16px 34px rgba(0,0,0,.45);border-color:rgba(212,175,55,.25)}
.product-card .img-wrap{position:relative;height:240px;background:#1b1b1b;overflow:hidden}
.product-card .img-wrap img{width:100%;height:100%;object-fit:cover;transition:transform .6s,filter .6s}
.product-card:hover .img-wrap img{transform:scale(1.06);filter:saturate(1.05)}
.product-badges{position:absolute;top:12px;inset-inline:12px auto;display:flex;gap:8px;z-index:2}
.badge{padding:6px 10px;border-radius:999px;font-size:12px;font-weight:700;color:#0f0f0f;background:linear-gradient(145deg,#b68f2a,#d4af37,#c8a951);box-shadow:inset 0 1px 0 rgba(255,255,255,.25)}
.product-info{padding:16px 16px 14px;display:flex;flex-direction:column;gap:10px}
.product-title{font-size:18px;margin:0;color:#eee}
.product-description{color:#9aa7b1;font-size:14px;line-height:1.75;margin:0}
.product-divider{height:1px;background:linear-gradient(90deg,transparent,rgba(212,175,55,.25),transparent);margin:6px 0 8px}
.product-price-container{display:flex;align-items:center;justify-content:space-between;gap:10px}
.product-price{font-weight:800;font-size:20px;background:linear-gradient(90deg,#b68f2a,#d4af37,#c8a951);-webkit-background-clip:text;background-clip:text;color:transparent}
.btn-gold,.btn-gold:link,.btn-gold:visited{text-decoration:none!important;display:inline-flex;align-items:center;gap:8px;padding:10px 16px;border-radius:10px;font-weight:800;color:#0f0f0f;background:linear-gradient(145deg,#b68f2a,#d4af37,#c8a951);box-shadow:0 10px 22px rgba(212,175,55,.22),inset 0 1px 0 rgba(255,255,255,.25);transition:transform .2s,box-shadow .2s,filter .2s}
.btn-gold:hover{transform:translateY(-2px);filter:saturate(1.05);box-shadow:0 14px 30px rgba(212,175,55,.28),inset 0 1px 0 rgba(255,255,255,.25)}
.btn-gold i{font-size:14px}
.more-products{margin-top:26px;display:flex;justify-content:center}
.more-products .cta-wide,.more-products .cta-wide:link,.more-products .cta-wide:visited{text-decoration:none!important;padding:14px 24px;border-radius:14px;font-weight:900;letter-spacing:.2px;color:#0f0f0f;background:linear-gradient(145deg,#b68f2a,#d4af37,#c8a951) padding-box,linear-gradient(145deg,rgba(212,175,55,.35),rgba(255,255,255,.15)) border-box;border:1px solid transparent;box-shadow:0 16px 34px rgba(212,175,55,.25);display:inline-flex;align-items:center;gap:10px;transition:transform .25s,box-shadow .25s,filter .25s}
.more-products .cta-wide:hover{transform:translateY(-3px);filter:saturate(1.08);box-shadow:0 22px 44px rgba(212,175,55,.32)}
@media(max-width:992px){.products-grid{grid-template-columns:repeat(2,1fr)}}
@media(max-width:576px){.products-grid{grid-template-columns:1fr}}

/* ===== Blog (بطاقتان) ===== */
.home-blog{padding:60px 0;width:90%;margin:0 auto}
.home-blog .grid{display:grid;grid-template-columns:repeat(2,1fr);gap:24px}
.home-blog .card{position:relative;background:linear-gradient(180deg,#141414 0%,#0f0f0f 100%);border:1px solid rgba(212,175,55,.12);border-radius:14px;overflow:hidden;box-shadow:0 10px 22px rgba(0,0,0,.35);transition:transform .3s,box-shadow .3s,border-color .3s}
.home-blog .card:hover{transform:translateY(-6px);border-color:rgba(212,175,55,.25);box-shadow:0 16px 34px rgba(0,0,0,.45)}
.home-blog .thumb{position:relative;height:220px;background:#1b1b1b;overflow:hidden}
.home-blog .thumb img{width:100%;height:100%;object-fit:cover;transition:transform .6s,filter .6s}
.home-blog .card:hover .thumb img{transform:scale(1.06);filter:saturate(1.05)}
.home-blog .body{padding:16px 16px 18px;display:flex;flex-direction:column;gap:8px}
.home-blog h3{font-size:18px;margin:0;color:#eee}
.home-blog p{color:#9aa7b1;font-size:14px;line-height:1.75;margin:0}
.home-blog .meta{font-size:12px;color:#aaa;margin-top:auto}
.home-blog .details-btn,.home-blog .details-btn:link,.home-blog .details-btn:visited{text-decoration:none!important;margin:12px 16px 16px auto;display:inline-flex;align-items:center;gap:8px;padding:9px 14px;border-radius:10px;font-weight:800;color:#0f0f0f;background:linear-gradient(145deg,#b68f2a,#d4af37,#c8a951);box-shadow:0 8px 18px rgba(212,175,55,.2),inset 0 1px 0 rgba(255,255,255,.25);transition:transform .2s,box-shadow .2s,filter .2s}
.home-blog .details-btn:hover{transform:translateY(-2px);filter:saturate(1.05);box-shadow:0 12px 26px rgba(212,175,55,.26),inset 0 1px 0 rgba(255,255,255,.25)}
@media (max-width:576px){.home-blog .grid{grid-template-columns:1fr}}

/* ===== شركاؤنا (سلايدر شعارات) ===== */
.section-wrap{width:90%;margin:0 auto;padding:50px 0}
.section-title{margin:0 0 20px;text-align:center;color:var(--text-color);font-size:28px;position:relative}
.section-title:after{content:'';display:block;width:60px;height:3px;background:var(--primary-color);margin:10px auto;border-radius:10px}
.partners-bar{background:linear-gradient(180deg,#121212 0%, #0f0f0f 100%);border:1px solid rgba(212,175,55,.45);border-radius:16px;padding:18px 14px;box-shadow:0 14px 30px rgba(0,0,0,.35);position:relative;overflow:hidden}
.logo-track{display:flex;align-items:center;gap:36px;min-width:100%;will-change:transform;animation:logos-roll 28s linear infinite}
.logo-track:hover{animation-play-state:paused}
.logo-item{flex:0 0 auto;width:160px;height:86px;border-radius:12px;background:#0f0f0f;border:1px solid rgba(212,175,55,.25);display:grid;place-items:center;padding:10px;transition:.25s;filter:grayscale(20%)}
.logo-item:hover{filter:none;transform:translateY(-4px);box-shadow:0 10px 24px rgba(0,0,0,.35), inset 0 1px 0 rgba(255,255,255,.08)}
.logo-item img{max-width:100%;max-height:100%;object-fit:contain}
@keyframes logos-roll{from{transform:translateX(0)}to{transform:translateX(-50%)}}
.partners-prev,.partners-next{position:absolute;top:50%;transform:translateY(-50%);width:40px;height:40px;border-radius:50%;border:0;cursor:pointer;background:rgba(0,0,0,.45);color:#fff;display:flex;align-items:center;justify-content:center;transition:.2s;z-index:2}
.partners-prev{right:10px}.partners-next{left:10px}
.partners-prev:hover,.partners-next:hover{background:rgba(0,0,0,.65)}

/* ===== تواصل معنا ===== */
.contact-grid{display:grid;grid-template-columns:2fr 1fr;gap:22px}
@media(max-width:900px){.contact-grid{grid-template-columns:1fr}}
.card{background:linear-gradient(180deg,#121212 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)}
.form-row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
@media(max-width:600px){.form-row{grid-template-columns:1fr}}
.field{position:relative}
.field i{position:absolute;right:12px;top:50%;transform:translateY(-50%);color:var(--primary-color);opacity:.9}
.input,.textarea{width:100%;background:#0b0b0b;color:#eaeaea;border:1px solid rgba(212,175,55,.35);border-radius:12px;padding:12px 40px 12px 12px;outline:0;transition:.2s}
.input:focus,.textarea:focus{border-color:var(--primary-color);box-shadow:0 0 0 3px rgba(212,175,55,.15)}
.textarea{min-height:130px;resize:vertical}
.btn-gold, .btn-gold:link, .btn-gold:visited{text-decoration:none!important;display:inline-flex;align-items:center;gap:8px;padding:12px 18px;border-radius:12px;font-weight:800;color:#0f0f0f;cursor:pointer;background:linear-gradient(145deg,var(--gold-2),var(--gold-3),var(--gold-4));box-shadow:0 12px 28px rgba(212,175,55,.25),inset 0 1px 0 rgba(255,255,255,.25);border:0;transition:transform .2s,box-shadow .2s,filter .2s}
.btn-gold:hover{transform:translateY(-2px);filter:saturate(1.05);box-shadow:0 16px 36px rgba(212,175,55,.32),inset 0 1px 0 rgba(255,255,255,.25)}
.info-list{list-style:none;padding:0;margin:0;display:flex;flex-direction:column;gap:12px}
.info-item{display:flex;align-items:center;gap:12px;color:#eaeaea}
.info-item .ico{width:40px;height:40px;border-radius:10px;display:grid;place-items:center;background:linear-gradient(145deg,var(--gold-2),var(--gold-3));color:#0f0f0f;box-shadow:inset 0 1px 0 rgba(255,255,255,.3)}
.info-actions{display:flex;gap:10px;margin-top:14px;flex-wrap:wrap}
.info-actions a{text-decoration:none!important}
.alert{border-radius:10px;padding:10px 12px;margin-bottom:12px;font-weight:600}
.alert-ok{background:#112d1a;border:1px solid #1f7a33;color:#b8f7c8}
.alert-err{background:#3f1d1d;border:1px solid #7f1d1d;color:#fee2e2}

/* تشغيل وضع عرض كامل للصورة */
.hero-slider[data-fit="contain"]{
  /* استخدم نسبة الأبعاد بدل ارتفاع ثابت */
  aspect-ratio: 1988 / 768;             /* نفس قيمة data-ar لأغلب المتصفحات */
  height: auto;                         /* الارتفاع يعتمد على العرض */
  max-height: 86vh;                     /* لا تتجاوز ارتفاع الشاشة */
  min-height: 260px;                    /* حد أدنى للجوال */
}

/* تعطيل ارتفاعات قديمة إن وُجدت (بما فيها .hero-slider--mini) */
.hero-slider[data-fit="contain"], 
.hero-slider[data-fit="contain"].hero-slider--mini{
  height: auto !important;
}

/* اجعل الخلفية "contain" كي لا تُقص الصورة */
.hero-slider[data-fit="contain"] .hero-slide{
  background-size: contain;             /* كان cover */
  background-repeat: no-repeat;
  background-position: center center;
  background-color: #000;               /* الشريطين العلوي/السفلي إن لزم */
}

/* طبقة التعتيم تبقى لكن بدون نصوص يمكن إخفاء المحتوى لو أردت */
.hero-slider[data-fit="contain"] .hero-overlay{
  background: linear-gradient(to bottom, rgba(0,0,0,.35), rgba(0,0,0,.35));
}

/* تحسينات صغيرة للجوال */
@media (max-width: 700px){
  .hero-slider[data-fit="contain"]{ max-height: 70vh; min-height: 220px; }
}


</style>

<!-- ============ السلايدر العلوي ============ -->
<section class="hero-slider" dir="rtl">
  <div class="hero-track" id="heroTrack">
    <?php foreach ($slides as $i => $s): $img = fix_image_url($s['image'] ?? ''); ?>
      <article class="hero-slide<?= $i===0?' is-active':'' ?>" style="--bg:url('<?= htmlspecialchars($img) ?>')">
        <div class="hero-overlay"></div>
        <div class="hero-content">
          <h1 class="hero-title"><?= htmlspecialchars($s['title'] ?? '') ?></h1>
          <?php if (!empty($s['subtitle'])): ?><p class="hero-subtitle"><?= htmlspecialchars($s['subtitle']) ?></p><?php endif; ?>
          <?php if (!empty($s['button_text']) && !empty($s['link'])): ?>
            <a class="hero-btn" href="<?= htmlspecialchars($s['link']) ?>"><?= htmlspecialchars($s['button_text']) ?></a>
          <?php endif; ?>
        </div>
      </article>
    <?php endforeach; ?>
  </div>
  <button class="hero-arrow hero-prev" id="heroPrev"><i class="fas fa-chevron-right"></i></button>
  <button class="hero-arrow hero-next" id="heroNext"><i class="fas fa-chevron-left"></i></button>
  <div class="hero-dots" id="heroDots">
    <?php foreach ($slides as $i => $_): ?><button class="hero-dot<?= $i===0?' active':'' ?>" data-idx="<?= $i ?>"></button><?php endforeach; ?>
  </div>
</section>

<!-- ============ من نحن ============ -->
<section class="about-section">
  <div class="about-wrap">
    <article class="about-card reveal">
      <div class="about-icon"><i class="fas fa-gem" aria-hidden="true"></i></div>
      <div class="about-content">
        <h2 class="about-title">من نحن</h2>
        <p class="about-text">
          <?= nl2br(htmlspecialchars($intro['body'] ?? '')) ?>
        </p>
        <a href="about.php" class="about-btn">اقرأ قصتنا</a>
      </div>
      <span class="about-border"></span>
    </article>
  </div>
</section>


<!-- ============ المنتجات (8) ============ -->
<section class="featured-products">
  <h2 class="section-title">منتجاتنا</h2>
  <?php $homeProducts = array_slice($products, 0, 8); ?>
  <div class="products-grid">
    <?php foreach ($homeProducts as $p): ?>
      <?php
        $isGold = (isset($p['karat']) && in_array($p['karat'], [24,21,18]));
        $key    = $isGold ? ("gold_".$p['karat']) : "silver";
        $unit   = (isset($prices[$key]) && is_numeric($prices[$key])) ? (float)$prices[$key] : 0.0;
        $wt     = (isset($p['weight']) && is_numeric($p['weight']))   ? (float)$p['weight']   : 0.0;
        $price  = $unit * $wt;

        // وصف منسّق + بديل نصي (محضّرَين مسبقًا في ملف الجلب)
        $desc_html  = !empty($p['_desc_html'])  ? $p['_desc_html']  : 'لا يوجد وصف متاح';
        $desc_plain = !empty($p['_desc_plain']) ? $p['_desc_plain'] : strip_tags($desc_html);

        $karat  = $isGold ? ($p['karat']." عيار") : "فضة";
        $wtxt   = $wt ? number_format($wt,2)." جم" : "";
      ?>
      <article class="product-card">
        <div class="img-wrap">
          <div class="product-badges">
            <span class="badge"><?= htmlspecialchars($karat) ?></span>
            <?php if ($wt): ?><span class="badge"><?= htmlspecialchars($wtxt) ?></span><?php endif; ?>
          </div>
          <img src="<?= htmlspecialchars(product_img($p['image'] ?? '')) ?>" alt="<?= htmlspecialchars($p['name'] ?? '') ?>">
        </div>
        <div class="product-info">
          <h3 class="product-title"><?= htmlspecialchars($p['name'] ?? '') ?></h3>

          <!-- وصف منسّق (بدون htmlspecialchars) + title نصي مختصر -->
          <div class="product-description product-description--html" title="<?= htmlspecialchars($desc_plain) ?>">
            <?= $desc_html ?>
          </div>

          <div class="product-divider"></div>
          <div class="product-price-container">
            <span class="product-price"><?= number_format($price,2) ?> ر.س</span>
            <a href="product.php?id=<?= (int)($p['id'] ?? 0) ?>" class="btn-gold">التفاصيل <i class="fas fa-arrow-left"></i></a>
          </div>
        </div>
      </article>
    <?php endforeach; ?>
  </div>
  <div class="more-products">
    <a class="cta-wide" href="gold.php">المزيد من المنتجات <i class="fas fa-layer-group"></i></a>
  </div>
</section>

<!-- ============ السلايدر السفلي (بدون عبارات) ============ -->
<<section class="hero-slider hero-slider--mini" dir="rtl" data-fit="contain" data-ar="1988/768" aria-label="سلايدر سفلي">

  <div class="hero-track" id="heroTrack2">
    <?php foreach ($bottomSlides as $i => $s): $img = fix_image_url($s['image'] ?? ''); $lnk = trim($s['link'] ?? ''); ?>
      <?php if ($lnk !== ''): ?>
        <a href="<?= htmlspecialchars($lnk) ?>" class="hero-slide<?= $i===0?' is-active':'' ?>" style="--bg:url('<?= htmlspecialchars($img) ?>')" title="">
          <span class="hero-overlay"></span>
          <span class="hero-content" aria-hidden="true"></span>
        </a>
      <?php else: ?>
        <article class="hero-slide<?= $i===0?' is-active':'' ?>" style="--bg:url('<?= htmlspecialchars($img) ?>')">
          <div class="hero-overlay"></div>
        </article>
      <?php endif; ?>
    <?php endforeach; ?>
  </div>
  <button class="hero-arrow hero-prev" id="heroPrev2" aria-label="السابق"><i class="fas fa-chevron-right"></i></button>
  <button class="hero-arrow hero-next" id="heroNext2" aria-label="التالي"><i class="fas fa-chevron-left"></i></button>
  <div class="hero-dots" id="heroDots2">
    <?php foreach ($bottomSlides as $i => $_): ?><button class="hero-dot<?= $i===0?' active':'' ?>" data-idx="<?= $i ?>"></button><?php endforeach; ?>
  </div>
</section>

<!-- ============ ما يميزنا (ديناميكي) ============ -->
<section class="features-dark" dir="rtl">
  <h2 class="section-title">ما يميزنا</h2>
  <div class="features-grid">
    <?php foreach($features as $f): ?>
      <article class="fcard reveal" data-tilt>
        <div class="fhead">
          <h3 class="ftitle"><?= htmlspecialchars($f['title']) ?></h3>
          <div class="ficon"><i class="fas <?= htmlspecialchars($f['icon']) ?>"></i></div>
        </div>
        <?php if (!empty($f['description'])): ?>
          <p class="fdesc"><?= nl2br(htmlspecialchars($f['description'])) ?></p>
        <?php endif; ?>
        <?php
          $items = array_filter(array_map('trim', explode("\n", (string)$f['items'])));
          if ($items):
        ?>
          <ul class="flist">
            <?php foreach($items as $it): ?><li><?= htmlspecialchars($it) ?></li><?php endforeach; ?>
          </ul>
        <?php endif; ?>
      </article>
    <?php endforeach; ?>
    <?php if(!$features): ?>
      <div style="grid-column:1/-1;color:#aaa;text-align:center">لم تتم إضافة بطاقات بعد.</div>
    <?php endif; ?>
  </div>
</section>

<!-- ============ المدونة (آخر 4) ============ -->
<section class="home-blog">
  <h2 class="section-title">المدونة</h2>
  <div class="grid">
    <?php foreach ($blog4 as $b): $img = fix_image_url($b['image'] ?? ''); ?>
      <article class="card">
        <div class="thumb"><img src="<?= htmlspecialchars($img) ?>" alt="<?= htmlspecialchars($b['title']) ?>"></div>
        <div class="body">
          <h3><?= htmlspecialchars($b['title']) ?></h3>
          <p><?= htmlspecialchars(mb_strimwidth((string)$b['summary'],0,120,'...','UTF-8')) ?></p>
          <div class="meta"><i class="far fa-calendar"></i> <?= date('Y-m-d', strtotime($b['created_at'])) ?></div>
        </div>
        <a class="details-btn" href="blog_view.php?id=<?= (int)$b['id'] ?>">اقرأ المزيد <i class="fas fa-arrow-left"></i></a>
      </article>
    <?php endforeach; ?>
    <?php if(!$blog4): ?>
      <div style="grid-column:1/-1;color:#aaa;text-align:center">لا توجد مقالات منشورة حالياً.</div>
    <?php endif; ?>
  </div>
  <div class="more-wrap" style="text-align:center;margin-top:22px">
    <a class="btn-more" href="blog.php" style="text-decoration:none;border:1px solid rgba(212,175,55,.5);color:var(--primary-color);padding:10px 18px;border-radius:10px;display:inline-block">المزيد من المقالات</a>
  </div>
</section>

<!-- ============ شركاؤنا ============ -->
<section class="section-wrap" dir="rtl">
  <h2 class="section-title">شركاؤنا</h2>
  <div class="partners-bar" id="partnersBar">
    <button class="partners-prev" id="partnersPrev" aria-label="السابق"><i class="fas fa-chevron-right"></i></button>
    <button class="partners-next" id="partnersNext" aria-label="التالي"><i class="fas fa-chevron-left"></i></button>
    <?php $logos2 = array_merge($partners,$partners); ?>
    <div class="logo-track" id="logoTrack">
      <?php foreach ($logos2 as $it): $src = fix_logo($it['logo'] ?? ''); $name = htmlspecialchars($it['name'] ?? ''); $url = trim($it['url'] ?? ''); ?>
        <?php if ($url !== ''): ?>
          <a class="logo-item" href="<?= htmlspecialchars($url) ?>" target="_blank" rel="noopener" title="<?= $name ?>">
            <img src="<?= htmlspecialchars($src) ?>" alt="<?= $name ?>">
          </a>
        <?php else: ?>
          <div class="logo-item" title="<?= $name ?>">
            <img src="<?= htmlspecialchars($src) ?>" alt="<?= $name ?>">
          </div>
        <?php endif; ?>
      <?php endforeach; ?>
    </div>
  </div>
</section>

<!-- ============ تواصل معنا ============ -->
<section class="section-wrap" dir="rtl">
  <h2 class="section-title">تواصل معنا</h2>
  <div class="contact-grid">
    <div class="card">
      <?php if ($contact_ok): ?><div class="alert alert-ok">شكرًا لك! تم استلام رسالتك.</div><?php endif; ?>
      <?php if ($contact_err): ?><div class="alert alert-err"><?= htmlspecialchars($contact_err) ?></div><?php endif; ?>
      <form method="post" novalidate>
        <input type="hidden" name="__contact_token" value="<?= bin2hex(random_bytes(6)) ?>">
        <div class="form-row">
          <div class="field"><i class="fas fa-user"></i><input class="input" type="text" name="name" placeholder="الاسم*" required></div>
          <div class="field"><i class="fas fa-envelope"></i><input class="input" type="email" name="email" placeholder="البريد الإلكتروني"></div>
        </div>
        <div class="form-row" style="margin-top:12px">
          <div class="field"><i class="fas fa-phone"></i><input class="input" type="text" name="phone" placeholder="رقم الجوال"></div>
          <div class="field"><i class="fas fa-tag"></i><input class="input" type="text" name="subject" placeholder="الموضوع"></div>
        </div>
        <div class="field" style="margin-top:12px">
          <i class="fas fa-comment-dots" style="top:18px"></i>
          <textarea class="textarea" name="message" placeholder="اكتب رسالتك هنا*" required></textarea>
        </div>
        <div style="margin-top:14px; display:flex; gap:10px; align-items:center">
          <button class="btn-gold" type="submit"><i class="fas fa-paper-plane"></i> إرسال الرسالة</button>
          <small style="color:#9aa7b1">* الحقول الإلزامية</small>
        </div>
      </form>
    </div>
    <aside class="card">
      <h3 style="margin:0 0 12px; color:var(--primary-color); font-size:20px">بيانات التواصل</h3>
      <ul class="info-list">
        <li class="info-item"><span class="ico"><i class="fas fa-phone"></i></span> <a href="tel:+966500000000" style="color:#eaeaea; text-decoration:none">+966 50 000 0000</a></li>
        <li class="info-item"><span class="ico"><i class="fab fa-whatsapp"></i></span> <a href="https://wa.me/966500000000" target="_blank" style="color:#eaeaea; text-decoration:none">واتساب مباشر</a></li>
        <li class="info-item"><span class="ico"><i class="fas fa-envelope"></i></span> <a href="mailto:info@example.com" style="color:#eaeaea; text-decoration:none">info@example.com</a></li>
        <li class="info-item"><span class="ico"><i class="fas fa-location-dot"></i></span> جدة ـ المملكة العربية السعودية</li>
        <li class="info-item"><span class="ico"><i class="fas fa-clock"></i></span> 9 صباحًا – 10 مساءً (يوميًا)</li>
      </ul>
      <div class="info-actions">
        <a class="btn-gold" href="https://maps.google.com/?q=Jeddah" target="_blank"><i class="fas fa-map-location-dot"></i> فتح الخريطة</a>
        <a class="btn-gold" href="contact.php"><i class="fas fa-envelope-open-text"></i> صفحة التواصل</a>
      </div>
    </aside>
  </div>
</section>

<script>
/* دالة عامة لتشغيل أي سلايدر */
function initHeroSlider({trackId,prevId,nextId,dotsId,auto=6000}) {
  const root   = document.getElementById(trackId);
  if(!root) return;
  const slides = [...root.querySelectorAll('.hero-slide')];
  const dots   = dotsId ? [...document.getElementById(dotsId).querySelectorAll('.hero-dot')] : [];
  const prev   = prevId ? document.getElementById(prevId) : null;
  const next   = nextId ? document.getElementById(nextId) : null;
  let idx=0,timer=null;

  function show(i){
    idx=(i+slides.length)%slides.length;
    slides.forEach((s,k)=>s.classList.toggle('is-active',k===idx));
    if(dots.length) dots.forEach((d,k)=>d.classList.toggle('active',k===idx));
  }
  function autoplay(){ clearInterval(timer); if(auto>0) timer=setInterval(()=>show(idx+1),auto); }

  prev && prev.addEventListener('click',()=>{show(idx-1);autoplay();});
  next && next.addEventListener('click',()=>{show(idx+1);autoplay();});
  dots.forEach(d=>d.addEventListener('click',e=>{show(+e.currentTarget.dataset.idx);autoplay();}));

  let startX=null;
  root.addEventListener('mouseenter',()=>clearInterval(timer));
  root.addEventListener('mouseleave',autoplay);
  root.addEventListener('touchstart',e=>{startX=e.touches[0].clientX},{passive:true});
  root.addEventListener('touchend',e=>{
    if(startX===null) return;
    const dx=e.changedTouches[0].clientX-startX;
    if(Math.abs(dx)>40){ dx>0?show(idx-1):show(idx+1); autoplay(); }
    startX=null;
  });

  autoplay();
}

/* السلايدر العلوي */
initHeroSlider({trackId:'heroTrack', prevId:'heroPrev', nextId:'heroNext', dotsId:'heroDots', auto:6000});

/* ظهور عند التمرير (.reveal) */
(function(){
  const els=document.querySelectorAll('.reveal,.fcard.reveal');
  if(!('IntersectionObserver'in window)||!els.length){ els.forEach(el=>el.classList.add('is-visible')); return; }
  const io=new IntersectionObserver((entries)=>{
    entries.forEach(e=>{ if(e.isIntersecting){ e.target.classList.add('is-visible'); io.unobserve(e.target);} });
  },{threshold:0.18});
  els.forEach(el=>io.observe(el));
})();

/* Tilt بسيط لبطاقات "ما يميزنا" */
(function(){
  const cards=document.querySelectorAll('.fcard[data-tilt]');
  cards.forEach(card=>{
    let rect; const maxTilt=6;
    card.addEventListener('mouseenter',()=>{rect=card.getBoundingClientRect()},{passive:true});
    card.addEventListener('mousemove',e=>{
      if(!rect) rect=card.getBoundingClientRect();
      const x=(e.clientX-rect.left)/rect.width, y=(e.clientY-rect.top)/rect.height;
      const rx=(0.5-y)*maxTilt, ry=(x-0.5)*maxTilt;
      card.style.transform=`translateY(-6px) rotateX(${rx}deg) rotateY(${ry}deg)`;
    });
    card.addEventListener('mouseleave',()=>{card.style.transform='';});
  });
})();

/* أسهم سلايدر الشركاء — إزاحة يدوية قصيرة ثم استئناف الحركة */
(function(){
  const track = document.getElementById('logoTrack');
  const prev  = document.getElementById('partnersPrev');
  const next  = document.getElementById('partnersNext');
  let offset = 0;
  function nudge(dir){
    offset += dir * 220;
    track.style.transition = 'transform .35s ease';
    track.style.transform  = `translateX(${offset}px)`;
    clearTimeout(track._reset);
    track._reset = setTimeout(()=>{
      track.style.transition = '';
      track.style.transform  = '';
      offset = 0;
    }, 800);
  }
  prev && prev.addEventListener('click', ()=> nudge(+1));
  next && next.addEventListener('click', ()=> nudge(-1));
})();

/* السلايدر السفلي */
initHeroSlider({trackId:'heroTrack2', prevId:'heroPrev2', nextId:'heroNext2', dotsId:'heroDots2', auto:5000});
</script>

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