<?php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';
require_login();

// Admin only
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    die("Access Denied. Admins only.");
}

$success = '';
$error   = '';

// ── ACTIONS ──
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Delete video
    if ($action === 'delete_video') {
        $vid_id = $_POST['video_id'] ?? '';
        try {
            $stmt = $pdo->prepare("SELECT video_url, thumbnail_url FROM videos WHERE id = ?");
            $stmt->execute([$vid_id]);
            $vid = $stmt->fetch();
            if ($vid) {
                if ($vid['video_url'] && file_exists(__DIR__ . '/' . $vid['video_url'])) unlink(__DIR__ . '/' . $vid['video_url']);
                if ($vid['thumbnail_url'] && file_exists(__DIR__ . '/' . $vid['thumbnail_url'])) unlink(__DIR__ . '/' . $vid['thumbnail_url']);
                $pdo->prepare("DELETE FROM videos WHERE id = ?")->execute([$vid_id]);
                $success = 'Video deleted successfully.';
            }
        } catch (PDOException $e) {
            $error = 'Failed to delete video.';
        }
    }

    // Edit video
    elseif ($action === 'edit_video') {
        $vid_id     = $_POST['video_id'] ?? '';
        $new_title  = trim($_POST['edit_title'] ?? '');
        $new_price  = floatval($_POST['edit_price'] ?? 0);
        $new_status = in_array($_POST['edit_status'] ?? '', ['active', 'inactive']) ? $_POST['edit_status'] : 'active';
        $new_fake   = intval($_POST['edit_fake_views'] ?? 0);
        $new_desc   = trim($_POST['edit_description'] ?? '');

        if (!empty($vid_id) && !empty($new_title)) {
            try {
                $pdo->prepare("UPDATE videos SET title = ?, price = ?, status = ?, fake_views = ?, description = ? WHERE id = ?")
                    ->execute([$new_title, $new_price, $new_status, $new_fake, $new_desc, $vid_id]);
                $success = 'Video updated successfully.';
            } catch (PDOException $e) {
                $error = 'Failed to update video: ' . $e->getMessage();
            }
        }
    }

    // Bulk delete
    elseif ($action === 'bulk_delete') {
        $ids = $_POST['selected_ids'] ?? [];
        if (!empty($ids)) {
            $deleted = 0;
            foreach ($ids as $vid_id) {
                try {
                    $stmt = $pdo->prepare("SELECT video_url, thumbnail_url FROM videos WHERE id = ?");
                    $stmt->execute([$vid_id]);
                    $vid = $stmt->fetch();
                    if ($vid) {
                        if ($vid['video_url'] && file_exists(__DIR__ . '/' . $vid['video_url'])) unlink(__DIR__ . '/' . $vid['video_url']);
                        if ($vid['thumbnail_url'] && file_exists(__DIR__ . '/' . $vid['thumbnail_url'])) unlink(__DIR__ . '/' . $vid['thumbnail_url']);
                        $pdo->prepare("DELETE FROM videos WHERE id = ?")->execute([$vid_id]);
                        $deleted++;
                    }
                } catch (PDOException $e) {}
            }
            $success = "$deleted video(s) deleted.";
        }
    }
}

// ── FILTERS ──
$search   = trim($_GET['search'] ?? '');
$filterBy = $_GET['filter_by'] ?? 'all';
$sortBy   = $_GET['sort'] ?? 'newest';
$page     = max(1, intval($_GET['page'] ?? 1));
$perPage  = 12;

// Build query
$where  = [];
$params = [];

if (!empty($search)) {
    $where[] = "(v.title LIKE ? OR u.name LIKE ? OR u.email LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if ($filterBy === 'active')   { $where[] = "v.status = 'active'"; }
if ($filterBy === 'inactive') { $where[] = "v.status = 'inactive'"; }

$whereSQL = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

$orderMap = [
    'newest'    => 'v.created_at DESC',
    'oldest'    => 'v.created_at ASC',
    'title'     => 'v.title ASC',
    'price_hi'  => 'v.price DESC',
    'price_lo'  => 'v.price ASC',
    'views'     => 'v.views DESC',
];
$orderSQL = $orderMap[$sortBy] ?? 'v.created_at DESC';

// Count total
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM videos v LEFT JOIN users u ON v.user_id = u.id $whereSQL");
$countStmt->execute($params);
$totalVideos = $countStmt->fetchColumn();
$totalPages  = max(1, ceil($totalVideos / $perPage));
$offset      = ($page - 1) * $perPage;

// Fetch
$sql = "SELECT v.*, u.name as uploader_name, u.email as uploader_email 
        FROM videos v 
        LEFT JOIN users u ON v.user_id = u.id 
        $whereSQL 
        ORDER BY $orderSQL 
        LIMIT $perPage OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$videos = $stmt->fetchAll();

// Stats
$totalAll    = $pdo->query("SELECT COUNT(*) FROM videos")->fetchColumn();
$totalActive = $pdo->query("SELECT COUNT(*) FROM videos WHERE status='active'")->fetchColumn();
$totalInactive = $pdo->query("SELECT COUNT(*) FROM videos WHERE status='inactive'")->fetchColumn();
$totalSize   = 0;
$sizeStmt    = $pdo->query("SELECT video_url FROM videos WHERE video_url IS NOT NULL AND video_url != ''");
while ($row = $sizeStmt->fetch()) {
    $fp = __DIR__ . '/' . $row['video_url'];
    if (file_exists($fp)) $totalSize += filesize($fp);
}

function formatBytes($bytes) {
    if ($bytes >= 1073741824) return number_format($bytes / 1073741824, 1) . ' GB';
    if ($bytes >= 1048576)    return number_format($bytes / 1048576, 1) . ' MB';
    return number_format($bytes / 1024, 1) . ' KB';
}

$pageTitle = "All Uploads - Admin";
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<?php include 'includes/head.php'; ?>
<style>
    .video-card { border-radius: 16px; overflow: hidden; transition: all 0.3s; border: 1px solid #e5e7eb; }
    .video-card:hover { box-shadow: 0 8px 24px rgba(0,0,0,0.08); transform: translateY(-2px); }
    .video-thumb-wrap {
        position: relative; padding-top: 56.25%; background: #1a1a2e; overflow: hidden;
    }
    .video-thumb-wrap img, .video-thumb-wrap video {
        position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover;
    }
    .video-overlay {
        position: absolute; inset: 0; background: rgba(0,0,0,0.4);
        display: flex; align-items: center; justify-content: center;
        opacity: 0; transition: opacity 0.3s; z-index: 2;
    }
    .video-thumb-wrap:hover .video-overlay { opacity: 1; }
    .play-btn {
        width: 52px; height: 52px; border-radius: 50%;
        background: rgba(255,255,255,0.95); border: none;
        display: flex; align-items: center; justify-content: center;
        font-size: 1.4rem; color: #6366f1; cursor: pointer;
        transition: transform 0.2s;
    }
    .play-btn:hover { transform: scale(1.1); }
    .url-box { font-size: 11px; background: #f8fafc; border-radius: 8px; border: 1px solid #e2e8f0; padding: 6px 10px; cursor: pointer; }
    .url-box:hover { background: #eef2ff; border-color: #6366f1; }
    .stat-card { border-radius: 14px; padding: 20px; border: 1px solid #e5e7eb; }
    .badge-status-active { background: #dcfce7; color: #15803d; }
    .badge-status-inactive { background: #fef2f2; color: #b91c1c; }
    .filter-btn.active { background: #6366f1; color: white; }

    /* Video Player Modal */
    #videoPlayerModal .modal-content { background: #000; border: none; }
    #videoPlayerModal video { width: 100%; max-height: 80vh; }
</style>
<body>
    <?php include 'includes/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'includes/header.php'; ?>
        <div class="dashboard-main-body">

            <!-- Header -->
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                <div>
                    <h6 class="fw-bold mb-4">All User Uploads</h6>
                    <p class="text-sm text-secondary-light mb-0">Manage all videos uploaded across the platform</p>
                </div>
                <ul class="d-flex align-items-center gap-2">
                    <li class="fw-medium">
                        <a href="<?= SITE_URL ?>/dashboard" class="d-flex align-items-center gap-1 hover-text-primary">
                            <iconify-icon icon="solar:home-smile-angle-outline" class="icon text-lg"></iconify-icon> Dashboard
                        </a>
                    </li>
                    <li>-</li>
                    <li class="fw-medium">All Uploads</li>
                </ul>
            </div>

            <!-- Flash messages -->
            <?php if ($success || $error): ?>
            <div class="alert alert-<?= $success ? 'success' : 'danger' ?> alert-dismissible fade show radius-12 mb-24">
                <iconify-icon icon="<?= $success ? 'lucide:check-circle' : 'lucide:alert-circle' ?>" class="me-8"></iconify-icon>
                <?= htmlspecialchars($success ?: $error) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php endif; ?>

            <!-- Stats Cards -->
            <div class="row g-3 mb-24">
                <div class="col-sm-6 col-lg-3">
                    <div class="stat-card d-flex align-items-center gap-16" style="background: linear-gradient(135deg, #eef2ff, #e0e7ff);">
                        <div class="w-48-px h-48-px radius-12 d-flex justify-content-center align-items-center text-white" style="background:#6366f1">
                            <iconify-icon icon="solar:video-library-bold-duotone" class="text-2xl"></iconify-icon>
                        </div>
                        <div>
                            <p class="text-xs text-secondary-light fw-medium mb-4">Total Videos</p>
                            <h5 class="fw-bold mb-0"><?= number_format($totalAll) ?></h5>
                        </div>
                    </div>
                </div>
                <div class="col-sm-6 col-lg-3">
                    <div class="stat-card d-flex align-items-center gap-16" style="background: linear-gradient(135deg, #f0fdf4, #dcfce7);">
                        <div class="w-48-px h-48-px radius-12 d-flex justify-content-center align-items-center text-white" style="background:#16a34a">
                            <iconify-icon icon="solar:check-circle-bold-duotone" class="text-2xl"></iconify-icon>
                        </div>
                        <div>
                            <p class="text-xs text-secondary-light fw-medium mb-4">Active</p>
                            <h5 class="fw-bold mb-0"><?= number_format($totalActive) ?></h5>
                        </div>
                    </div>
                </div>
                <div class="col-sm-6 col-lg-3">
                    <div class="stat-card d-flex align-items-center gap-16" style="background: linear-gradient(135deg, #fef2f2, #fecaca);">
                        <div class="w-48-px h-48-px radius-12 d-flex justify-content-center align-items-center text-white" style="background:#dc2626">
                            <iconify-icon icon="solar:close-circle-bold-duotone" class="text-2xl"></iconify-icon>
                        </div>
                        <div>
                            <p class="text-xs text-secondary-light fw-medium mb-4">Inactive</p>
                            <h5 class="fw-bold mb-0"><?= number_format($totalInactive) ?></h5>
                        </div>
                    </div>
                </div>
                <div class="col-sm-6 col-lg-3">
                    <div class="stat-card d-flex align-items-center gap-16" style="background: linear-gradient(135deg, #fffbeb, #fef3c7);">
                        <div class="w-48-px h-48-px radius-12 d-flex justify-content-center align-items-center text-white" style="background:#d97706">
                            <iconify-icon icon="solar:server-bold-duotone" class="text-2xl"></iconify-icon>
                        </div>
                        <div>
                            <p class="text-xs text-secondary-light fw-medium mb-4">Storage Used</p>
                            <h5 class="fw-bold mb-0"><?= formatBytes($totalSize) ?></h5>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Toolbar -->
            <div class="card radius-12 mb-24 border-0 shadow-sm">
                <div class="card-body p-16">
                    <div class="row g-12 align-items-center">
                        <div class="col-md-5">
                            <form method="GET" class="input-group">
                                <input type="hidden" name="filter_by" value="<?= htmlspecialchars($filterBy) ?>">
                                <input type="hidden" name="sort" value="<?= htmlspecialchars($sortBy) ?>">
                                <span class="input-group-text bg-transparent border-end-0 radius-start-10"><iconify-icon icon="ion:search-outline"></iconify-icon></span>
                                <input type="text" name="search" class="form-control border-start-0 radius-end-10" placeholder="Search by title, user name or email..." value="<?= htmlspecialchars($search) ?>">
                            </form>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select radius-10" onchange="applyFilter('filter_by', this.value)">
                                <option value="all" <?= $filterBy==='all'?'selected':'' ?>>All Videos</option>
                                <option value="active" <?= $filterBy==='active'?'selected':'' ?>>Active Only</option>
                                <option value="inactive" <?= $filterBy==='inactive'?'selected':'' ?>>Inactive Only</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select radius-10" onchange="applyFilter('sort', this.value)">
                                <option value="newest" <?= $sortBy==='newest'?'selected':'' ?>>Newest First</option>
                                <option value="oldest" <?= $sortBy==='oldest'?'selected':'' ?>>Oldest First</option>
                                <option value="title" <?= $sortBy==='title'?'selected':'' ?>>Title A-Z</option>
                                <option value="price_hi" <?= $sortBy==='price_hi'?'selected':'' ?>>Price: High-Low</option>
                                <option value="price_lo" <?= $sortBy==='price_lo'?'selected':'' ?>>Price: Low-High</option>
                                <option value="views" <?= $sortBy==='views'?'selected':'' ?>>Most Views</option>
                            </select>
                        </div>
                        <div class="col-md-1 text-end">
                            <button type="button" class="btn btn-outline-danger radius-10 w-100 p-10" onclick="bulkDelete()" title="Delete Selected">
                                <iconify-icon icon="solar:trash-bin-trash-bold-duotone" class="text-xl"></iconify-icon>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Video Grid -->
            <form id="bulkForm" method="POST">
                <input type="hidden" name="action" value="bulk_delete">
                <div class="row g-3">
                    <?php if (empty($videos)): ?>
                    <div class="col-12">
                        <div class="text-center py-60">
                            <iconify-icon icon="solar:video-library-bold-duotone" class="text-6xl text-secondary-light d-block mb-16"></iconify-icon>
                            <h5 class="fw-bold text-secondary-light">No videos found</h5>
                            <p class="text-sm text-secondary-light">Try adjusting your filters or search term.</p>
                        </div>
                    </div>
                    <?php else: ?>
                    <?php foreach ($videos as $v):
                        $videoFullUrl = SITE_URL . '/' . $v['video_url'];
                        $thumbSrc    = $v['thumbnail_url'] ?: 'assets/images/placeholder.jpg';
                        $fileSize    = '';
                        $fp = __DIR__ . '/' . $v['video_url'];
                        if ($v['video_url'] && file_exists($fp)) $fileSize = formatBytes(filesize($fp));
                    ?>
                    <div class="col-sm-6 col-lg-4 col-xl-3">
                        <div class="video-card bg-white">
                            <!-- Thumbnail -->
                            <div class="video-thumb-wrap">
                                <img src="<?= htmlspecialchars($thumbSrc) ?>" alt="<?= htmlspecialchars($v['title']) ?>">
                                <div class="video-overlay">
                                    <button type="button" class="play-btn" onclick="playVideo('<?= htmlspecialchars($v['video_url']) ?>', '<?= htmlspecialchars(addslashes($v['title'])) ?>')">
                                        <iconify-icon icon="solar:play-bold"></iconify-icon>
                                    </button>
                                </div>
                                <!-- Select checkbox -->
                                <div style="position:absolute; top:8px; left:8px; z-index:3;">
                                    <input type="checkbox" name="selected_ids[]" value="<?= $v['id'] ?>" class="form-check-input" style="width:20px;height:20px; cursor:pointer;">
                                </div>
                                <!-- Status badge -->
                                <div style="position:absolute; top:8px; right:8px; z-index:3;">
                                    <span class="badge badge-status-<?= $v['status'] ?> px-8 py-4 text-xxs fw-bold"><?= ucfirst($v['status']) ?></span>
                                </div>
                                <!-- File size -->
                                <?php if ($fileSize): ?>
                                <div style="position:absolute; bottom:8px; right:8px; z-index:3;">
                                    <span class="badge bg-dark bg-opacity-75 text-white px-8 py-4 text-xxs"><?= $fileSize ?></span>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Info -->
                            <div class="p-14">
                                <h6 class="text-sm fw-bold mb-4 text-truncate" title="<?= htmlspecialchars($v['title']) ?>"><?= htmlspecialchars($v['title']) ?></h6>
                                <div class="d-flex align-items-center gap-6 mb-8">
                                    <iconify-icon icon="solar:user-circle-bold-duotone" class="text-secondary-light"></iconify-icon>
                                    <span class="text-xs text-secondary-light text-truncate"><?= htmlspecialchars($v['uploader_name'] ?? 'Unknown') ?></span>
                                </div>
                                <div class="d-flex align-items-center justify-content-between mb-8">
                                    <span class="text-xs fw-bold" style="color:#6366f1">TSH <?= number_format($v['price']) ?></span>
                                    <span class="text-xs text-secondary-light">
                                        <iconify-icon icon="solar:eye-bold" class="me-4"></iconify-icon><?= number_format($v['views'] + ($v['fake_views'] ?? 0)) ?>
                                    </span>
                                </div>

                                <!-- Video URL box -->
                                <div class="url-box text-truncate mb-10" onclick="copyUrl(this)" title="Click to copy"><?= htmlspecialchars($videoFullUrl) ?></div>

                                <div class="text-xxs text-secondary-light mb-10"><?= date('M d, Y H:i', strtotime($v['created_at'])) ?></div>

                                <!-- Actions -->
                                <div class="d-flex gap-6">
                                    <button type="button" class="btn btn-sm btn-outline-primary radius-8 flex-grow-1"
                                            data-bs-toggle="modal" data-bs-target="#editVideoModal"
                                            data-vid-id="<?= $v['id'] ?>"
                                            data-vid-title="<?= htmlspecialchars($v['title'], ENT_QUOTES) ?>"
                                            data-vid-price="<?= $v['price'] ?>"
                                            data-vid-status="<?= $v['status'] ?>"
                                            data-vid-fake="<?= $v['fake_views'] ?? 0 ?>"
                                            data-vid-desc="<?= htmlspecialchars($v['description'] ?? '', ENT_QUOTES) ?>">
                                        <iconify-icon icon="solar:pen-new-square-bold-duotone" class="me-4"></iconify-icon>Edit
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-danger radius-8" onclick="deleteSingle('<?= $v['id'] ?>')">
                                        <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </form>

            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
            <nav class="mt-24">
                <ul class="pagination justify-content-center gap-2">
                    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                    <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                        <a class="page-link radius-8 fw-bold" href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&filter_by=<?= $filterBy ?>&sort=<?= $sortBy ?>"><?= $i ?></a>
                    </li>
                    <?php endfor; ?>
                </ul>
            </nav>
            <?php endif; ?>

        </div>
        <?php include 'includes/footer.php'; ?>
    </main>

    <!-- ═══ EDIT VIDEO MODAL ═══ -->
    <div class="modal fade" id="editVideoModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content radius-16 border-0 shadow-lg">
                <div class="modal-header border-0 px-24 pt-24 pb-0">
                    <div class="d-flex align-items-center gap-12">
                        <div class="w-40-px h-40-px radius-10 d-flex justify-content-center align-items-center text-white" style="background:#6366f1">
                            <iconify-icon icon="solar:pen-new-square-bold-duotone" class="text-lg"></iconify-icon>
                        </div>
                        <div>
                            <h6 class="fw-bold mb-0">Edit Video</h6>
                            <p class="text-xxs text-secondary-light mb-0">Update video details</p>
                        </div>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="edit_video">
                    <input type="hidden" name="video_id" id="editVidId">
                    <div class="modal-body px-24 py-20">
                        <div class="row g-16">
                            <div class="col-md-8">
                                <label class="form-label fw-bold text-sm mb-8">Title <span class="text-danger">*</span></label>
                                <input type="text" name="edit_title" id="editVidTitle" class="form-control radius-12" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-bold text-sm mb-8">Price (TSH)</label>
                                <input type="number" name="edit_price" id="editVidPrice" class="form-control radius-12" min="0" step="0.01">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold text-sm mb-8">Status</label>
                                <select name="edit_status" id="editVidStatus" class="form-select radius-12">
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold text-sm mb-8">Fake Views</label>
                                <input type="number" name="edit_fake_views" id="editVidFake" class="form-control radius-12" min="0">
                            </div>
                            <div class="col-12">
                                <label class="form-label fw-bold text-sm mb-8">Description</label>
                                <textarea name="edit_description" id="editVidDesc" class="form-control radius-12" rows="3"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer border-0 px-24 pb-24 pt-0 gap-12">
                        <button type="button" class="btn btn-outline-secondary radius-10 px-20" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary radius-10 px-32 fw-bold">
                            <iconify-icon icon="solar:disk-bold-duotone" class="me-8"></iconify-icon>Save Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- ═══ VIDEO PLAYER MODAL ═══ -->
    <div class="modal fade" id="videoPlayerModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content radius-16 border-0">
                <div class="modal-header border-0 bg-dark px-20 py-12">
                    <h6 class="text-white fw-bold mb-0" id="playerTitle">Video Player</h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-0 bg-dark">
                    <video id="modalVideoPlayer" controls class="w-100" style="max-height:70vh;"></video>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══ HIDDEN DELETE FORM ═══ -->
    <form id="deleteSingleForm" method="POST" style="display:none;">
        <input type="hidden" name="action" value="delete_video">
        <input type="hidden" name="video_id" id="deleteSingleId">
    </form>

<script>
    // Edit modal pre-fill
    document.getElementById('editVideoModal').addEventListener('show.bs.modal', function(event) {
        var btn = event.relatedTarget;
        document.getElementById('editVidId').value     = btn.getAttribute('data-vid-id');
        document.getElementById('editVidTitle').value   = btn.getAttribute('data-vid-title');
        document.getElementById('editVidPrice').value   = btn.getAttribute('data-vid-price');
        document.getElementById('editVidStatus').value  = btn.getAttribute('data-vid-status');
        document.getElementById('editVidFake').value    = btn.getAttribute('data-vid-fake');
        document.getElementById('editVidDesc').value    = btn.getAttribute('data-vid-desc');
    });

    // Stop video when closing player modal
    document.getElementById('videoPlayerModal').addEventListener('hidden.bs.modal', function() {
        var vid = document.getElementById('modalVideoPlayer');
        vid.pause();
        vid.src = '';
    });

    // Play video
    function playVideo(url, title) {
        document.getElementById('playerTitle').textContent = title;
        document.getElementById('modalVideoPlayer').src = url;
        bootstrap.Modal.getOrCreateInstance(document.getElementById('videoPlayerModal')).show();
    }

    // Delete single
    function deleteSingle(id) {
        if (confirm('Are you sure you want to delete this video? This cannot be undone.')) {
            document.getElementById('deleteSingleId').value = id;
            document.getElementById('deleteSingleForm').submit();
        }
    }

    // Bulk delete
    function bulkDelete() {
        var checked = document.querySelectorAll('#bulkForm input[name="selected_ids[]"]:checked');
        if (checked.length === 0) { alert('Select at least one video.'); return; }
        if (confirm('Delete ' + checked.length + ' selected video(s)? This cannot be undone.')) {
            document.getElementById('bulkForm').submit();
        }
    }

    // Copy URL
    function copyUrl(el) {
        navigator.clipboard.writeText(el.textContent.trim()).then(function() {
            var orig = el.textContent;
            el.textContent = '✓ Copied!';
            el.style.background = '#dcfce7';
            setTimeout(function() { el.textContent = orig; el.style.background = ''; }, 1500);
        });
    }

    // Filter helper
    function applyFilter(key, value) {
        var url = new URL(window.location);
        url.searchParams.set(key, value);
        url.searchParams.delete('page');
        window.location = url.toString();
    }
</script>
</body>
</html>


