<?php
include 'koneksi.php';

function limit_words($text, $limit) {
    $words = explode(' ', $text);
    if (count($words) > $limit) {
        return implode(' ', array_slice($words, 0, $limit)) . '...';
    }
    return $text;
}

function extractYouTubeVideoId($url) {
    $parsedUrl = parse_url($url);
    $host = $parsedUrl['host'] ?? '';
    $path = $parsedUrl['path'] ?? '';

    if (strpos($host, 'youtube.com') !== false) {
        // Handle youtube.com URLs
        if (isset($parsedUrl['query'])) {
            parse_str($parsedUrl['query'], $query);
            return $query['v'] ?? '';
        }
        // Handle embed URLs like https://www.youtube.com/embed/VIDEOID
        if (preg_match('#/embed/([a-zA-Z0-9_-]+)#', $path, $matches)) {
            return $matches[1];
        }
    } elseif (strpos($host, 'youtu.be') !== false) {
        // Handle youtu.be URLs like https://youtu.be/VIDEOID
        return ltrim($path, '/');
    }

    return '';
}

function getYouTubeData($url) {
    // Extract video ID from URL
    $videoId = extractYouTubeVideoId($url);
    if (!$videoId) return ['title' => 'Unknown Title', 'upload_date' => 'Unknown Date'];

    // Use YouTube Data API v3 to get video details (requires API key)
    $apiKey = 'YOUR_YOUTUBE_API_KEY'; // Replace with your actual API key
    $apiUrl = "https://www.googleapis.com/youtube/v3/videos?id=$videoId&key=$apiKey&part=snippet";
    $json = @file_get_contents($apiUrl);
    if ($json) {
        $data = json_decode($json, true);
        if (isset($data['items'][0]['snippet'])) {
            $snippet = $data['items'][0]['snippet'];
            return [
                'title' => $snippet['title'] ?? 'Unknown Title',
                'upload_date' => $snippet['publishedAt'] ?? 'Unknown Date'
            ];
        }
    }

    // Fallback to oEmbed for title if Data API fails
    $oembedUrl = "https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=$videoId&format=json";
    $json = @file_get_contents($oembedUrl);
    if ($json) {
        $data = json_decode($json, true);
        return [
            'title' => $data['title'] ?? 'Unknown Title',
            'upload_date' => 'Unknown Date'
        ];
    }
    return ['title' => 'Unknown Title', 'upload_date' => 'Unknown Date'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head><link rel="icon" href="upload/bn2.png" type="image/png">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Galeri | Smk Budiniah 2</title>
    <style>
        body{
            margin: 0;
            font-family: 'Times New Roman', Times, serif;
        }
        .hero-caption{
            display: flex;
            flex-direction: column;
            align-items: left;
            justify-content: left;
            text-align: left;
            margin-top: 10%;
            margin-bottom: 5%;
            padding-left: 5%;
            padding-right: 5%;
        }
        .hero-caption h1{
            margin: 0 0 20px 0;
            font-size: 60px;
            font-weight: 700;
        }
        .hero-caption p{
            margin: 0 0 20px 0;
            max-width: 500px;
            line-height: 1.6;
            font-weight: 500;
        }
        .card-galeri {
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            justify-content: center;
            align-items: center;
            gap: 20px;
            padding: 20px 0;
        }
        .video-item {
            flex: 0 0 400px;
            scroll-snap-align: start;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            background: white;
        }
        .video-item iframe {
            width: 100%;
            height: 225px;
            border: none;
        }
        .video-info {
            padding: 10px;
            text-align: center;
        }
        .video-date {
            color: #0f62fe;
            font-size: 14px;
            margin: 0 0 5px 0;
            font-weight: bold;
            text-align: left;
            justify-items: left;
            align-items: left;
        }
        .video-title {
            font-size: 18px;
            margin: 0;
            text-align: left;
            align-items: left;
            justify-items: left;
            color: #333;
        }
    </style>
</head>
<body>
    <?php require 'navbar.php'; ?>
    <div class="hero-caption">
        <h1>Galeri</h1>
        <p>Sebuah dokumentasi dari berbagai jenis kegiatan yang dilakukan di Sekolah kami.</p>
    </div>
    <div class="card-galeri">
        <?php
        $query = "SELECT * FROM tb_post WHERE kategori='post' ORDER BY tanggal DESC";
        $result = mysqli_query($host,$query);
        if($result && mysqli_num_rows($result) > 0){
            while ($row = mysqli_fetch_assoc($result)){
                if ($row['jenis'] === 'video' && !empty($row['iframe'])) {
                    $iframeContent = $row['iframe'];
                    if (strpos($iframeContent, '<iframe') === 0) {
                        // It's a full iframe tag, extract src
                        preg_match('/src="([^"]+)"/', $iframeContent, $matches);
                        $url = $matches[1] ?? '';
                    } else {
                        $url = $iframeContent;
                    }
                    if ($url) {
                        $data = getYouTubeData($url);
                        $title = $data['title'];
                        $tanggal = date('d M Y', strtotime($row['tanggal']));
                        $fullTitle = htmlspecialchars($title . ' - ' . $tanggal);
                        // Extract video ID and create embed URL
                        $videoId = extractYouTubeVideoId($url);
                        if ($videoId) {
                            $embedUrl = "https://www.youtube.com/embed/" . $videoId;
                            echo '<div class="video-item">';
                            echo '<iframe width="560" height="315" src="' . htmlspecialchars($embedUrl) . '" title="' . $fullTitle . '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>';
                            echo '<div class="video-info">';
                            echo '<p class="video-date">'. "-" . $tanggal . "-" . '</p>';
                            echo '<h3 class="video-title">' . htmlspecialchars($title) . '</h3>';
                            echo '</div>';
                            echo '</div>';
                        }
                    }
                }
            }
        } else {
            echo '<p>Belum ada dokumentasi tersedia.</p>';
        }
        ?>
    </div>
    <?php require 'footer.php'; ?>
</body>
</html>
