<?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';
$heroBg = !empty($info['hero_bg_path']) ? "background-image:url('".base_url($info['hero_bg_path'])."');" : '';
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= $schoolName ?></title>

  <link rel="stylesheet" href="<?= base_url('assets/css/style.css') ?>">
  <link rel="stylesheet" href="<?= base_url('assets/fontawesome/css/all.css') ?>">
  <link rel="icon" href="<?= base_url('assets/images/logo1.png') ?>" type="image/png">

  
  <style>
    :root{
      --hero-bg: url("<?= base_url($info['hero_bg_path'] ?? 'assets/images/fotologo.jpg') ?>");
    }
</style>
<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>

<?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';

$heroBgUrl = !empty($info['hero_bg_path'])
    ? base_url($info['hero_bg_path'])
    : base_url('assets/images/fotologo.jpg');
?>

<section class="hero-logo" style="--hero-bg: url('<?= esc($heroBgUrl) ?>');">
  <div class="logo-wrapper">
    <img src="<?= $logo ?>" alt="Logo Sekolah">
  </div>

  <div class="school-name-card">
  <h1 class="school-title"><?= $schoolName ?></h1>

  <?php
    // Tagline dinamis dari DB (kalau kosong pakai default)
    $tagline = !empty($info['tagline']) ? esc($info['tagline']) : 'Cerdas, Berkarakter, dan Berprestasi';
  ?>
  <p class="school-tagline"><?= $tagline ?></p>
</div>
</section>

  <div class="sosmed-container">
    <?php if (!empty($info['facebook_url'])): ?>
      <a href="<?= esc($info['facebook_url']) ?>" class="icon facebook" target="_blank" rel="noopener">
        <i class="fa-brands fa-facebook"></i>
      </a>
    <?php endif; ?>

    <?php if (!empty($info['instagram_url'])): ?>
      <a href="<?= esc($info['instagram_url']) ?>" class="icon instagram" target="_blank" rel="noopener">
        <i class="fa-brands fa-instagram"></i>
      </a>
    <?php endif; ?>

    <?php if (!empty($info['youtube_url'])): ?>
      <a href="<?= esc($info['youtube_url']) ?>" class="icon youtube" target="_blank" rel="noopener">
        <i class="fa-brands fa-youtube"></i>
      </a>
    <?php endif; ?>

    <?php if (!empty($info['email'])): ?>
      <a href="mailto:<?= esc($info['email']) ?>" class="icon gmail">
        <i class="fa-solid fa-envelope"></i>
      </a>
    <?php endif; ?>
  </div>
</section>

<!--visi misi tujuan-->
<?php
use App\Models\SchoolInfoModel;

$school = (new SchoolInfoModel())->find(1) ?? []; // ambil data id=1

function text_to_li($text)
{
    $text = trim($text ?? '');
    if ($text === '') return '';

    $lines = preg_split("/\r\n|\n|\r/", $text);
    $out = [];

    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '') continue;

        $line = preg_replace('/^[-•]\s*/', '', $line);
        $out[] = '<li>' . esc($line) . '</li>';
    }

    return implode("\n", $out);
}
?>
<section class="visi-misi-container">
  <div class="tabs">
    <button class="tab active" onclick="showTab('visi')">Visi</button>
    <button class="tab" onclick="showTab('misi')">Misi</button>
    <button class="tab" onclick="showTab('tujuan')">Tujuan</button>
  </div>

  <!-- VISI -->
  <div class="tab-content active" id="visi">
    <h2>Visi</h2>
    <p><?= nl2br(esc($school['visi'] ?? '')) ?></p>
  </div>

  <!-- MISI -->
  <div class="tab-content" id="misi">
    <h2>Misi</h2>
    <ul>
      <?= text_to_li($school['misi'] ?? '') ?>
    </ul>
  </div>

  <!-- TUJUAN -->
  <div class="tab-content" id="tujuan">
    <h2>Tujuan</h2>
    <ul>
      <?= text_to_li($school['tujuan'] ?? '') ?>
    </ul>
  </div>

</section>

<!--sambutan kepala sekolah-->
<section class="kepsek-section">
  <div class="kepsek-container">
    <!-- FOTO KEPALA SEKOLAH -->
    <div class="kepsek-photo-wrapper">
      <div class="photo-frame">

        <?php
          // fallback gambar kalau belum upload
          $foto = $school['kepsek_foto'] ?? null;
          $fotoUrl = $foto ? base_url($foto) : base_url('assets/images/nnd.png');
        ?>
        <img src="<?= esc($fotoUrl) ?>" alt="Kepala Sekolah">

      </div>
    </div>

    <!-- CONTENT -->
    <div class="kepsek-content">
      <p class="tagline">SAMBUTAN KEPALA SEKOLAH</p>

      <h2 class="main-title">
        <?= esc($school['kepsek_nama'] ?? 'Kepala Sekolah') ?><br>
        <span class="highlight">
  <?= esc($school['kepsek_judul_highlight'] ?? ($school['school_name'] ?? '')) ?>
</span>
      </h2>

      <div class="divider"></div>

      <p class="description">
        <?= nl2br(esc($school['kepsek_sambutan'] ?? '')) ?>
      </p>
    </div>
  </div>
</section>

<!--profile vidio-->
<?php
$videoTitle = trim($school['video_title'] ?? '');
$videoDesc  = trim($school['video_description'] ?? '');
$videoEmbed = trim($school['video_embed'] ?? '');

// fallback kalau kosong
if ($videoTitle === '') {
  $videoTitle = "Di Sini, Setiap Langkah Kecil\nMenuju Impian Besar Dimulai";
}
if ($videoDesc === '') {
  $videoDesc = "SMAS Sentosa Bhakti membuka peluang bagi setiap anak untuk mengembangkan potensi terbaik mereka.
Masa depan cerah dimulai dari sini! Kami hadir untuk mendukung setiap langkah generasi penerus bangsa.";
}

// pastikan embed URL benar (kalau admin masukin youtu.be / watch?v=)
if ($videoEmbed !== '') {
  // kalau bukan embed, coba konversi cepat
  if (strpos($videoEmbed, 'youtube.com/embed/') === false) {
    // ambil ID dari youtu.be atau watch?v=
    $id = '';
    if (preg_match('~youtu\.be/([^?&/]+)~', $videoEmbed, $m)) $id = $m[1];
    if (preg_match('~v=([^?&/]+)~', $videoEmbed, $m)) $id = $m[1];

    if ($id !== '') $videoEmbed = 'https://www.youtube.com/embed/' . $id;
  }
}
?>
<!--profile vidio-->
<section class="profile-section">
    <div class="profile-container">

        <!-- TEXT BLOCK -->
        <div class="profile-left fade-in-left">
            <h1 class="typing-title">
                <?= nl2br(esc($videoTitle)) ?>
            </h1>

            <p class="profile-desc fade-in">
                <?= nl2br(esc($videoDesc)) ?>
            </p>
    
            
            <button class="profile-btn" onclick="playVideo()">Video Profil Sekolah</button>
        </div>

        <!-- VIDEO BLOCK -->
        <div class="profile-video zoom-in">
            <iframe 
                id="videoFrame"
                width="560" 
                height="315"
                data-youtube="<?= esc($videoEmbed) ?>"
                title="Video Profil Sekolah" 
                frameborder="0"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                allowfullscreen>
            </iframe>
        </div>

    </div>
</section>

<!--statistika jumlah guru siswa sekolah-->
<!--statistika jumlah guru siswa sekolah-->
<section class="stats-section">
  <div class="stats-container">
    <div class="stats-header">
      <h2><?= esc($school['stats_title'] ?? 'Data Sekolah') ?></h2>
      <p><?= esc($school['stats_subtitle'] ?? 'Statistik terkini SMAS Sentosa Bhakti') ?></p>
    </div>

    <div class="stats-grid">
      <!-- GURU PENGAJAR -->
      <div class="stat-card">
        <div class="stat-number" data-target="<?= (int)($school['stat_guru_angka'] ?? 71) ?>">0</div>
        <div class="stat-label"><?= esc($school['stat_guru_label'] ?? 'Guru Pengajar') ?></div>
        <div class="stat-description"><?= esc($school['stat_guru_desc'] ?? 'Tenaga pendidik profesional dan berpengalaman') ?></div>
      </div>

      <!-- PESERTA DIDIK -->
      <div class="stat-card">
        <div class="stat-number" data-target="<?= (int)($school['stat_siswa_angka'] ?? 1373) ?>">0</div>
        <div class="stat-label"><?= esc($school['stat_siswa_label'] ?? 'Peserta Didik') ?></div>
        <div class="stat-description"><?= esc($school['stat_siswa_desc'] ?? 'Siswa aktif tahun ajaran 2024/2025') ?></div>
      </div>

      <!-- EKSTRAKURIKULER -->
      <div class="stat-card">
        <div class="stat-number" data-target="<?= (int)($school['stat_ekskul_angka'] ?? 20) ?>">0</div>
        <div class="stat-label"><?= esc($school['stat_ekskul_label'] ?? 'Ekstrakurikuler') ?></div>
        <div class="stat-description"><?= esc($school['stat_ekskul_desc'] ?? 'Program pengembangan bakat dan minat') ?></div>
      </div>
    </div>
  </div>
</section>


    <script>
        document.addEventListener("DOMContentLoaded", () => {
            const numbers = document.querySelectorAll(".stat-number");

            const animateNumber = (number) => {
                if (number.dataset.animated === "true") return;

                number.dataset.animated = "true";

                const target = parseInt(number.dataset.target);
                let current = 0;
                const increment = Math.ceil(target / 80);

                const update = () => {
                    current += increment;
                    if (current < target) {
                        number.textContent = current.toLocaleString('id-ID');
                        requestAnimationFrame(update);
                    } else {
                        number.textContent = target.toLocaleString('id-ID');
                    }
                };

                update();
            };

            const observer = new IntersectionObserver(
                (entries, obs) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            // animasi angka
                            animateNumber(entry.target);

                            // animasi card
                            entry.target.closest(".stat-card")?.classList.add("animate");

                            // stop observe → cuma sekali
                            obs.unobserve(entry.target);
                        }
                    });
                },
                { threshold: 0.5 }
            );

            numbers.forEach(number => {
                number.textContent = "0";
                observer.observe(number);
            });
        });
    </script>

<!-- FOOTER SECTION -->
<footer class="footer">
    <div class="footer-container">
        <div class="footer-content">

            <div class="footer-social">
                <!-- SOCIAL MEDIA -->
                <h4 class="footer-title">Follow Sosial Media Kami</h4>

                <div class="social-media-footer">

                    <?php if (!empty($footer['facebook'])): ?>
                        <a href="<?= esc($footer['facebook']) ?>" target="_blank" title="Facebook">
                            <i class="fab fa-facebook-f"></i>
                        </a>
                    <?php endif; ?>

                    <?php if (!empty($footer['instagram'])): ?>
                        <a href="<?= esc($footer['instagram']) ?>" target="_blank" title="Instagram">
                            <i class="fab fa-instagram"></i>
                        </a>
                    <?php endif; ?>

                    <?php if (!empty($footer['youtube'])): ?>
                        <a href="<?= esc($footer['youtube']) ?>" target="_blank" title="YouTube">
                            <i class="fab fa-youtube"></i>
                        </a>
                    <?php endif; ?>

                </div>

                <!-- ADMIN LOGIN -->
                <div class="admin-login">
                    <a href="<?= base_url('login') ?>" title="Login Admin">
                        <i class="fas fa-user-shield"></i>
                        <span></span>
                    </a>
                </div>
            </div>

            <!-- CONTACT INFO -->
            <div class="footer-contact">
                <h4 class="footer-title">Informasi Kontak</h4>

                <?php if (!empty($footer['phone'])): ?>
                    <div class="contact-item">
                        <i class="fas fa-phone-alt"></i>
                        <a href="tel:<?= esc($footer['phone']) ?>">
                            <?= esc($footer['phone']) ?>
                        </a>
                    </div>
                <?php endif; ?>

                <?php if (!empty($footer['email'])): ?>
                    <div class="contact-item">
                        <i class="fas fa-envelope"></i>
                        <a href="mailto:<?= esc($footer['email']) ?>">
                            <?= esc($footer['email']) ?>
                        </a>
                    </div>
                <?php endif; ?>

            </div>

            <!-- LOCATION MAP -->
            <div class="footer-location">
                <h4 class="footer-title">Lokasi Sekolah</h4>
                <div class="footer-map">
                    <iframe 
                        src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d1989.7486506204066!2d104.1728821444275!3d-4.1220762999999945!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x2e39af27680c431d%3A0x37cb8ef633c80b54!2sSMA%20SENTOSA%20(SMASEBHA)!5e0!3m2!1sid!2sid!4v1765644767168!5m2!1sid!2sid"
                        loading="lazy"
                        referrerpolicy="no-referrer-when-downgrade">
                    </iframe>
                </div>
            </div>

        </div>

        <!-- COPYRIGHT -->
        <div class="footer-bottom">
            <p>© <?= date('Y') ?> SMAS Sentosa Bhakti. All Rights Reserved.</p>
        </div>
    </div>
</footer>

<script>
// Hamburger Menu Toggle
document.addEventListener('DOMContentLoaded', function() {
    // Buat elemen hamburger button
    const hamburger = document.createElement('div');
    hamburger.className = 'hamburger';
    hamburger.innerHTML = '<span></span><span></span><span></span>';
    
    // Tambahkan hamburger ke dalam nav
    const nav = document.querySelector('nav');
    nav.appendChild(hamburger);
    
    // Get menu ul
    const navMenu = document.querySelector('nav ul');
    
    // Toggle menu saat hamburger diklik
    hamburger.addEventListener('click', function() {
        this.classList.toggle('active');
        navMenu.classList.toggle('active');
    });
    
    // Close menu saat link diklik
    const navLinks = document.querySelectorAll('nav ul a');
    navLinks.forEach(link => {
        link.addEventListener('click', function() {
            hamburger.classList.remove('active');
            navMenu.classList.remove('active');
        });
    });
    
    // Close menu saat klik di luar
    document.addEventListener('click', function(e) {
        if (!nav.contains(e.target)) {
            hamburger.classList.remove('active');
            navMenu.classList.remove('active');
        }
    });
});
</script>

<!--tab visi misi-->
<script>
    function showTab(tabName, el) {
      const tabs = document.querySelectorAll('.tab');
      const contents = document.querySelectorAll('.tab-content');

      tabs.forEach(tab => tab.classList.remove('active'));
      contents.forEach(content => content.classList.remove('active'));

      document.querySelector(`#${tabName}`).classList.add('active');
      el.classList.add('active');
    }
  </script>
  <!--tutup visi misi-->

  <script>


// Fungsi untuk play video ketika tombol diklik
(function () {
  function getYoutubeId(url) {
    if (!url) return null;
    const patterns = [
      /youtu\.be\/([^?&/]+)/i,
      /youtube\.com\/watch\?v=([^?&/]+)/i,
      /youtube\.com\/embed\/([^?&/]+)/i,
      /youtube\.com\/shorts\/([^?&/]+)/i,
    ];
    for (const re of patterns) {
      const m = url.match(re);
      if (m && m[1]) return m[1];
    }
    return null;
  }

  let player = null;
  let apiLoaded = false;
  let apiLoading = false;

  function loadYouTubeAPI(cb) {
    if (apiLoaded) return cb();
    if (apiLoading) return;

    apiLoading = true;
    const tag = document.createElement("script");
    tag.src = "https://www.youtube.com/iframe_api";
    document.head.appendChild(tag);

    window.onYouTubeIframeAPIReady = function () {
      apiLoaded = true;
      apiLoading = false;
      cb();
    };
  }

  // ✅ SET SRC SAAT HALAMAN LOAD -> thumbnail muncul
  function setInitialThumbnail() {
    const iframe = document.getElementById("videoFrame");
    if (!iframe) return;

    const rawLink = iframe.getAttribute("data-youtube") || "";
    const videoId = getYoutubeId(rawLink);
    if (!videoId) return;

    const origin = encodeURIComponent(window.location.origin);
    const baseSrc = `https://www.youtube.com/embed/${videoId}?enablejsapi=1&rel=0&playsinline=1&origin=${origin}`;

    // set sekali saja
    if (!iframe.src || !iframe.src.includes(`/embed/${videoId}`)) {
      iframe.src = baseSrc; // <-- ini bikin thumbnail langsung tampil
    }
  }

  // ✅ panggil saat DOM siap
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", setInitialThumbnail);
  } else {
    setInitialThumbnail();
  }

  // ✅ fungsi tombol onclick
  window.playVideo = function () {
    const iframe = document.getElementById("videoFrame");
    if (!iframe) {
      console.error("iframe #videoFrame tidak ditemukan");
      return;
    }

    const rawLink = iframe.getAttribute("data-youtube") || "";
    const videoId = getYoutubeId(rawLink);
    if (!videoId) {
      console.error("Link YouTube tidak valid:", rawLink);
      return;
    }

    const origin = encodeURIComponent(window.location.origin);
    const baseSrc = `https://www.youtube.com/embed/${videoId}?enablejsapi=1&rel=0&playsinline=1&origin=${origin}`;

    // pastikan src sudah benar (biar player bisa attach)
    if (!iframe.src || !iframe.src.includes(`/embed/${videoId}`)) {
      iframe.src = baseSrc;
    }

    iframe.scrollIntoView({ behavior: "smooth", block: "center" });

    if (player && typeof player.playVideo === "function") {
      player.playVideo();
      return;
    }

    loadYouTubeAPI(function () {
      player = new YT.Player("videoFrame", {
        events: {
          onReady: function (e) {
            e.target.mute();      // autoplay policy
            e.target.playVideo(); // ✅ langsung play saat klik
          },
        },
      });
    });
  };
})();

//akhir vidio//

// Animasi ketika scroll
const observerOptions = {
    threshold: 0.2,
    rootMargin: '0px 0px -100px 0px'
};

const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.classList.add('show');
        }
    });
}, observerOptions);

// Observe semua element dengan class animasi
document.querySelectorAll('.fade-in, .fade-in-left, .zoom-in').forEach(el => {
    observer.observe(el);
});

</script>


<script>
document.addEventListener("DOMContentLoaded", () => {
    const cards = document.querySelectorAll(".stat-card");
    const numbers = document.querySelectorAll(".stat-number");

    // === OBSERVER UNTUK ANIMASI MASUK ===
    const observer = new IntersectionObserver(entries => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add("show");
            }
        });
    }, { threshold: 0.3 });

    cards.forEach(card => observer.observe(card));
// == ANIMASI YT == //
});
</script>

</html>
</body>