<?php
session_start();
require_once '../config/db.php';
require_once 'auth.php';

$pageTitle = 'Galeri Video';
$activePage = 'gallery_videos';
$msg = '';

if (isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM gallery_videos WHERE id=?")->execute([$_GET['delete']]);
    $msg = adminAlert('Video berhasil dihapus.');
}
if (isset($_GET['toggle'])) {
    $pdo->prepare("UPDATE gallery_videos SET is_active = 1 - is_active WHERE id=?")->execute([$_GET['toggle']]);
    header('Location: gallery-videos.php'); exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id']??null;
    $title = trim($_POST['title']??'');
    $desc = trim($_POST['description']??'');
    $url = trim($_POST['youtube_url']??'');
    // Convert watch URL to embed
    if (preg_match('/watch\?v=([a-zA-Z0-9_-]+)/', $url, $m)) $url = 'https://www.youtube.com/embed/'.$m[1];
    elseif (preg_match('/youtu\.be\/([a-zA-Z0-9_-]+)/', $url, $m)) $url = 'https://www.youtube.com/embed/'.$m[1];
    $sort = (int)($_POST['sort_order']??0);
    $active = isset($_POST['is_active']) ? 1 : 0;
    $existing_thumb = $_POST['existing_thumb']??'';
    $thumb = $existing_thumb;
    if (!empty($_FILES['thumbnail']['name'])) {
        $uploaded = uploadFile($_FILES['thumbnail'], 'assets/images/gallery');
        if ($uploaded) $thumb = $uploaded;
    }
    if ($id) {
        $pdo->prepare("UPDATE gallery_videos SET title=?,description=?,youtube_url=?,thumbnail=?,sort_order=?,is_active=? WHERE id=?")
            ->execute([$title,$desc,$url,$thumb,$sort,$active,$id]);
        $msg = adminAlert('Video berhasil diperbarui.');
    } else {
        $pdo->prepare("INSERT INTO gallery_videos (title,description,youtube_url,thumbnail,sort_order,is_active) VALUES (?,?,?,?,?,?)")
            ->execute([$title,$desc,$url,$thumb,$sort,$active]);
        $msg = adminAlert('Video berhasil ditambahkan.');
    }
}

$editItem = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM gallery_videos WHERE id=?");
    $stmt->execute([$_GET['edit']]);
    $editItem = $stmt->fetch();
}

$items = $pdo->query("SELECT * FROM gallery_videos ORDER BY sort_order ASC")->fetchAll();
include 'partials/header.php';
?>
<?= $msg ?>
<div class="row g-4">
    <div class="col-lg-4">
        <div class="card">
            <div class="card-header"><?= $editItem ? 'Edit Video' : 'Tambah Video' ?></div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <?php if ($editItem): ?>
                        <input type="hidden" name="id" value="<?= $editItem['id'] ?>">
                        <input type="hidden" name="existing_thumb" value="<?= $editItem['thumbnail'] ?>">
                    <?php endif; ?>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Judul <span class="text-danger">*</span></label>
                        <input type="text" name="title" class="form-control" required value="<?= htmlspecialchars($editItem['title']??'') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Deskripsi</label>
                        <textarea name="description" class="form-control" rows="2"><?= htmlspecialchars($editItem['description']??'') ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">URL YouTube</label>
                        <input type="url" name="youtube_url" class="form-control" placeholder="https://www.youtube.com/watch?v=..." value="<?= htmlspecialchars($editItem['youtube_url']??'') ?>">
                        <div class="form-text">Masukkan link YouTube (watch atau embed)</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Thumbnail</label>
                        <input type="file" name="thumbnail" class="form-control" accept="image/*">
                        <?php if ($editItem && $editItem['thumbnail']): ?>
                            <img src="../<?= $editItem['thumbnail'] ?>" class="mt-2 rounded" style="height:60px;object-fit:cover;" onerror="this.style.display='none'">
                        <?php endif; ?>
                    </div>
                    <div class="row g-2 mb-3">
                        <div class="col"><label class="form-label fw-semibold">Urutan</label><input type="number" name="sort_order" class="form-control" value="<?= $editItem['sort_order']??0 ?>"></div>
                        <div class="col d-flex align-items-end pb-1"><div class="form-check"><input class="form-check-input" type="checkbox" name="is_active" id="ia" <?= ($editItem['is_active']??1)?'checked':'' ?>><label class="form-check-label fw-semibold" for="ia">Aktif</label></div></div>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-dark"><?= $editItem ? 'Update' : 'Tambah' ?></button>
                        <?php if ($editItem): ?><a href="gallery-videos.php" class="btn btn-outline-secondary">Batal</a><?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">Daftar Video (<?= count($items) ?>)</div>
            <div class="table-responsive">
                <table class="table mb-0 align-middle">
                    <thead class="table-light"><tr><th>Thumbnail</th><th>Judul</th><th>URL</th><th>Status</th><th>Aksi</th></tr></thead>
                    <tbody>
                    <?php foreach ($items as $item): ?>
                        <tr>
                            <td><img src="../<?= $item['thumbnail'] ?>" style="width:80px;height:50px;object-fit:cover;border-radius:4px;" onerror="this.src='https://via.placeholder.com/80x50?text=Video'"></td>
                            <td><div class="fw-semibold"><?= htmlspecialchars($item['title']) ?></div></td>
                            <td><small class="text-muted text-truncate d-block" style="max-width:150px;"><?= htmlspecialchars($item['youtube_url']??'-') ?></small></td>
                            <td><a href="?toggle=<?= $item['id'] ?>" class="badge <?= $item['is_active'] ? 'badge-active' : 'badge-inactive' ?> text-decoration-none"><?= $item['is_active'] ? 'Aktif' : 'Off' ?></a></td>
                            <td>
                                <a href="?edit=<?= $item['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-pencil"></i></a>
                                <a href="?delete=<?= $item['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Hapus?')"><i class="bi bi-trash"></i></a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php include 'partials/footer.php'; ?>
