<?php
session_start();
include "../include/config.php";

if (!isset($_SESSION['studentid'])) {
    header("location:../index.php");
    exit;
}

$id = intval($_GET['id']);
$query = mysqli_query($conn, "SELECT * FROM videos WHERE id='$id'");
$row = mysqli_fetch_array($query);

if (!$row) {
    echo "Video not found!";
    exit;
}

// Convert YouTube/Vimeo link to embed link
$video_link = $row['video_link'];

if (strpos($video_link, 'youtube.com') !== false || strpos($video_link, 'youtu.be') !== false) {
    // Extract YouTube video ID
    if (preg_match("/v=([a-zA-Z0-9_-]+)/", $video_link, $matches) ||
        preg_match("/youtu\.be\/([a-zA-Z0-9_-]+)/", $video_link, $matches)) {
        $video_id = $matches[1];
        $video_link = "https://www.youtube.com/embed/$video_id";
    }
} elseif (strpos($video_link, 'vimeo.com') !== false) {
    // Extract Vimeo video ID
    if (preg_match("/vimeo\.com\/(\d+)/", $video_link, $matches)) {
        $video_id = $matches[1];
        $video_link = "https://player.vimeo.com/video/$video_id";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $row['title']; ?></title>
<link rel="stylesheet" href="res/bootstrap@5.2.0.min.css">
</head>
<body>
<?php include "../include/nav.php"; ?>
<div class="content">
<div class="container mt-5">
    <h3><?php echo $row['title']; ?></h3>
    <p><small>Uploaded on <?php echo date("M d, Y", strtotime($row['date'])); ?></small></p>

    <div class="embed-responsive embed-responsive-16by9">
        <iframe class="embed-responsive-item" src="<?php echo $video_link; ?>" frameborder="0" allowfullscreen style="width:100%; height:500px;"></iframe>
    </div>
</div>
</div>

</body>
</html>
