<?php include 'koneksi.php';
session_start();
if (!isset($_SESSION['login_admin'])) {
    header('Location: dashboard.php');
    exit;
}

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'];
}

// Get the gallery ID from URL parameter
$id_post = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($id_post <= 0) {
    echo "<script>alert('ID galeri tidak valid'); window.location.href='manage_galeri.php';</script>";
    exit;
}

// Fetch gallery details from database
$query = "SELECT * FROM tb_post WHERE id_post = $id_post";
$result = mysqli_query($host, $query);

if (!$result || mysqli_num_rows($result) == 0) {
    echo "<script>alert('Galeri tidak ditemukan'); window.location.href='manage_galeri.php';</script>";
    exit;
}

$row = mysqli_fetch_assoc($result);
$judul_db = htmlspecialchars($row['judul_post']);
$deskripsi = htmlspecialchars($row['deskripsi']);
$tanggal = date('d M Y', strtotime($row['tanggal']));
$jenis = $row['jenis'];
$gambar = htmlspecialchars($row['gambar']);
$iframe = $row['iframe'];

if ($jenis === 'video' && !empty($iframe)) {
    $iframeContent = $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);
        $judul = htmlspecialchars($data['title']);
    } else {
        $judul = $judul_db;
    }
} else {
    $judul = $judul_db;
}
?>
<!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><?php echo $judul; ?> | SMK Budiniah 2 Admin</title>
    <link rel="stylesheet" href="style_admin.css">
    <link rel="stylesheet" href="footer.css">
<style>
    *{
        margin: 0;
        padding: 0;
        scroll-behavior: smooth;
    }

    body{
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background: #ffffff;
    }
    
    .galeri-detail {
        width: 100%;
        background: #eef5ff;         
        padding: 60px 0 120px;          
        text-align: center;
    }

    .galeri-detail h1 {
        font-size: 40px;
        font-weight: bold;
        color: #2a2a2a;
        text-transform: capitalize;
    }

    .detail-galeri {
        margin: -80px auto 40px auto;    
        background: #fff;
        padding: 30px;
        border-radius: 15px;
        max-width: 900px;

        display: grid;
        gap: 20px;

        box-shadow: 0 8px 20px rgba(0,0,0,0.12);
        position: relative;
        z-index: 10;
    }

    .bagian-teks {
        background: #fff;
        border-radius: 10px;
        line-height: 1.6;
    }

    .bagian-teks h3 {
        margin-bottom: 15px;
        color: #333;
    }

    .bagian-teks p {
        margin-bottom: 15px;
        text-align: justify;
    }

    .bagian-teks .tanggal {
        font-size: 14px;
        color: #666;
        margin-bottom: 20px;
    }

    .bagian-media {
        text-align: center;
        margin-bottom: 20px;
    }

    .bagian-media img {
        max-width: 100%;
        height: auto;
        border-radius: 10px;
    }

    .video-container {
        position: relative;
        padding-bottom: 56.25%;
        height: 0;
        overflow: hidden;
        border-radius: 10px;
    }

    .video-container iframe {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }

    .button-kembali {
        text-align: center;
        margin-top: 30px;
    }

    .button-kembali a {
        display: inline-block;
        padding: 10px 20px;
        background: linear-gradient(135deg, #0037fd, #5b8cffff);
        color: #fff;
        text-decoration: none;
        border-radius: 5px;
        font-weight: bold;
        transition: all 0.3s ease;
    }

    .button-kembali a:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0,55,253,0.4);
    }
    
    @media (max-width: 768px) {
        .detail-galeri {
            grid-template-columns: 1fr;
            margin: -50px 20px 20px 20px;
            padding: 20px;
        }
    }
</style>
</head>
<body>

<div class="galeri-detail">
    <h1><?php echo $judul; ?></h1>
</div>
<div class="detail-galeri">
    <div class="bagian-teks">
        <div class="tanggal">Tanggal: <?php echo $tanggal; ?></div>

        <?php if ($jenis === 'foto' && !empty($gambar)): ?>
        <div class="bagian-media">
            <img src="upload/<?php echo $gambar; ?>" alt="<?php echo $judul; ?>">
        </div>
        <?php elseif ($jenis === 'video' && !empty($iframe)): ?>
        <div class="bagian-media">
            <div class="video-container">
                <?php
                $iframeContent = $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) {
                    // Extract video ID and create embed URL
                    $videoId = extractYouTubeVideoId($url);
                    if ($videoId) {
                        $embedUrl = "https://www.youtube.com/embed/" . $videoId;
                        echo '<iframe width="560" height="315" src="' . htmlspecialchars($embedUrl) . '" title="' . htmlspecialchars($judul) . '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>';
                    }
                }
                ?>
            </div>
        </div>
        <?php endif; ?>

        <h3>Deskripsi Galeri</h3>
        <p><?php echo nl2br($deskripsi); ?></p>

        <div class="button-kembali">
            <a href="manage_galeri.php">← Kembali ke Manage Galeri</a>
        </div>
    </div>
</div>
</body>
</html>

