<?php
require_once __DIR__.'/db.php';
require_once __DIR__.'/header-student.php';
// require_student();

$id = (int)$_GET['id'];
$blog = $mysqli->query("SELECT * FROM blogs WHERE id=$id")->fetch_assoc();
if (!$blog) die("Blog not found");

$pdfs = $mysqli->query("SELECT * FROM blog_pdfs WHERE blog_id=$id");
$videos = $mysqli->query("SELECT * FROM blog_videos WHERE blog_id=$id");

function isRTL($text) {
    return preg_match('/[\x{0600}-\x{06FF}]/u', $text);
}

$dir   = isRTL($blog['content']) ? 'rtl' : 'ltr';
$class = isRTL($blog['content']) ? 'rtl' : 'ltr';
?>
<link rel="stylesheet" href="assets/view-blog.css">
<div class="container mt-2">
  <div class="card">
    <div class="card-header">
      <a href="index.php" class="btn btn-outline-secondary" style="padding: 2px 6px !important; border-radius: 50%; background: gray; color: white">←</a>
      <b><?= htmlspecialchars($blog['title']) ?></b>
    </div>
    <div class="card-body">
      <p dir="<?= $dir ?>" class="<?= $class ?>"><?= nl2br(htmlspecialchars($blog['content'])) ?></p>

      <?php if($pdfs->num_rows): ?>
        <hr><p><b>Documents</b></p>
        <table class="table" width='100%'>
          <tbody>
            <?php while($pdf = $pdfs->fetch_assoc()): ?>
              <tr>
                <td><b><?= htmlspecialchars($pdf['title']) ?></b></td>
                <td align=right><a href="<?php echo $base_url; ?>/<?= $pdf['pdf_path'] ?>" target="_blank">📄 View PDF</a></td>
              </tr>
            <?php endwhile; ?>
          </tbody>
        </table>
      <?php endif; ?>


      <?php if($videos->num_rows): ?>
      <hr><p><b>Videos</b></p>
      <table class="table" width="100%">
        <tbody>
      <?php while($vid = $videos->fetch_assoc()): ?>
          <tr>
            <td><b><?= htmlspecialchars($vid['title']) ?></b></td>
            <td align=right><a href="<?= $vid['youtube_url'] ?>" target="_blank">📄 Open Link</a></td>
          </tr>
      <?php endwhile; ?>
        </tbody>
      </table>
      <?php endif; ?>
    </div>
  </div>
</div>
</body>
</html>
