<?php
session_start();

if (empty($_SESSION['namauser']) && empty($_SESSION['passuser'])) {
    echo "<link href='../../css/style_login.css' rel='stylesheet' type='text/css' />
          <div id='login'><h1 class='fail'>Untuk mengakses modul, Anda harus login dulu.</h1>
          <p class='fail'><a href='../../index.php'>LOGIN</a></p></div>";
    exit();
}

include "../../../config/koneksi.php";
include "../../../config/fungsi_seo.php";

$module = $_GET['module'] ?? '';
$act    = $_GET['act'] ?? '';

// Helper Function: Ekstrak ID Video YouTube dari berbagai format URL
function getYoutubeId($url) {
    $url = trim($url);
    if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/\s]{11})%i', $url, $match)) {
        return $match[1];
    }
    // Jika user menginput ID secara langsung tanpa URL
    if (strlen($url) == 11) {
        return $url;
    }
    return $url;
}

// ==========================================
// ACTION: HAPUS VIDEO
// ==========================================
if ($module == 'video' && $act == 'hapus') {
    $id = mysqli_real_escape_string($konek, $_GET['id'] ?? '');
    mysqli_query($konek, "DELETE FROM video WHERE id_video='$id'");

    header("location:../../media.php?module=" . $module);
    exit();
}

// ==========================================
// ACTION: INPUT VIDEO (TAMBAH)
// ==========================================
elseif ($module == 'video' && $act == 'input') {
    $judul_video  = mysqli_real_escape_string($konek, $_POST['judul_video'] ?? '');
    $video_seo    = seo_title($_POST['judul_video'] ?? '');
    $raw_youtube  = $_POST['link_youtube'] ?? '';
    $link_youtube = mysqli_real_escape_string($konek, getYoutubeId($raw_youtube));

    mysqli_query($konek, "INSERT INTO video(judul_video, video_seo, link_youtube) 
                          VALUES('$judul_video', '$video_seo', '$link_youtube')");

    header("location:../../media.php?module=" . $module);
    exit();
}

// ==========================================
// ACTION: UPDATE VIDEO (EDIT)
// ==========================================
elseif ($module == 'video' && $act == 'update') {
    $id           = mysqli_real_escape_string($konek, $_POST['id'] ?? '');
    $judul_video  = mysqli_real_escape_string($konek, $_POST['judul_video'] ?? '');
    $video_seo    = seo_title($_POST['judul_video'] ?? '');
    $raw_youtube  = $_POST['link_youtube'] ?? '';
    $link_youtube = mysqli_real_escape_string($konek, getYoutubeId($raw_youtube));

    mysqli_query($konek, "UPDATE video SET 
                            judul_video  = '$judul_video', 
                            video_seo    = '$video_seo', 
                            link_youtube = '$link_youtube' 
                          WHERE id_video = '$id'");

    header("location:../../media.php?module=" . $module);
    exit();
}
?>