<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) { header("Location: login.php"); exit(); }
include '../db_connect.php';

// Handle Video Add
if (isset($_POST['add_video'])) {
    $title = $_POST['title'];
    $url = $_POST['url'];
    // Extract YouTube ID from URL (simple logic)
    parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
    $youtube_id = $my_array_of_vars['v'] ?? ''; 
    
    // If user pasted short url (youtu.be), handle differently or just ask for ID
    if(empty($youtube_id)) {
        // Fallback for short URLs
        $parts = explode('/', $url);
        $youtube_id = end($parts);
    }

    $conn->query("INSERT INTO videos (title, youtube_id) VALUES ('$title', '$youtube_id')");
    header("Location: videos.php");
}

// Handle Delete
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $conn->query("DELETE FROM videos WHERE id=$id");
    header("Location: videos.php");
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Manage Videos</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 p-6">
    <nav class="mb-6 flex gap-4">
        <a href="dashboard.php" class="text-blue-600 font-bold">← Back to Dashboard</a>
    </nav>

    <div class="bg-white p-6 rounded shadow-md mb-8">
        <h2 class="text-xl font-bold mb-4">Add YouTube Video</h2>
        <form method="POST" class="flex flex-col md:flex-row gap-4 items-end">
            <input type="text" name="title" placeholder="Video Title" required class="border p-2 rounded w-full md:w-1/3">
            <input type="text" name="url" placeholder="YouTube Link (e.g. https://www.youtube.com/watch?v=xxxxx)" required class="border p-2 rounded w-full md:w-1/3">
            <button type="submit" name="add_video" class="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700">Add Video</button>
        </form>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <?php
        $result = $conn->query("SELECT * FROM videos ORDER BY id DESC");
        while($row = $result->fetch_assoc()) {
            echo '<div class="bg-white p-4 rounded shadow">';
            echo '<iframe class="w-full h-40 rounded" src="https://www.youtube.com/embed/' . $row['youtube_id'] . '" allowfullscreen></iframe>';
            echo '<h3 class="font-bold mt-2">'.$row['title'].'</h3>';
            echo '<a href="videos.php?delete=' . $row['id'] . '" class="text-red-500 text-sm mt-2 block" onclick="return confirm(\'Remove video?\')">Delete</a>';
            echo '</div>';
        }
        ?>
    </div>
</body>
</html>