<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title><?= htmlspecialchars($video->title) ?> - Lustoria</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>

<body class="bg-black text-white font-sans">
    <!-- HEADER -->
    <header class="bg-gray-900 shadow-lg">
        <div class="max-w-7xl mx-auto px-4 py-4 flex justify-between items-center">
            <h1 class="text-2xl font-bold text-orange-500">Lustoria</h1>
            <button id="sidebar-toggle" class="lg:hidden text-yellow-400 focus:outline-none">
                <svg class="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
                </svg>
            </button>
            <nav class="hidden lg:flex gap-6">
                <a href="<?= site_url('user_dashboard') ?>" class="hover:text-yellow-400">Home</a>

                <!-- Desktop Category Dropdown -->
                <div class="relative dropdown">
                    <button class="hover:text-yellow-400 cursor-pointer flex items-center">
                        Kategori <svg class="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                        </svg>
                    </button>
                    <div class="dropdown-menu absolute hidden bg-gray-800 min-w-[200px] shadow-lg rounded-md mt-2 z-50">
                        <?php if (!empty($categories)): ?>
                            <?php foreach ($categories as $category): ?>
                                <a href="<?php echo site_url('category/' . $category->slug); ?>"
                                    class="block px-4 py-2 text-sm hover:bg-yellow-500 hover:text-black">
                                    <?php echo htmlspecialchars($category->name); ?>
                                </a>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <span class="block px-4 py-2 text-sm text-gray-400">Tidak ada kategori</span>
                        <?php endif; ?>
                    </div>
                </div>

                <?php if ($this->session->userdata('user_id')): ?>
                    <span class="text-yellow-400"><?= htmlspecialchars($this->session->userdata('username')) ?></span>
                    <a href="<?= site_url('user/profile') ?>" class="hover:text-yellow-400">Profile</a>
                    <a href="<?= site_url('auth/logout') ?>" class="hover:text-yellow-400">Logout</a>
                <?php else: ?>
                    <a href="<?= site_url('auth/login') ?>" class="hover:text-yellow-400">Login</a>
                    <a href="<?= site_url('auth/register') ?>" class="hover:text-yellow-400">Register</a>
                <?php endif; ?>
            </nav>
        </div>
    </header>

    <!-- SIDEBAR MOBILE -->
    <aside id="sidebar"
        class="fixed inset-y-0 left-0 bg-gray-900 w-64 transform -translate-x-full transition-transform duration-300 z-50 overflow-y-auto">
        <?php if ($this->session->userdata('user_id')): ?>
            <!-- LOGGED IN USER SIDEBAR -->
            <div class="p-4 flex flex-col items-center space-y-2 border-b border-gray-700 text-center">
                <img src="<?= htmlspecialchars($this->session->userdata('profile_image') ?? 'https://via.placeholder.com/80'); ?>"
                    alt="Profile Picture" class="w-16 h-16 rounded-full object-cover border-2 border-yellow-400">
                <div>
                    <p class="font-semibold"><?= htmlspecialchars($this->session->userdata('username')); ?></p>
                    <p class="text-gray-400 text-sm">Welcome back!</p>
                </div>
            </div>
            <nav class="p-4 space-y-2">
                <a href="<?= site_url('user_dashboard'); ?>"
                    class="block py-2 px-3 rounded hover:bg-yellow-500 hover:text-black">Home</a>
                <button id="category-toggle"
                    class="w-full text-left py-2 px-3 rounded hover:bg-yellow-500 hover:text-black">
                    Kategori ▼
                </button>
                <div id="category-submenu" class="hidden ml-4">
                    <?php if (!empty($categories)): ?>
                        <?php foreach ($categories as $category): ?>
                            <a href="<?= site_url('category/' . $category->slug); ?>"
                                class="block py-2 px-3 rounded hover:bg-yellow-500 hover:text-black">
                                <?= htmlspecialchars($category->name); ?>
                            </a>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <span class="block py-2 px-3 text-gray-400">Tidak ada kategori</span>
                    <?php endif; ?>
                </div>
                <a href="<?= site_url('user/profile'); ?>"
                    class="block py-2 px-3 rounded hover:bg-yellow-500 hover:text-black">Profile</a>
                <a href="<?= site_url('auth/logout'); ?>"
                    class="block py-2 px-3 rounded hover:bg-yellow-500 hover:text-black">Logout</a>
            </nav>
        <?php else: ?>
            <!-- GUEST USER SIDEBAR -->
            <div class="p-4 flex flex-col items-center space-y-2 border-b border-gray-700 text-center">
                <img src="https://via.placeholder.com/80"
                    alt="Guest" class="w-16 h-16 rounded-full object-cover border-2 border-yellow-400">
                <div>
                    <p class="font-semibold">Guest</p>
                    <p class="text-gray-400 text-sm">Welcome to Lustoria</p>
                </div>
            </div>
            <nav class="p-4 space-y-2">
                <a href="<?= site_url(''); ?>"
                    class="block py-2 px-3 rounded hover:bg-yellow-500 hover:text-black">Home</a>
                <button id="category-toggle"
                    class="w-full text-left py-2 px-3 rounded hover:bg-yellow-500 hover:text-black">
                    Kategori ▼
                </button>
                <div id="category-submenu" class="hidden ml-4">
                    <?php if (!empty($categories)): ?>
                        <?php foreach ($categories as $category): ?>
                            <a href="<?= site_url('category/' . $category->slug); ?>"
                                class="block py-2 px-3 rounded hover:bg-yellow-500 hover:text-black">
                                <?= htmlspecialchars($category->name); ?>
                            </a>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <span class="block py-2 px-3 text-gray-400">Tidak ada kategori</span>
                    <?php endif; ?>
                </div>
                <a href="<?= site_url('auth/login'); ?>"
                    class="block py-2 px-3 rounded hover:bg-yellow-500 hover:text-black">Login</a>
                <a href="<?= site_url('auth/register'); ?>"
                    class="block py-2 px-3 rounded hover:bg-yellow-500 hover:text-black">Register</a>
            </nav>
        <?php endif; ?>
    </aside>

    <!-- MAIN CONTENT -->
    <main class="max-w-7xl mx-auto px-4 py-6 lg:ml-64">
        <div class="grid lg:grid-cols-4 gap-6">
            <!-- VIDEO & DETAILS -->
            <div class="lg:col-span-3">
                <?php if (!empty($video->drive_link)): ?>
                    <!-- Google Drive Video Player -->
                    <div class="w-full rounded-lg shadow-lg bg-black">
                        <?php
                        // Extract file ID from Google Drive link (support multiple formats)
                        $file_id = '';
                        if (preg_match('/\/file\/d\/([a-zA-Z0-9-_]+)/', $video->drive_link, $matches)) {
                            $file_id = $matches[1];
                        } elseif (preg_match('/id=([a-zA-Z0-9-_]+)/', $video->drive_link, $matches)) {
                            $file_id = $matches[1];
                        }
                        ?>
                        <iframe src="https://drive.google.com/file/d/<?php echo $file_id; ?>/preview" width="100%"
                            height="500" allow="autoplay" class="rounded-lg" allowfullscreen>
                        </iframe>
                    </div>
                <?php else: ?>
                    <!-- Regular Video Player -->
                    <video class="w-full rounded-lg shadow-lg" controls preload="metadata"
                        poster="<?= base_url('uploads/thumbnails/' . ($video->thumbnail ?? 'default.jpg')) ?>">
                        <source src="<?= base_url('uploads/videos/' . $video->filename) ?>" type="video/mp4">
                        Your browser does not support the video tag.
                    </video>
                <?php endif; ?>

                <div class="mt-4 flex flex-col sm:flex-row sm:items-center sm:justify-between">
                    <h2 class="text-2xl font-bold text-yellow-700"><?= htmlspecialchars($video->title) ?></h2>
                </div>

                <p class="mt-2 text-gray-300"><?= nl2br(htmlspecialchars($video->description ?? '')) ?></p>

                <!-- LIKE -->
                <button id="like-button" class="mt-4 flex items-center space-x-2 px-2 py-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition 
                     <?= $user_liked ? 'text-white-600' : 'text-white-400' ?>">

                    <!-- Ikon Like (mirip YouTube) -->
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"
                        fill="<?= $user_liked ? 'currentColor' : 'none' ?>" stroke="currentColor" stroke-width="2"
                        class="w-6 h-6">
                        <path d="M14 9V5a3 3 0 00-3-3L5 9v12a3 3 0 003 3h6a3 3 0 003-3v-5l3-3V9h-6z" />
                    </svg>

                    <!-- Jumlah Like -->
                    <span id="like-count"><?= $likes_count ?></span>
                </button>


                <!-- COMMENTS -->
                <div class="mt-8">
                    <h3 class="text-xl font-bold mb-4">Comments</h3>
                    <?php if ($this->session->userdata('user_id')): ?>
                        <form id="comment-form">
                            <textarea id="comment-content" name="content" rows="4"
                                class="w-full p-3 rounded bg-gray-800 text-white" placeholder="Add a comment..."></textarea>
                            <input type="hidden" name="video_id" value="<?= $video->id ?>">
                            <button type="submit"
                                class="mt-3 bg-yellow-500 text-black px-4 py-2 rounded hover:bg-yellow-600 font-semibold">
                                Submit
                            </button>
                        </form>
                    <?php else: ?>
                        <p>Please <a href="<?= site_url('auth/login') ?>" class="text-yellow-400">log in</a> to comment.</p>
                    <?php endif; ?>

                    <div id="comments-list" class="mt-6 space-y-4">
                        <?php if (!empty($comments)): ?>
                            <?php foreach ($comments as $comment): ?>
                                <div class="bg-gray-800 p-3 rounded">
                                    <p class="text-sm text-yellow-400 font-semibold"><?= htmlspecialchars($comment->username) ?>
                                    </p>
                                    <p class="text-gray-300"><?= nl2br(htmlspecialchars($comment->content)) ?></p>
                                    <p class="text-xs text-gray-500"><?= date('Y-m-d H:i', strtotime($comment->created_at)) ?>
                                    </p>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <p class="text-gray-500">No comments yet.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <?php if (!empty($banners)): ?>
                <section class="mb-6 max-w-5xl mx-auto">
                    <?php $this->load->view('templates/banner_display', ['banners' => $banners]); ?>
                </section>
            <?php endif; ?>

            <!-- RELATED Videos -->
            <div>
                <h3 class="text-lg font-bold mb-4">Related videos</h3>
                <div class="grid grid-cols-2 gap-4">
                    <?php if (!empty($related_videos)): ?>
                        <?php foreach ($related_videos as $rv): ?>
                            <a href="<?= site_url('home/watch/' . $rv->id) ?>" class="group">
                                <div class="relative overflow-hidden rounded-lg">
                                    <img src="<?= base_url('uploads/thumbnails/' . ($rv->thumbnail ?? 'default.jpg')) ?>"
                                        alt="<?= htmlspecialchars($rv->title) ?>"
                                        class="w-full h-28 object-cover group-hover:scale-105 transition-transform duration-300">
                                    <span
                                        class="absolute top-2 left-2 bg-white text-black text-xs px-2 py-0.5 rounded">HD</span>
                                </div>
                                <p class="mt-1 text-sm text-yellow-400 font-semibold truncate">
                                    <?= htmlspecialchars($rv->title) ?>
                                </p>
                            </a>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="text-gray-500">No related videos found.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </main>

    <!-- FOOTER -->
    <footer class="bg-gray-900 py-4 text-center text-gray-500 mt-8">
        &copy; 2025 plowsky. All rights reserved.
    </footer>

    <script>
        document.getElementById('sidebar-toggle').addEventListener('click', function () {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('-translate-x-full'); // sembunyikan
            sidebar.classList.toggle('translate-x-0');     // tampilkan
        });
    </script>

    <script>
        // Pass CSRF token to JavaScript
        const csrfName = '<?php echo $this->security->get_csrf_token_name(); ?>';
        const csrfHash = '<?php echo $this->security->get_csrf_hash(); ?>';

        document.addEventListener('DOMContentLoaded', function () {
            const likeButton = document.getElementById('like-button');
            const likeText = document.getElementById('like-text');
            const likeCount = document.getElementById('like-count');
            const commentForm = document.getElementById('comment-form');
            const commentContent = document.getElementById('comment-content');
            const commentsList = document.getElementById('comments-list');
            const sidebarToggle = document.getElementById('sidebar-toggle');
            const sidebar = document.getElementById('sidebar');

            if (likeButton) {
                likeButton.addEventListener('click', function () {
                    const action = likeText.textContent.toLowerCase() === 'like' ? 'like' : 'unlike';
                    const videoId = <?php echo json_encode($video->id); ?>;

                    // Include CSRF token in POST body
                    const postData = new URLSearchParams({
                        video_id: videoId,
                        action: action
                    });
                    postData.append(csrfName, csrfHash);

                    fetch('<?php echo site_url('home/like_video'); ?>', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: postData.toString()
                    })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                likeCount.textContent = data.likes_count;
                                if (action === 'like') {
                                    likeText.textContent = 'Unlike';
                                    likeButton.classList.remove('bg-gray-700', 'text-white');
                                    likeButton.classList.add('bg-yellow-500', 'text-black');
                                } else {
                                    likeText.textContent = 'Like';
                                    likeButton.classList.remove('bg-yellow-500', 'text-black');
                                    likeButton.classList.add('bg-gray-700', 'text-white');
                                }
                            } else {
                                if (data.message === 'User not logged in') {
                                    alert('Please log in to like this video.');
                                    window.location.href = '<?php echo site_url('auth/login'); ?>';
                                } else {
                                    alert(data.message || 'Failed to update like status.');
                                }
                            }
                        })
                        .catch(() => alert('Failed to update like status.'));
                });
            }

            if (commentForm) {
                commentForm.addEventListener('submit', function (e) {
                    e.preventDefault();
                    const videoId = <?php echo json_encode($video->id); ?>;
                    const content = commentContent.value.trim();

                    if (!content) {
                        alert('Comment cannot be empty.');
                        return;
                    }

                    fetch('<?php echo site_url('home/post_comment'); ?>', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: new URLSearchParams({
                            video_id: videoId,
                            content: content
                        })
                    })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                alert(data.message);
                                commentContent.value = '';
                                // Optionally, refresh comments list or append new comment
                                location.reload();
                            } else {
                                alert(data.message || 'Failed to submit comment.');
                            }
                        })
                        .catch(() => alert('Failed to submit comment.'));
                });
            }

            // Toggle sidebar functionality
            if (sidebarToggle && sidebar) {
                sidebarToggle.addEventListener('click', () => {
                    if (sidebar.classList.contains('-translate-x-full')) {
                        sidebar.classList.remove('-translate-x-full');
                    } else {
                        sidebar.classList.add('-translate-x-full');
                    }
                });

                // Close sidebar when clicking outside on mobile
                document.addEventListener('click', (e) => {
                    if (window.innerWidth < 1024 && !sidebar.contains(e.target) && !sidebarToggle.contains(e.target)) {
                        sidebar.classList.add('-translate-x-full');
                    }
                });
            }
        });
    </script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const toggle = document.getElementById('category-toggle');
            const submenu = document.getElementById('category-submenu');
            if (toggle && submenu) {
                toggle.addEventListener('click', () => {
                    submenu.classList.toggle('hidden');
                });
            }
        });
    </script>
</body>

</html>