<?php
$info = model('App\Models\SchoolInfoModel')->find(1);
$logo = !empty($info['logo_path']) ? base_url($info['logo_path']) : base_url('assets/images/logo1.png');
$schoolName = !empty($info['school_name']) ? esc($info['school_name']) : 'SMAS SENTOSA BHAKTI';

if (!isset($row) || empty($row)) {
    echo "Data berita tidak ditemukan.";
    exit;
}

$imgFile = $row['gambar'] ?? null;

$img = !empty($imgFile)
    ? base_url('uploads/berita/' . $imgFile)
    : base_url('assets/images/default-berita.jpg');

$tgl = $row['tanggal_publish'] ?? $row['created_at'] ?? null;
$tglTampil = $tgl ? date('d M Y', strtotime($tgl)) : '-';

/*
  ====== URL DOWNLOAD ======
  PAKAI ID biar aman walau slug kosong.
  Pastikan route ini ada:
  $routes->get('berita/download-id/(:num)', 'Berita::downloadById/$1');
*/
$downloadUrl = (!empty($imgFile) && !empty($row['id']))
    ? base_url('berita/download-id/' . $row['id'])
    : null;

// ======================================================
// ✅ CEK KELULUSAN EMBED (muncul kalau ada tag)
// Tag: [CEK_KELULUSAN]
// ======================================================
$kontenRaw = (string)($row['konten'] ?? '');
$showKelulusan = stripos($kontenRaw, '[CEK_KELULUSAN]') !== false;

// supaya tag tidak tampil di halaman
if ($showKelulusan) {
    $row['konten'] = str_ireplace('[CEK_KELULUSAN]', '', $kontenRaw);
}

// proses cek (kalau form disubmit)
$cekError = null;
$cekSuccess = null;
$hasil = null;
$pdfUrl = null;

$nisnInput = trim((string)($_POST['nisn'] ?? ''));
$tglInput  = trim((string)($_POST['tgl_lahir'] ?? ''));

if ($showKelulusan && ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST' && isset($_POST['do_cek_kelulusan'])) {
    if ($nisnInput === '' || $tglInput === '') {
        $cekError = 'NISN dan Tanggal Lahir wajib diisi.';
    } else {
        $kelulusanModel = model('App\Models\KelulusanModel');

        $hasil = $kelulusanModel
            ->where('nisn', $nisnInput)
            ->where('tgl_lahir', $tglInput)
            ->first();

        if (!$hasil) {
            $cekError = 'Data tidak ditemukan. Pastikan NISN dan Tanggal Lahir benar.';
        } else {
            $cekSuccess = 'Data ditemukan.';

            // cek pdf SKL
            $pdfFile = 'SKL_' . preg_replace('/\D+/', '', $nisnInput) . '.pdf';
            $pdfPath = ROOTPATH . 'public/uploads/skl/' . $pdfFile;
            $pdfUrl  = is_file($pdfPath) ? base_url('uploads/skl/' . $pdfFile) : null;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title><?= $schoolName ?> - <?= esc($row['judul']) ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="<?= base_url('assets/css/berita.css') ?>">

  <style>
    body { background:#f4f6f8; font-family:system-ui,-apple-system,BlinkMacSystemFont,sans-serif; }
    .detail-wrapper{ max-width:900px; margin:40px auto; background:#fff; padding:32px; border-radius:16px; box-shadow:0 12px 30px rgba(0,0,0,.08); }
    .detail-back{ margin-bottom:12px; }
    .detail-back a{ color:#0d6efd; text-decoration:none; font-weight:500; }
    .detail-title{ font-size:30px; font-weight:700; margin:10px 0; line-height:1.3; }
    .detail-meta{ color:#6c757d; font-size:14px; margin-bottom:14px; display:flex; gap:10px; flex-wrap:wrap; align-items:center; }
    .detail-actions{ margin: 6px 0 10px; display:flex; gap:10px; flex-wrap:wrap; }
    .btn{
      display:inline-flex; align-items:center; gap:8px;
      padding:10px 14px; border-radius:12px; text-decoration:none;
      font-weight:600; font-size:14px; border:1px solid transparent;
      transition:.15s ease;
    }
    .btn-primary{ background:#0d6efd; color:#fff; }
    .btn-primary:hover{ filter:brightness(.95); }
    .btn-ghost{ background:#fff; color:#0d6efd; border-color:#cfe2ff; }
    .btn-ghost:hover{ background:#f1f7ff; }

    .detail-image{ width:100%; margin:20px 0; text-align:center; }
    .detail-image img{
      width:100%;
      height:auto;
      max-height:80vh;
      object-fit:contain;
      border-radius:14px;
      background:#f1f3f5;
    }
    
    /* =========================
       🔧 FIX UTAMA DI SINI
       ========================= */
       .detail-content{
      font-size:16px;
      line-height:1.9;
      color:#212529;

      word-wrap: break-word;
      overflow-wrap: break-word;
      word-break: break-word;
    }

    .detail-ringkasan{ font-size:18px; line-height:1.7; font-style:italic; color:#495057; margin-bottom:22px; }
    .detail-content{ font-size:16px; line-height:1.9; color:#212529; }
    .detail-content img{ max-width:100%; height:auto; }

    /* ===== Kelulusan box ===== */
    .kel-box{ margin-top:28px; padding:18px; border:1px solid #e9ecef; border-radius:16px; background:#fbfcfe; }
    .kel-title{ margin:0 0 6px; font-size:18px; font-weight:800; }
    .kel-sub{ margin:0 0 14px; color:#556; font-size:14px; }
    .kel-grid{ display:grid; grid-template-columns: 1fr 1fr; gap:12px; }
    .kel-grid input{ width:100%; padding:10px 12px; border:1px solid #ced4da; border-radius:12px; }
    .kel-actions{ margin-top:12px; display:flex; gap:10px; flex-wrap:wrap; }
    .alert{ padding:10px 12px; border-radius:12px; margin:12px 0 0; font-size:14px; }
    .alert-err{ background:#fee2e2; border:1px solid #f87171; }
    .alert-ok{ background:#d1fae5; border:1px solid #34d399; }
    .kel-table{ margin-top:12px; width:100%; border-collapse:collapse; }
    .kel-table th,.kel-table td{ border:1px solid #e9ecef; padding:10px; text-align:left; }
    .kel-table th{ background:#f8f9fa; width:30%; }
    @media (max-width:768px){
      .detail-wrapper{ padding:22px; }
      .detail-title{ font-size:24px; }
      .kel-grid{ grid-template-columns:1fr; }
    }
  </style>
</head>
<body>

<nav>
  <div class="left-box">
    <img src="<?= $logo ?>" alt="Logo">
    <span class="school-name"><?= $schoolName ?></span>
  </div>
  <ul>
    <a href="<?= base_url() ?>">Beranda</a>
    <a href="<?= base_url('berita') ?>">Berita</a>
    <a href="<?= base_url('galeri') ?>">Galeri</a>
    <a href="<?= base_url('tentang') ?>">Tentang</a>
  </ul>
</nav>

<section class="detail-wrapper">

  <div class="detail-back">
    <a href="<?= base_url('berita') ?>">← Kembali ke Berita</a>
  </div>

  <h1 class="detail-title"><?= esc($row['judul']) ?></h1>

  <div class="detail-meta">
    <strong><?= esc(strtoupper($row['kategori'])) ?></strong>
    <span>• <?= esc($tglTampil) ?></span>
    <span>• <?= esc($row['penulis'] ?? 'Admin') ?></span>
  </div>

  <?php if ($downloadUrl): ?>
    <div class="detail-actions">
      <a class="btn btn-primary" href="<?= $downloadUrl ?>">⬇ Download Foto</a>
      <a class="btn btn-ghost" href="<?= $img ?>" target="_blank" rel="noopener">🖼 Buka Foto</a>
    </div>
  <?php endif; ?>

  <div class="detail-image">
    <img src="<?= $img ?>" alt="<?= esc($row['judul']) ?>">
  </div>

  <?php if (!empty($row['ringkasan'])) : ?>
    <div class="detail-ringkasan">
      <?= esc($row['ringkasan']) ?>
    </div>
  <?php endif; ?>

  <?php
$konten = $row['konten'] ?? '';

// kalau ada placeholder, ganti dengan form cek kelulusan
if (strpos($konten, '[CEK_KELULUSAN]') !== false) {
    $formKelulusan = view('kelulusan/_embed_form');
    $konten = str_replace('[CEK_KELULUSAN]', $formKelulusan, $konten);
}
?>

<div class="detail-content">
  <?= $konten ?>
</div>

  <?php if ($showKelulusan): ?>
    <form method="post" action="<?= site_url('kelulusan/cek') ?>" style="margin:14px 0;">
    <?= csrf_field() ?>

    <div style="margin-bottom:10px;">
      <label>NISN</label><br>
      <input type="text" name="nisn" value="<?= esc($nisn ?? '') ?>"
             placeholder="contoh: 1234567890"
             style="width:100%;padding:10px;border:1px solid #ccc;border-radius:8px;">
    </div>

    <div style="margin-bottom:10px;">
      <label>Tanggal Lahir (YYYY-MM-DD)</label><br>
      <input type="date" name="tgl_lahir" value="<?= esc($tgl_lahir ?? '') ?>"
             style="width:100%;padding:10px;border:1px solid #ccc;border-radius:8px;">
      <small style="color:#666;">Contoh: 2007-01-12</small>
    </div>

    <button type="submit"
            style="padding:10px 14px;border:none;border-radius:10px;background:#2563eb;color:#fff;cursor:pointer;">
      Cek Kelulusan
    </button>
  </form>

        <?php if ($cekError): ?>
          <div class="alert alert-err"><?= esc($cekError) ?></div>
        <?php endif; ?>

        <?php if ($cekSuccess): ?>
          <div class="alert alert-ok"><?= esc($cekSuccess) ?></div>
        <?php endif; ?>
      </form>

      <?php if (!empty($hasil)): ?>
        <table class="kel-table">
          <tr><th>Tahun</th><td><?= esc($hasil['tahun'] ?? '-') ?></td></tr>
          <tr><th>NISN</th><td><?= esc($hasil['nisn'] ?? '-') ?></td></tr>
          <tr><th>Nama</th><td><?= esc($hasil['nama'] ?? '-') ?></td></tr>
          <tr><th>Kelas</th><td><?= esc($hasil['kelas'] ?? '-') ?></td></tr>
          <tr><th>Status</th><td><b><?= esc($hasil['status'] ?? '-') ?></b></td></tr>
          <?php if (!empty($hasil['keterangan'])): ?>
            <tr><th>Keterangan</th><td><?= esc($hasil['keterangan']) ?></td></tr>
          <?php endif; ?>
        </table>

        <div class="kel-actions" style="margin-top:14px;">
          <?php if (!empty($pdfUrl)): ?>
            <a class="btn btn-primary" href="<?= esc($pdfUrl) ?>" target="_blank" rel="noopener">📄 Lihat PDF SKL</a>
            <a class="btn btn-ghost" href="<?= esc($pdfUrl) ?>" download>⬇ Download PDF SKL</a>
          <?php else: ?>
            <span style="color:#b45309;">PDF SKL belum tersedia.</span>
          <?php endif; ?>
        </div>
      <?php endif; ?>
    </div>
  <?php endif; ?>

</section>

</body>
</html>
