<?php
require_once "config/db.php";
include "includes/header.php";

/* ====== جلب البيانات ====== */

// التصنيفات والمدن لنموذج البحث
$categories = $pdo->query("SELECT id, name FROM categories ORDER BY name ASC")->fetchAll();
$cities     = $pdo->query("SELECT id, name FROM cities ORDER BY name ASC")->fetchAll();

// شركات نشطة (مميزة/أحدث)
$companies = $pdo->query("
    SELECT c.*, cat.name AS category_name, city.name AS city_name
    FROM companies c
    LEFT JOIN categories cat ON c.category_id = cat.id
    LEFT JOIN cities city ON c.city_id = city.id
    WHERE c.status = 'active'
    ORDER BY c.id DESC
")->fetchAll();

// سلايدر علوي/سفلي (مع صلاحية تاريخ الانتهاء)
$sliders_top = $pdo->query("
    SELECT * FROM sliders
    WHERE active = 1 AND type = 'top' AND expire_date >= CURDATE()
    ORDER BY id DESC
")->fetchAll();

$sliders_bottom = $pdo->query("
    SELECT * FROM sliders
    WHERE active = 1 AND type = 'bottom' AND expire_date >= CURDATE()
    ORDER BY id DESC
")->fetchAll();

// أحدث العروض
$stmt = $pdo->prepare("
    SELECT o.*, c.name AS company_name, c.logo AS company_logo, c.phone, c.whatsapp
    FROM offers o
    JOIN companies c ON o.company_id = c.id
    WHERE o.status = 'موافق'
    ORDER BY o.id DESC
    LIMIT 8
");
$stmt->execute();
$offers = $stmt->fetchAll();

// شركاء النجاح
$partners = $pdo->query("SELECT * FROM partners WHERE status='active' ORDER BY id DESC")->fetchAll();

/* ====== دوال مساعدة ====== */
function formatWhatsapp($number) {
    $number = preg_replace('/\D+/', '', (string)$number);
    if ($number === '') return '';
    // 05XXXXXXXX -> 9665XXXXXXXX
    if (strpos($number, '05') === 0) return '966' . substr($number, 1);
    if (strpos($number, '5') === 0)  return '966' . $number;
    if (strpos($number, '966') === 0) return $number;
    return '966' . ltrim($number, '0');
}
function slider_img_path($img) {
    $img = trim((string)$img);
    if ($img === '') return '';
    return (strpos($img, 'uploads/sliders/') === 0) ? $img : 'uploads/sliders/' . $img;
}
?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.4.2/css/all.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css"/>

<style>
/* ====== تنسيقات عامة ====== */
body { font-family: 'Tajawal','Cairo',Arial,sans-serif; background:#f8f9fb; margin:0; }

/* تبويبات البحث */
.search-tabs{ display:flex; gap:10px; justify-content:center; margin:20px auto 10px; }
.search-tabs button{
  background:#6d2490; color:#fff; border:0; padding:10px 16px; border-radius:10px; cursor:pointer; font-weight:700;
}
.search-tabs button.active{ background:#43126d; }

/* نماذج البحث */
.search-form{ display:flex; gap:12px; flex-wrap:wrap; justify-content:center; margin:10px auto 24px; max-width:1000px; }
.search-form .form-group{ display:flex; flex-direction:column; min-width:220px; }
.search-form label{ color:#333; font-weight:600; margin-bottom:6px; }
.search-form select, .search-form input{
  height:42px; padding:0 10px; border-radius:10px; border:1px solid #e5e5ef; background:#fff;
}
.search-btn{
  background:#1976d2; color:#fff; border:0; padding:0 18px; border-radius:10px; font-weight:700; height:42px;
}

/* ====== السلايدر (علوي/سفلي) ====== */
.main-slider, .bottom-slider{ margin:24px auto 36px; max-width:1000px; border-radius:15px; overflow:hidden; position:relative; }
.slider-item{ position:relative; }
.slider-item img{ width:100%; height:270px; object-fit:cover; display:block; }
.slide-link{ display:block; width:100%; height:100%; position:relative; z-index:1; }
.slider-caption{
  position:absolute; left:0; right:0; bottom:0;
  background:rgba(0,0,0,.45); color:#fff; padding:8px 14px; font-size:15px; border-bottom-left-radius:15px; border-bottom-right-radius:15px;
}
.slick-prev, .slick-next{
  background:#fff; border:none; width:38px; height:38px; border-radius:50%;
  box-shadow:0 2px 6px #0001; top:45%; z-index:3;
}
.slick-prev{ right:10px; }
.slick-next{ left:10px; }
.slick-dots li button:before{ color:#6616d0 !important; font-size:14px; }
@media (max-width: 991px){ .slider-item img{ height:220px; } }

/* ====== بطاقات الشركات ====== */
.page-header{ text-align:center; margin:10px auto 10px; }
.page-header h1{ font-size:28px; color:#6d2490; margin:0 0 6px; }
.page-header p{ color:#777; margin:0; }
.featured-companies{
  display:grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap:16px; max-width:1100px; margin:16px auto 10px; padding:0 10px;
}
@media (max-width:991px){ .featured-companies{ grid-template-columns: repeat(2, 1fr);} }
@media (max-width:580px){ .featured-companies{ grid-template-columns: 1fr; } }

.company-card2 {
  background:#fff; border-radius:18px; box-shadow:0 2px 14px #0001; padding:0 0 18px; overflow:hidden;
  display:flex; flex-direction:column; transition: box-shadow .2s;
}
.company-card2:hover{ box-shadow:0 6px 28px #0002; }
.cover-image{ width:100%; height:145px; background-size:cover; background-position:center; position:relative; }
.status-badge{
  position:absolute; top:13px; left:15px; background:#ece8fd; color:#6d2490; font-size:15px; font-weight:600;
  border-radius:18px; padding:4px 18px; box-shadow:0 2px 8px #0001;
}
.company-header{ display:flex; align-items:center; gap:12px; padding:0 18px; margin-top:-32px; position:relative; z-index:1; }
.logo-wrap{ width:62px; height:62px; border-radius:50%; overflow:hidden; border:2.5px solid #fff; background:#fff; box-shadow:0 2px 8px #0001; display:flex; align-items:center; justify-content:center; }
.logo-wrap img{ width:54px; height:54px; object-fit:contain; background:#f5f5fa; border-radius:50%; }
.company-name-badge{
  background:#fff; color:#6d2490; font-size:18px; font-weight:bold; border-radius:15px; padding:6px 20px 5px; box-shadow:0 1px 6px #0001; border:1.5px solid #eaeaea; margin-bottom:4px; display:inline-block;
}
.company-header .meta{ color:#888; font-size:14px; margin-bottom:2px; }
.description{ color:#454545; font-size:16px; margin:14px 18px 8px; min-height:40px; }
.actions{ display:flex; gap:12px; margin:12px 18px 0; }
.btn-details{ background:#6d2490; color:#fff; padding:7px 19px; border-radius:9px; font-size:15px; text-decoration:none; font-weight:600; transition:.18s; }
.btn-details:hover{ background:#43126d; }
.btn-contact{ background:#4eac5d; color:#fff; padding:7px 19px; border-radius:9px; font-size:15px; text-decoration:none; font-weight:600; transition:.18s; }
.btn-contact:hover{ background:#338b40; }

.more-container{ text-align:center; margin:10px 0 30px; }
.btn-more{ background:#1976d2; color:#fff; padding:10px 18px; border-radius:10px; text-decoration:none; font-weight:700; }

/* ====== أحدث العروض ====== */
.section-title{ font-size:30px; font-weight:bold; color:#1976d2; margin:40px auto 28px; display:flex; align-items:center; gap:10px; direction:rtl; justify-content:flex-end; max-width:1100px; padding:0 10px; }
.section-title i{ color:#ffb300; font-size:27px; margin-right:8px; }
.offers-slider{ width:95%; margin:0 auto 55px; }
.offer-card.offer-style2{
  background:#fff; border-radius:25px; box-shadow:0 8px 28px #e1e1e1a8; margin:18px 12px; max-width:345px; min-width:250px; padding:0; display:flex; flex-direction:column; align-items:stretch; text-align:center; transition:.18s; overflow:hidden;
}
.offer-card.offer-style2:hover{ box-shadow:0 12px 38px #cec4eb38; }
.offer-img2{ width:100%; height:190px; background:#f5f5fa; display:flex; align-items:center; justify-content:center; overflow:hidden; }
.offer-img2 img{ width:100%; height:100%; object-fit:cover; display:block; border-radius:0; }
.offer-body{ padding:22px 18px 15px; display:flex; flex-direction:column; align-items:center; }
.offer-title{ font-size:20px; font-weight:bold; color:#222; margin-bottom:8px; }
.offer-desc{ color:#888; font-size:15.5px; min-height:35px; margin:0 0 10px; }
.offer-prices{ margin-bottom:8px; font-size:16.5px; display:flex; align-items:center; justify-content:center; gap:10px; }
.old-price{ color:#b7b7b7; text-decoration:line-through; font-size:16px; }
.new-price{ color:#18a300; font-weight:bold; font-size:19px; }
.currency{ font-size:16px; color:#1a1a1a; font-weight:bold; margin-right:3px; }
.offer-expire{ color:#666; font-size:15px; margin-bottom:10px; display:flex; align-items:center; gap:5px; justify-content:center; }
.offer-actions{ display:flex; gap:14px; justify-content:center; margin-top:8px; }
.btn-icon{ display:flex; align-items:center; justify-content:center; width:41px; height:41px; background:#f3f3f7; border-radius:10px; font-size:21px; color:#fff; border:none; transition:.16s; text-decoration:none !important; }
.btn-icon.whatsapp{ background:#25d366; }
.btn-icon.phone{ background:#7c3aed; }
.btn-icon.page{ background:#ffc107; color:#fff; }
.btn-icon:hover{ opacity:.87; box-shadow:0 4px 18px #0001; }
@media (max-width:991px){
  .offer-card.offer-style2{ max-width:99vw; min-width:180px; }
  .offer-img2{ height:130px; }
}

/* ====== شركاء النجاح ====== */
.featured-slider{ max-width:1100px; margin:60px auto; padding:0 10px; }
.slider-header{ display:flex; align-items:center; justify-content:space-between; margin-bottom:12px; }
.slider-header h2{ margin:0; color:#6d2490; }
.companies-slider .slide-item{ padding:10px; }
.companies-slider .slide-img{
  height:110px; display:flex; align-items:center; justify-content:center; background:#fff; border-radius:14px; box-shadow:0 2px 12px #0000000a;
}
.companies-slider img{ height:80px; max-width:140px; object-fit:contain; }
</style>

<div class="search-tabs">
  <button type="button" class="active" id="tab-companies">بحث عن شركات</button>
  <button type="button" id="tab-offers">بحث عن عروض</button>
</div>

<!-- نموذج بحث الشركات -->
<form class="search-form" id="form-companies" method="get" action="companies.php" style="display:flex;">
  <div class="form-group">
    <label><i class="fas fa-list"></i> اختر التصنيف</label>
    <select name="category_id">
      <option value="">جميع التصنيفات</option>
      <?php foreach ($categories as $cat): ?>
        <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
      <?php endforeach; ?>
    </select>
  </div>
  <div class="form-group">
    <label><i class="fas fa-map-marker-alt"></i> اختر المدينة</label>
    <select name="city_id">
      <option value="">جميع المدن</option>
      <?php foreach ($cities as $city): ?>
        <option value="<?= $city['id'] ?>"><?= htmlspecialchars($city['name']) ?></option>
      <?php endforeach; ?>
    </select>
  </div>
  <div class="form-group">
    <label><i class="fas fa-search"></i> كلمة البحث</label>
    <input type="text" name="q" placeholder="ابحث بالاسم أو النشاط...">
  </div>
  <button class="search-btn" type="submit"><i class="fas fa-search"></i> بحث</button>
</form>

<!-- نموذج بحث العروض -->
<form class="search-form" id="form-offers" method="get" action="offers.php" style="display:none;">
  <div class="form-group">
    <label><i class="fas fa-list"></i> اختر تصنيف العرض</label>
    <select name="category_id">
      <option value="">جميع التصنيفات</option>
      <?php foreach ($categories as $cat): ?>
        <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
      <?php endforeach; ?>
    </select>
  </div>
  <div class="form-group">
    <label><i class="fas fa-search"></i> كلمة البحث</label>
    <input type="text" name="q" placeholder="ابحث بعنوان أو وصف العرض...">
  </div>
  <button class="search-btn" type="submit"><i class="fas fa-search"></i> بحث</button>
</form>

<!-- ===== السلايدر العلوي ===== -->
<div class="main-slider">
  <?php if ($sliders_top): foreach ($sliders_top as $s):
    $img = slider_img_path($s['image'] ?? '');
    $url = trim($s['link'] ?? '');
    $title = htmlspecialchars($s['title'] ?? '');
    $is_ext = preg_match('~^https?://~i', $url);
  ?>
    <div class="slider-item">
      <?php if ($url): ?>
        <a class="slide-link" href="<?= htmlspecialchars($url) ?>" <?= $is_ext ? 'target="_blank" rel="noopener"' : '' ?>>
          <img src="<?= htmlspecialchars($img) ?>" alt="<?= $title ?>">
          <?php if ($title): ?><div class="slider-caption"><?= $title ?></div><?php endif; ?>
        </a>
      <?php else: ?>
        <img src="<?= htmlspecialchars($img) ?>" alt="<?= $title ?>">
        <?php if ($title): ?><div class="slider-caption"><?= $title ?></div><?php endif; ?>
      <?php endif; ?>
    </div>
  <?php endforeach; else: ?>
    <div style="text-align:center;color:#aaa;padding:24px;">لا توجد شرائح حالياً.</div>
  <?php endif; ?>
</div>

<!-- ===== شركات مميزة ===== -->
<div class="page-header">
  <h1><i class="fas fa-star"></i> شركات مميزة</h1>
  <p>أفضل الشركات المسجلة في دليلنا حسب التقييمات والخدمات</p>
</div>

<div class="featured-companies">
<?php if (!$companies): ?>
  <div style="text-align:center;color:#aaa;padding:30px 0;">لا يوجد شركات مميزة حتى الآن.</div>
<?php else: foreach ($companies as $company): ?>
  <div class="company-card2">
    <div class="cover-image" style="background-image:url('<?= !empty($company['cover']) ? htmlspecialchars($company['cover']) : 'images/cover-default.png' ?>')">
      <div class="status-badge">نشط</div>
    </div>

    <div class="company-header">
      <div class="logo-wrap">
        <img src="<?= !empty($company['logo']) ? htmlspecialchars($company['logo']) : 'images/company-default.png' ?>" alt="شعار الشركة">
      </div>
      <div>
        <div class="company-name-badge"><?= htmlspecialchars($company['name']) ?></div>
        <div class="meta">
          <span><i class="fas fa-tag"></i> <?= htmlspecialchars($company['category_name']) ?></span>
          <span><i class="fas fa-map-marker-alt"></i> <?= htmlspecialchars($company['city_name']) ?></span>
        </div>
      </div>
    </div>

    <?php
      $about = $company['about'] ?? '';
      $desc = mb_substr($about, 0, 72, 'UTF-8') . (mb_strlen($about, 'UTF-8') > 72 ? '...' : '');
    ?>
    <p class="description"><?= htmlspecialchars($desc) ?></p>
    <div class="actions">
      <a href="company.php?id=<?= $company['id'] ?>" class="btn-details"><i class="fas fa-eye"></i> التفاصيل</a>
      <?php if (!empty($company['phone'])): ?>
        <a href="tel:<?= htmlspecialchars($company['phone']) ?>" class="btn-contact"><i class="fas fa-phone-alt"></i> اتصل</a>
      <?php endif; ?>
    </div>
  </div>
<?php endforeach; endif; ?>
</div>

<div class="more-container">
  <a href="companies.php" class="btn-more">عرض المزيد من الشركات <i class="fas fa-arrow-left"></i></a>
</div>

<!-- ===== أحدث العروض ===== -->
<div class="section-title">
  <span>أحدث العروض</span>
  <i class="fas fa-handshake"></i>
</div>

<div class="offers-slider">
  <?php foreach ($offers as $offer): ?>
  <div class="offer-card offer-style2">
    <div class="offer-img2">
      <img src="<?= htmlspecialchars($offer['image'] ?? 'assets/images/offer-default.png') ?>" alt="صورة العرض">
    </div>
    <div class="offer-body">
      <div class="offer-title"><?= htmlspecialchars($offer['title'] ?? '') ?></div>
      <div class="offer-desc"><?= htmlspecialchars(mb_substr($offer['description'] ?? '', 0, 60, 'UTF-8')) ?>...</div>
      <div class="offer-prices">
        <?php if(!empty($offer['old_price'])): ?><span class="old-price"><?= number_format($offer['old_price']) ?></span><?php endif; ?>
        <span class="new-price"><?= number_format($offer['new_price'] ?? 0) ?></span>
        <span class="currency">ريال</span>
      </div>
      <div class="offer-expire"><i class="fas fa-calendar-alt"></i> <?= htmlspecialchars($offer['end_date'] ?? $offer['expire_date'] ?? '') ?></div>
      <div class="offer-actions">
        <a href="company.php?id=<?= $offer['company_id'] ?>" class="btn-icon page" title="صفحة الشركة"><i class="fas fa-home"></i></a>
        <?php if(!empty($offer['whatsapp'])): ?>
          <a href="https://wa.me/<?= formatWhatsapp($offer['whatsapp']) ?>" target="_blank" class="btn-icon whatsapp" title="واتساب"><i class="fab fa-whatsapp"></i></a>
        <?php endif; ?>
        <?php if(!empty($offer['phone'])): ?>
          <a href="tel:<?= htmlspecialchars($offer['phone']) ?>" class="btn-icon phone" title="اتصال"><i class="fas fa-phone-alt"></i></a>
        <?php endif; ?>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<!-- ===== السلايدر السفلي ===== -->
<div class="bottom-slider">
  <?php if ($sliders_bottom): foreach ($sliders_bottom as $s):
    $img = slider_img_path($s['image'] ?? '');
    $url = trim($s['link'] ?? '');
    $title = htmlspecialchars($s['title'] ?? '');
    $is_ext = preg_match('~^https?://~i', $url);
  ?>
    <div class="slider-item">
      <?php if ($url): ?>
        <a class="slide-link" href="<?= htmlspecialchars($url) ?>" <?= $is_ext ? 'target="_blank" rel="noopener"' : '' ?>>
          <img src="<?= htmlspecialchars($img) ?>" alt="<?= $title ?>">
          <?php if ($title): ?><div class="slider-caption"><?= $title ?></div><?php endif; ?>
        </a>
      <?php else: ?>
        <img src="<?= htmlspecialchars($img) ?>" alt="<?= $title ?>">
        <?php if ($title): ?><div class="slider-caption"><?= $title ?></div><?php endif; ?>
      <?php endif; ?>
    </div>
  <?php endforeach; else: ?>
    <div style="text-align:center;color:#aaa;padding:24px;">لا توجد شرائح حالياً.</div>
  <?php endif; ?>
</div>

<!-- ===== شركاء النجاح ===== -->
<div class="featured-slider">
  <div class="slider-header">
    <h2><i class="fas fa-handshake"></i> شركاء النجاح</h2>
  </div>
  <div class="companies-slider">
    <?php if ($partners): foreach ($partners as $partner):
      $logo = trim($partner['logo'] ?? '');
      if ($logo !== '' && strpos($logo, 'uploads/partners/') !== 0) $logo = 'uploads/partners/' . $logo;
    ?>
      <div class="slide-item">
        <a href="<?= htmlspecialchars($partner['link'] ?: '#') ?>" target="_blank" rel="noopener">
          <div class="slide-img">
            <?php if ($logo): ?>
              <img src="<?= htmlspecialchars($logo) ?>" alt="شعار <?= htmlspecialchars($partner['name']) ?>">
            <?php else: ?>
              <span style="color:#bbb;font-size:13px;">لا يوجد شعار</span>
            <?php endif; ?>
          </div>
        </a>
      </div>
    <?php endforeach; else: ?>
      <div style="color:#aaa;padding:24px;text-align:center;">لا يوجد شعارات شركاء حالياً.</div>
    <?php endif; ?>
  </div>
</div>

<!-- مكتبات وتهيئة واحدة فقط (احذف أي مكررات في الهيدر) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js"></script>

<script>
// تبويبات البحث
$('#tab-companies').on('click', function(){
  $(this).addClass('active'); $('#tab-offers').removeClass('active');
  $('#form-companies').show(); $('#form-offers').hide();
});
$('#tab-offers').on('click', function(){
  $(this).addClass('active'); $('#tab-companies').removeClass('active');
  $('#form-offers').show(); $('#form-companies').hide();
});

// تهيئة كل السلايدرات مرة واحدة
$(function(){
  var $main   = $('.main-slider');
  var $bottom = $('.bottom-slider');

  if ($main.hasClass('slick-initialized'))   $main.slick('unslick');
  if ($bottom.hasClass('slick-initialized')) $bottom.slick('unslick');

  $main.slick({
    rtl:true, dots:true, arrows:true, infinite:true,
    slidesToShow:1, slidesToScroll:1,
    autoplay:true, autoplaySpeed:5000,
    pauseOnHover:true, pauseOnFocus:true,
    prevArrow:'<button class="slick-prev"><i class="fas fa-chevron-right"></i></button>',
    nextArrow:'<button class="slick-next"><i class="fas fa-chevron-left"></i></button>'
  });

  $bottom.slick({
    rtl:true, dots:true, arrows:true, infinite:true,
    slidesToShow:1, slidesToScroll:1,
    autoplay:true, autoplaySpeed:4500,
    pauseOnHover:true, pauseOnFocus:true,
    prevArrow:'<button class="slick-prev"><i class="fas fa-chevron-right"></i></button>',
    nextArrow:'<button class="slick-next"><i class="fas fa-chevron-left"></i></button>'
  });

  // أحدث العروض (كرتين مبدئياً على الديسكتوب)
  $('.offers-slider').slick({
    rtl:true, dots:true, arrows:true, infinite:true,
    slidesToShow:2, slidesToScroll:1,
    autoplay:true, autoplaySpeed:5000,
    responsive:[{ breakpoint:991, settings:{ slidesToShow:1 } }],
    prevArrow:'<button class="slick-prev"><i class="fas fa-chevron-right"></i></button>',
    nextArrow:'<button class="slick-next"><i class="fas fa-chevron-left"></i></button>'
  });

  // شعارات الشركاء
  $('.companies-slider').slick({
    rtl:true, dots:false, arrows:true, infinite:true,
    slidesToShow:5, slidesToScroll:1,
    autoplay:true, autoplaySpeed:3000,
    responsive:[
      { breakpoint:1200, settings:{ slidesToShow:4 } },
      { breakpoint:991,  settings:{ slidesToShow:3 } },
      { breakpoint:600,  settings:{ slidesToShow:2 } }
    ],
    prevArrow:'<button class="slick-prev"><i class="fas fa-chevron-right"></i></button>',
    nextArrow:'<button class="slick-next"><i class="fas fa-chevron-left"></i></button>'
  });

  // حماية إضافية: في حال كان هناك سكربت قديم يختطف النقرات، نضمن فتح رابط السلايد نفسه فقط
  function openSlideLink(e){
    // تجاهل النقر على الأسهم/النقاط/الروابط نفسها
    if ($(e.target).closest('.slick-arrow, .slick-dots, a').length) return;
    var $a = $(this).find('a.slide-link').first();
    if (!$a.length) return;
    var href = $a.attr('href');
    if (!href) return;
    if (/^https?:\/\//i.test(href)) window.open(href, '_blank', 'noopener'); else window.location.href = href;
  }
  $main.on('click', '.slick-slide', openSlideLink);
  $bottom.on('click', '.slick-slide', openSlideLink);
});
</script>

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