<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include 'includes/header.php';
include_once __DIR__ . '/admin/config/db.php';

/*
  Supports ALL:
  - youtube.com/watch?v=VIDEOID
  - youtu.be/VIDEOID
  - youtube.com/embed/VIDEOID
  - youtube.com/shorts/VIDEOID
  - youtube.com/live/VIDEOID   ✅ FIX
*/
function getYoutubeId($url) {

    $parsed = parse_url($url);

    // LIVE, SHORTS, EMBED → /live/ID, /shorts/ID, /embed/ID
    if (!empty($parsed['path'])) {
        $parts = explode('/', trim($parsed['path'], '/'));
        if (in_array($parts[0], ['live', 'shorts', 'embed']) && isset($parts[1])) {
            return $parts[1];
        }
    }

    // youtu.be short link
    if (isset($parsed['host']) && strpos($parsed['host'], 'youtu.be') !== false) {
        return trim($parsed['path'], '/');
    }

    // watch?v=ID
    if (!empty($parsed['query'])) {
        parse_str($parsed['query'], $vars);
        if (isset($vars['v'])) {
            return $vars['v'];
        }
    }

    return '';
}

$q = mysqli_query($conn, "SELECT * FROM videos ORDER BY id DESC ");

if (!$q) {
    die("Database Error: " . mysqli_error($conn));
}
?>

<!DOCTYPE html>
<html lang="hi">
<head>
<meta charset="UTF-8">
<title>वीडियो</title>

<style>
.video-section{
    width:92%;
    margin:50px auto;
}
.video-section h2{
    font-size:32px;
    margin-bottom:30px;
    font-weight:700;
    border-left:6px solid #ff7a18;
    padding-left:15px;
}
.video-grid{
    display:grid;
    grid-template-columns:repeat(3,1fr);
    gap:30px;
}
.video-card{
    background:#fff;
    border-radius:12px;
    overflow:hidden;
    box-shadow:0 10px 30px rgba(0,0,0,.08);
}
.video-card iframe{
    width:100%;
    height:280px;
    border:none;
}
.video-card h4{
    padding:15px;
    margin:0;
    font-size:18px;
    font-weight:600;
}
@media(max-width:1024px){
    .video-grid{grid-template-columns:repeat(2,1fr);}
}
@media(max-width:600px){
    .video-grid{grid-template-columns:1fr;}
    .video-card iframe{height:220px;}
}
</style>
</head>

<body>

<div class="video-section">
  <h2>नवीनतम वीडियो</h2>

  <div class="video-grid">
    <?php while ($row = mysqli_fetch_assoc($q)) { 
        $videoId = getYoutubeId($row['youtube_link']);
        if ($videoId == '') continue;
    ?>
      <div class="video-card">
        <iframe
          src="https://www.youtube.com/embed/<?php echo htmlspecialchars($videoId); ?>"
          allowfullscreen>
        </iframe>
        <h4><?php echo htmlspecialchars($row['title']); ?></h4>
      </div>
    <?php } ?>
  </div>
</div>

<?php include 'includes/footer.php'; ?>
</body>
</html>
