<?php
$page_title  = "Blog & News — CY Consultancy Centre";
$page_desc   = "Latest news and guides for Bangladeshi students studying abroad.";
$active_page = "blog";
include 'includes/header.php';
$B  = BASE_PATH;
$db = site_db();

// Search & filter
$search = trim($_GET['q']   ?? '');
$cat    = trim($_GET['cat'] ?? '');
$page   = max(1, (int)($_GET['page'] ?? 1));
$perPage= 6;
$offset = ($page - 1) * $perPage;

$where = "WHERE status='published'";
$params = [];
if ($search) { $where .= " AND (title LIKE '%".htmlspecialchars($search,ENT_QUOTES)."%' OR excerpt LIKE '%".htmlspecialchars($search,ENT_QUOTES)."%')"; }
if ($cat)    { $where .= " AND category='".htmlspecialchars($cat,ENT_QUOTES)."'"; }

$posts = $total = [];
$totalCount = 0;
$categories = [];
$recentPosts= [];
if ($db) {
    $r = $db->query("SELECT * FROM blog_posts $where ORDER BY created_at DESC LIMIT $perPage OFFSET $offset");
    if ($r) $posts = $r->fetch_all(MYSQLI_ASSOC);
    $r2 = $db->query("SELECT COUNT(*) as c FROM blog_posts $where");
    if ($r2) $totalCount = (int)$r2->fetch_assoc()['c'];
    $r3 = $db->query("SELECT DISTINCT category FROM blog_posts WHERE status='published' AND category!='' ORDER BY category");
    if ($r3) $categories = array_column($r3->fetch_all(MYSQLI_ASSOC),'category');
    $r4 = $db->query("SELECT id,title,featured_image,created_at FROM blog_posts WHERE status='published' ORDER BY created_at DESC LIMIT 5");
    if ($r4) $recentPosts = $r4->fetch_all(MYSQLI_ASSOC);
}
$totalPages = ceil($totalCount / $perPage);
?>
<div class="page-hero" style="background-image:url('<?=$B?>assets/images/bg-study2.jpg');background-size:cover;background-position:center">
  <h1>Blog &amp; Study Abroad News</h1>
  <p>Latest news, visa updates, study tips and insights to help plan your journey abroad.</p>
  <div class="breadcrumb"><a href="<?=$B?>index.php">Home</a><i class="fas fa-chevron-right"></i><span>Blog</span></div>
</div>

<!-- Search bar -->
<div style="background:#fff;padding:20px 0;border-bottom:1px solid #e5e7eb">
  <form method="GET" style="max-width:600px;margin:0 auto;padding:0 20px;display:flex;gap:10px">
    <input type="text" name="q" value="<?=htmlspecialchars($search)?>" placeholder="Search blog posts..." style="flex:1;padding:10px 16px;border:1.5px solid #e5e7eb;border-radius:8px;font-size:14px;outline:none">
    <?php if ($cat): ?><input type="hidden" name="cat" value="<?=htmlspecialchars($cat)?>"><?php endif; ?>
    <button type="submit" style="padding:10px 20px;background:#1a56db;color:#fff;border:none;border-radius:8px;font-weight:600;cursor:pointer"><i class="fas fa-search"></i></button>
  </form>
</div>

<section class="sec" style="background:var(--bgf)">
  <div class="blog-layout">
    <div class="blog-main">
      <?php if (empty($posts)): ?>
      <div style="text-align:center;padding:60px 20px;color:#6b7280">
        <i class="fas fa-newspaper" style="font-size:48px;opacity:.3;display:block;margin-bottom:16px"></i>
        <h3 style="margin-bottom:8px">No blog posts found</h3>
        <?php if ($search || $cat): ?>
        <p><a href="blog.php" style="color:#1a56db">Clear filters</a> to see all posts</p>
        <?php else: ?>
        <p>Check back soon for the latest news and guides!</p>
        <?php endif; ?>
      </div>
      <?php else: ?>
      <?php foreach($posts as $i => $p): ?>
      <div class="blog-card" data-aos="fade-up" data-aos-delay="<?=$i*80?>">
        <div class="blog-img">
          <?php if ($p['featured_image']): ?>
          <img src="<?=htmlspecialchars(BASE_URL.'/'.$p['featured_image'])?>" alt="<?=htmlspecialchars($p['title'])?>" loading="lazy" onerror="this.parentNode.style.background='linear-gradient(135deg,#1a56db,#1e3a8a)';this.style.display='none'">
          <?php else: ?>
          <div style="width:100%;height:100%;min-height:200px;background:linear-gradient(135deg,#1a56db,#1e3a8a);display:flex;align-items:center;justify-content:center;font-size:48px">
            <?= $p['category']==='Malta'?'🇲🇹':($p['category']==='UK'?'🇬🇧':($p['category']==='Canada'?'🇨🇦':'📰')) ?>
          </div>
          <?php endif; ?>
        </div>
        <div class="blog-body">
          <div class="blog-meta">
            <?php if($p['category']): ?><span class="blog-cat"><?=htmlspecialchars($p['category'])?></span><?php endif; ?>
            <span class="blog-date"><i class="far fa-calendar"></i> <?=date('M j, Y',strtotime($p['created_at']))?></span>
            <span style="font-size:11px;color:#9ca3af"><i class="fas fa-user" style="margin-right:3px"></i><?=htmlspecialchars($p['author']??'CY Consultancy')?></span>
          </div>
          <h3><?=htmlspecialchars($p['title'])?></h3>
          <p><?=htmlspecialchars($p['excerpt']??substr(strip_tags($p['content']??''),0,150).'...')?></p>
          <a href="blog-post.php?slug=<?=htmlspecialchars($p['slug'])?>" class="blog-read">Read More <i class="fas fa-arrow-right"></i></a>
        </div>
      </div>
      <?php endforeach; ?>

      <?php if ($totalPages > 1): ?>
      <div style="display:flex;gap:8px;justify-content:center;margin-top:32px;flex-wrap:wrap">
        <?php for($pg=1;$pg<=$totalPages;$pg++): ?>
        <a href="?page=<?=$pg?><?=$search?'&q='.urlencode($search):''?><?=$cat?'&cat='.urlencode($cat):'?'?>"
           style="width:38px;height:38px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-weight:600;font-size:14px;text-decoration:none;<?=$pg===$page?'background:#1a56db;color:#fff':'background:#fff;color:#374151;border:1px solid #e5e7eb'?>">
          <?=$pg?>
        </a>
        <?php endfor; ?>
      </div>
      <?php endif; ?>
      <?php endif; ?>
    </div>

    <!-- SIDEBAR -->
    <div class="blog-sidebar">
      <?php if (!empty($recentPosts)): ?>
      <div class="sb-box" data-aos="fade-left">
        <h4>Recent Posts</h4>
        <?php foreach($recentPosts as $rp): ?>
        <div class="rp">
          <div class="rp-img">
            <?php if($rp['featured_image']): ?>
            <img src="<?=htmlspecialchars(BASE_URL.'/'.$rp['featured_image'])?>" alt="" onerror="this.style.display='none'">
            <?php else: ?>
            <div style="width:100%;height:100%;background:#dbeafe;display:flex;align-items:center;justify-content:center;font-size:18px">📰</div>
            <?php endif; ?>
          </div>
          <div>
            <div class="rp-title"><a href="blog-post.php?id=<?=$rp['id']?>" style="color:inherit;text-decoration:none"><?=htmlspecialchars(substr($rp['title'],0,45).(strlen($rp['title'])>45?'...':''))?></a></div>
            <div class="rp-date"><?=date('M j, Y',strtotime($rp['created_at']))?></div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <?php if (!empty($categories)): ?>
      <div class="sb-box" data-aos="fade-left">
        <h4>Categories</h4>
        <ul class="cat-list">
          <?php foreach($categories as $c): 
            $cnt = $db ? (int)$db->query("SELECT COUNT(*) as n FROM blog_posts WHERE status='published' AND category='".htmlspecialchars($c,ENT_QUOTES)."'")->fetch_assoc()['n'] : 0;
          ?>
          <li><a href="?cat=<?=urlencode($c)?>" style="<?=$cat===$c?'color:#1a56db;font-weight:700':''?>"><?=htmlspecialchars($c)?></a><span class="cat-count"><?=$cnt?></span></li>
          <?php endforeach; ?>
          <?php if ($cat): ?><li><a href="blog.php" style="color:#e76f51">✕ Clear filter</a></li><?php endif; ?>
        </ul>
      </div>
      <?php endif; ?>

      <div class="sb-box" data-aos="fade-left" style="background:linear-gradient(135deg,#e76f51,#f4a261);border:none">
        <h4 style="color:#fff;border-color:rgba(255,255,255,.2)">Free Consultation</h4>
        <p style="font-size:12.5px;color:rgba(255,255,255,.9);margin-bottom:14px;line-height:1.7">Questions about studying abroad? Talk to our experts — completely free!</p>
        <a href="<?=$B?>contact.php" class="btn" style="background:#fff;color:#e76f51;width:100%;justify-content:center;font-size:13px;font-weight:700"><i class="fas fa-arrow-right"></i> Book Now</a>
      </div>
    </div>
  </div>
</section>
<?php include 'includes/footer.php'; ?>
