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

$user_id = $_SESSION['user_id'];
$error = '';
$success = '';

// Handle Delete
if(isset($_POST['delete_id'])) {
    $del_id = $_POST['delete_id'];
    try {
        $stmt = $pdo->prepare("SELECT video_url, thumbnail_url FROM videos WHERE id = ? AND user_id = ?");
        $stmt->execute([$del_id, $user_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']);
            
            $stmt = $pdo->prepare("DELETE FROM videos WHERE id = ?");
            $stmt->execute([$del_id]);
            $success = "Video deleted successfully.";
        }
    } catch(PDOException $e) {
        $error = "Failed to delete video.";
    }
}

try {
    $stmt = $pdo->prepare("SELECT * FROM videos WHERE user_id = ? ORDER BY position ASC, created_at ASC");
    $stmt->execute([$user_id]);
    $videos = $stmt->fetchAll();
} catch (PDOException $e) {
    $videos = [];
}
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<?php include 'includes/head.php'; ?>
<style>
.toast-container { z-index: 2000; }
.custom-toast { min-width: 320px; border-radius: 16px !important; box-shadow: 0 15px 35px rgba(0,0,0,0.2); backdrop-filter: blur(10px); animation: slideInCustom 0.5s cubic-bezier(0.68,-0.55,0.27,1.55); position: relative; overflow: hidden; }
.toast-header { background: rgba(255,255,255,0.9) !important; padding: 12px 16px; color: #111; }
.toast-icon-wrapper { font-size: 1.2rem; display: flex; align-items: center; }
.toast-body { padding: 12px 16px 18px; font-weight: 500; letter-spacing: -0.2px; }
.toast-progress { position: absolute; bottom: 0; left: 0; height: 4px; width: 100%; background: rgba(255,255,255,0.3); }
.toast-progress::before { content: ""; position: absolute; height: 100%; width: 100%; background: rgba(255,255,255,0.7); animation: progressAnim 4s linear forwards; transform-origin: left; }
.custom-toast.text-bg-success { background: linear-gradient(135deg, #10b981, #059669) !important; color: white; }
.custom-toast.text-bg-danger { background: linear-gradient(135deg, #f43f5e, #e11d48) !important; color: white; }
@keyframes progressAnim { from { transform: scaleX(1); } to { transform: scaleX(0); } }
@keyframes slideInCustom { from { transform: translateY(20px) scale(0.9); opacity: 0; } to { transform: translateY(0) scale(1); opacity: 1; } }
.drag-handle { cursor: grab; color: #ccc; transition: color 0.2s; }
.drag-handle:hover { color: #5d66e5; }
.sortable-ghost { opacity: 0.3; background: #e2eafc !important; }
.sortable-chosen { background: #fff; box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
</style>
<body>
    <?php include 'includes/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'includes/header.php'; ?>
        <div class="dashboard-main-body">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                <h6 class="fw-semibold mb-0">Manage Videos</h6>
                <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">Manage Videos</li>
                </ul>
            </div>

            <?php if($error || $success): ?>
            <div class="toast-container position-fixed bottom-0 end-0 p-3">
                <div id="liveToast" class="toast custom-toast text-bg-<?= $success ? 'success' : 'danger' ?>" role="alert" aria-live="assertive" aria-atomic="true">
                    <div class="toast-header d-flex justify-content-between">
                        <div class="d-flex align-items-center gap-2">
                            <span class="toast-icon-wrapper text-<?= $success ? 'success' : 'danger' ?>">
                                <iconify-icon icon="<?= $success ? 'lucide:check-circle' : 'lucide:alert-circle' ?>"></iconify-icon>
                            </span>
                            <strong class="me-auto"><?= $success ? 'Success' : 'Error' ?></strong>
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
                    </div>
                    <div class="toast-body text-white">
                        <?= htmlspecialchars($success ?: $error) ?>
                        <div class="toast-progress"></div>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <div class="card radius-12">
                <div class="card-header border-bottom d-flex align-items-center justify-content-between flex-wrap gap-2">
                    <h6 class="mb-0 text-lg">Video Manage</h6>
                    <a href="<?= SITE_URL ?>/upload" class="btn btn-primary-600 radius-8 px-20 py-11 d-flex align-items-center gap-2">
                        <i class="ri-add-line pb-1"></i> Add New
                    </a>
                </div>
                
                <div class="card-body p-16">
                    <div class="table-responsive">
                        <table class="table bordered-table mb-0 stripe dataTable">
                            <thead>
                                <tr>
                                    <th>Move</th>
                                    <th>Title</th>
                                    <th>Price</th>
                                    <th>Views</th>
                                     <th>Fake Views</th>
                                    <th>Status</th>
                                    <th>Uploaded At</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody id="sortable-video-list">
                                <?php if(!empty($videos)): ?>
                                    <?php foreach($videos as $v): ?>
                                    <tr data-id="<?= htmlspecialchars($v['id']) ?>">
                                        <td class="drag-handle text-center"><iconify-icon icon="lucide:grip-vertical" width="24"></iconify-icon></td>
                                        <td>
                                            <div class="d-flex align-items-center gap-12">
                                                <img src="<?= htmlspecialchars($v['thumbnail_url'] ?: 'assets/images/placeholder.jpg') ?>" class="w-40-px h-40-px radius-8 object-fit-cover">
                                                <span class="text-md fw-medium text-black"><?= htmlspecialchars($v['title']) ?></span>
                                            </div>
                                        </td>
                                        <td class="text-sm">TSH <?= number_format($v['price']) ?></td>
                                        <td class="text-sm"><?= number_format($v['views']) ?></td>
                                         <td class="text-sm"><?= number_format($v['fake_views'] ?? 0) ?></td>
                                        <td><span class="bg-success-focus text-success-main px-24 py-4 rounded-pill fw-medium text-sm"><?= ucfirst($v['status']) ?></span></td>
                                        <td class="text-sm"><?= date('M d, Y', strtotime($v['created_at'])) ?></td>
                                        <td>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('Delete video?');">
                                                <input type="hidden" name="delete_id" value="<?= $v['id'] ?>">
                                                <button type="submit" class="w-32-px h-32-px bg-danger-focus text-danger-main rounded-circle d-inline-flex align-items-center justify-content-center" title="Delete Video">
                                                    <iconify-icon icon="mingcute:delete-2-line"></iconify-icon>
                                                </button>
                                            </form>
                                            <a href="edit_video?id=<?= $v['id'] ?>" class="w-32-px h-32-px bg-success-focus text-success-main rounded-circle d-inline-flex align-items-center justify-content-center">
                                                <iconify-icon icon="material-symbols:edit-outline"></iconify-icon>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="8" class="text-center py-20 text-muted">No videos found. Upload one to get started!</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <?php include 'includes/footer.php'; ?>
    </main>
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const toastEl = document.getElementById('liveToast');
            if (toastEl) {
                const toast = bootstrap.Toast.getOrCreateInstance(toastEl, { delay: 4000 });
                toast.show();
            }
            
            const el = document.getElementById('sortable-video-list');
            if(el) {
                Sortable.create(el, {
                    animation: 150,
                    handle: '.drag-handle',
                    ghostClass: 'sortable-ghost',
                    onEnd: function() {
                        let order = [];
                        $('#sortable-video-list tr').each(function(index) {
                            order.push({ id: $(this).data('id'), position: index + 1 });
                        });

                        $.ajax({
                            url: "reorder_videos.php",
                            method: "POST",
                            data: { order: order },
                            success: function(response) { console.log("Order saved successfully"); },
                            error: function() { alert("Error saving order. Please refresh."); }
                        });
                    }
                });
            }
        });
    </script>
</body>
</html>





