<?php
header('Content-Type: text/html; charset=UTF-8');
session_start();
require_once 'db.php'; // Use centralized, secure DB connection

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Fetch selected blog post with category name
$stmt = $pdo->prepare("
    SELECT blogs.*, categories.name AS category 
    FROM blogs 
    LEFT JOIN categories ON blogs.category_id = categories.id 
    WHERE blogs.id = ? 
    LIMIT 1
");
$stmt->execute([$id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);






// Fetch other blog recommendations
// Step 1: Always include blog ID 8 if it's not the current blog
$related = [];

if ($id != 8) {
    $stmt = $pdo->prepare("SELECT id, title FROM blogs WHERE id = ?");
    $stmt->execute([8]);
    $fixedBlog = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($fixedBlog) {
        $related[] = $fixedBlog;
    }
}

// Step 2: Fetch 3 more blogs excluding the current blog and blog ID 8
$excludeIds = [$id, 8];
$placeholders = implode(',', array_fill(0, count($excludeIds), '?'));

$stmt = $pdo->prepare("
    SELECT id, title 
    FROM blogs 
    WHERE id NOT IN ($placeholders)
    ORDER BY created_at DESC 
    LIMIT 3
");
$stmt->execute($excludeIds);
$moreBlogs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Step 3: Merge all into final related list
$recommendedBlogs = array_merge($related, $moreBlogs);











// Fetch latest blog posts for sidebar
$latestBlogsStmt = $pdo->query("
    SELECT id, title 
    FROM blogs 
    ORDER BY created_at DESC 
    LIMIT 5
");
$latestBlogs = $latestBlogsStmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch latest user reviews
$latestReviewsStmt = $pdo->query("
    SELECT r.comment, r.rating, u.username, c.name AS company_name
    FROM reviews r
    JOIN users u ON r.user_id = u.id
    JOIN companies c ON r.company_id = c.id
    ORDER BY r.id DESC
    LIMIT 5
");
$latestReviews = $latestReviewsStmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch top-rated companies
$topCompaniesStmt = $pdo->query("
    SELECT c.id, c.name, c.image, ROUND(AVG(r.rating), 1) AS avg_rating
    FROM companies c
    JOIN reviews r ON c.id = r.company_id
    GROUP BY c.id
    HAVING COUNT(r.id) >= 1
    ORDER BY avg_rating DESC
    LIMIT 5
");
$topCompanies = $topCompaniesStmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title><?= $row ? htmlspecialchars($row['title']) : 'Post Not Found' ?> - Review Stream</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
	<!-- Sans-serif fonts -->
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Raleway&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Roboto+Slab&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif&display=swap" rel="stylesheet">


<!-- Favicon -->
<link rel="icon" href="/favicon.png" type="image/png" />

    <style>
body { margin:0; font-family:Arial,sans-serif; background:#f9f9f9; padding-bottom: 140px}
.topbar { display:flex; justify-content:space-between; align-items:center; padding:10px 20px; background:#007BFF; color:white; }
.logo { font-weight:bold; font-size:20px; }
.menu a { color:white; margin:0 8px; text-decoration:none; }
.menu a:hover { text-decoration:underline; }
.container { max-width:1200px; margin:20px auto; padding:0 10px; }
.content-layout { display: flex; gap: 20px; flex-wrap: wrap; }
.main-content { 
  flex: 3; 
  min-width: 250px; 
}
.sidebar { flex: 1; min-width: 200px; display: flex; flex-direction: column; gap: 20px; }
.sidebar-card {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 10px rgba(0,0,0,0.07);
  transition: box-shadow 0.3s ease;
}
.sidebar-card:hover { box-shadow: 0 6px 14px rgba(0,0,0,0.12); }

.review-box {
  background: white;
  padding: 10px;
  border-radius: 8px;
  margin-bottom: 15px;
}
.hero {
  background: linear-gradient(90deg, #007BFF, #00b67a);
  color: white;
  text-align: center;
  padding: 40px 20px;
  border-radius: 12px;
  margin-bottom: 30px;
  box-shadow: 0 6px 14px rgba(0,0,0,0.15);
}
.hero h2 { margin: 0; font-size: 28px; }
.star-box { display: inline-block; width: 20px; height: 20px; margin-right: 2px; text-align: center; line-height: 20px; border-radius: 3px; }
.star-box.filled { background: #00b67a; color: white; }
.star-box.empty { background: #d3d3d3; color: white; }
.blog-post { background:white; padding:20px; border-radius:12px; box-shadow:0 4px 10px rgba(0,0,0,0.07); margin-bottom:20px; }
.blog-post img { width: 100%; border-radius: 8px; height: auto; object-fit: cover; margin-bottom: 15px; }
.category { font-size: 0.9em; color: #999; margin-bottom: 10px; }
@media (max-width: 768px) {
  .topbar { flex-direction: column; gap: 10px; }
  .menu { display: flex; flex-wrap: wrap; justify-content: center; }
}

.fixed-footer {
      position: fixed;
      left: 0;
      bottom: 0;
      width: 100%;
      background: #222;
      text-align: center;
      padding: 10px 0;
      color: #fff;
      z-index: 1000;
    }
	.fixed-footer p{
		font-family: 'Poppins', sans-serif !important;
		font-size: 13px !important;
	}

    .footer-menu a {
      margin: 0 10px;
      text-decoration: none;
      color: #fff;
	  font-family: 'Poppins', sans-serif !important;
	  font-size: 13px !important;
    }

    .footer-menu a:hover {
      text-decoration: underline;
    }
	
	
	
.topbar {
  background-color: #007BFF; /* Blue */
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 15px;
  position: relative;
}

.logo {
  display: flex;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
}

.logo-icon {
  background: linear-gradient(135deg, #a2d4f5, #fefb72);
  border-radius: 50%;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
}

.menu-toggle {
  font-size: 1.5em;
  color: #fff;
  cursor: pointer;
  display: none;
}

.menu {
  display: flex;
  gap: 15px;
}

.menu a, .menu button {
  color: #fff;
  text-decoration: none;
  background: none;
  border: none;
  cursor: pointer;
}

/* Mobile styles */
@media (max-width: 768px) {
  .menu-toggle {
    display: block;
  }

  .menu {
    flex-direction: column;
    background-color: #007BFF;
    position: absolute;
    top: 60px;
    left: 0;
    right: 0;
    display: none;
    padding: 10px 0;
    z-index: 1000;
  }

  .menu.active {
    display: flex;
  }

  .menu a, .menu button {
    padding: 10px 15px;
  }
}



/*Related News*/
.related-news {
  margin-top: 40px;
  padding: 20px;
  border-top: 1px solid #ddd;
  background-color: #f9f9f9;
  font-family: 'Poppins', sans-serif;
}

.related-news h3 {
  font-size: 20px;
  margin-bottom: 15px;
  color: #333;
}

.related-news ul {
  list-style-type: disc;
  padding-left: 20px;
  margin-top: 10px;
}

.related-news li {
  margin-bottom: 10px;
}

.related-news a {
  text-decoration: none;
  color: #007BFF;
  font-weight: 500;
}

.related-news a:hover {
  text-decoration: underline;
  color: #0056b3;
}

</style>
</head>
<body>
<div class="topbar">
  <div class="logo">
    <div class="logo-icon">
      <i class="fas fa-shield-alt" style="color:#4A90E2; font-size: 25px; box-shadow: 0 1px 3px rgba(0,0,0,0.2); margin-left: 1px"></i>
    </div>
    REVIEW STREAM
  </div>

  <div class="menu-toggle" onclick="toggleMenu()">
    <i class="fas fa-bars"></i>
  </div>

  <div class="menu" id="topMenu">
    <a href="index.php">Home</a>
    <a href="companies.php">Companies</a>
	<a href="blog.php">Newsroom</a>
    <?php if(isset($_SESSION['user_id'])): ?>
      <a href="user-settings.php">My Settings</a>
      <a href="logout.php">Logout</a>
    <?php else: ?>
      <a href="login.php">Login</a>
    <?php endif; ?>
    <button class="dark-mode-toggle" onclick="document.body.classList.toggle('dark-mode')">🌓</button>
  </div>
</div>

<div class="container">
  <div class="hero">
    <h2>📰 News Details</h2>
  </div>
  <div class="content-layout">
    <div class="main-content">
      <?php if ($row): ?>
        <div class="blog-post">
            <?php if ($row['image']): ?>
        <img src="uploads/<?= htmlspecialchars($row['image']) ?>" alt="<?= htmlspecialchars($row['title']) ?>" style="width:100%; border-radius:8px; margin-bottom:15px;">
    <?php endif; ?>
    <h2><?= htmlspecialchars($row['title']) ?></h2>
    <?php if ($row['category']): ?>
        <div class="category">Category: <?= htmlspecialchars($row['category']) ?></div>
    <?php endif; ?>
    <div><?= nl2br(htmlspecialchars($row['content'])) ?></div>
        </div>
      <?php else: ?>
        <p>Post not found.</p>
      <?php endif; ?>
    </div>
    <div class="sidebar">
      <div class="sidebar-card">
        <h4>Latest Reviews</h4>
        <?php foreach($latestReviews as $rev): ?>
          <p><strong><?= htmlspecialchars($rev['username']) ?></strong> on <em><?= htmlspecialchars($rev['company_name']) ?></em>:</p>
          <div>
            <?php for($i=1;$i<=5;$i++): ?>
              <span class="star-box <?= $i<=$rev['rating'] ? 'filled' : 'empty' ?>">★</span>
            <?php endfor; ?>
            (<?= $rev['rating'] ?>/5)
          </div>
          <p style="margin-top:2px;"><?= htmlspecialchars(substr($rev['comment'],0,50)) ?>...</p>
          <hr>
        <?php endforeach; ?>
      </div>
      <div class="sidebar-card">
        <h4>Top Rated Companies</h4>
        <?php foreach($topCompanies as $top): ?>
          <div style="display:flex;align-items:center;gap:8px;margin-bottom:5px;">
            <img src="images/companies/<?= htmlspecialchars($top['image']) ?>" alt="<?= htmlspecialchars($top['name']) ?>" style="width:30px;height:30px;object-fit:contain;">
            <span><?= htmlspecialchars($top['name']) ?> (<?= $top['avg_rating'] ?>/5)</span>
          </div>
        <?php endforeach; ?>
      </div>
      <div class="sidebar-card">
        <h4>Latest Blog Posts</h4>
        <?php foreach($latestBlogs as $b): ?>
          <p><a href="blog_details.php?id=<?= $b['id'] ?>"><?= htmlspecialchars($b['title']) ?></a></p>
        <?php endforeach; ?>
      </div>
    </div>
	

  </div>
  
  <?php if (!empty($recommendedBlogs)): ?>
  <div class="related-news">
    <h3>Related News</h3>
    <ul>
      <?php foreach($recommendedBlogs as $blog): ?>
        <li>
          <a href="blog_details.php?id=<?= $blog['id'] ?>">
            <?= htmlspecialchars($blog['title']) ?>
          </a>
        </li>
      <?php endforeach; ?>
    </ul>
  </div>
<?php endif; ?>


</div>



<?php include 'footer.php'; ?>


<script>
  function toggleMenu() {
    document.getElementById('topMenu').classList.toggle('active');
  }
</script>
</body>
</html>
