<?php
session_start();
if (!isset($_SESSION['admin'])) {
    header('Location: login.php');
    exit();
}

include 'db.php';
include 'upload_helper.php';

$message = '';

// Handle Video Upload/Add
if (isset($_POST['add_video'])) {
    $title = $_POST['title'];
    $video_url = $_POST['video_url_manual'];
    $thumbnail = $_POST['thumbnail_url'];

    // Handle Video File Upload if provided
    if (isset($_FILES['video_file']) && $_FILES['video_file']['error'] === UPLOAD_ERR_OK) {
        $videoUpload = handleFileUpload($_FILES['video_file'], '../../assets/videos/', ['mp4', 'mov', 'avi'], 50 * 1024 * 1024); // 50MB limit
        if ($videoUpload['status'] === 'success') {
            $video_url = $videoUpload['fileName'];
        } else {
            $message = "<div class='alert alert-danger'>Video Upload Error: " . $videoUpload['message'] . "</div>";
        }
    }

    if (empty($message) && !empty($video_url)) {
        try {
            $stmt = $conn->prepare("INSERT INTO videos (video_url, title, thumbnail) VALUES (?, ?, ?)");
            if (!$stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            $stmt->bind_param("sss", $video_url, $title, $thumbnail);
            if ($stmt->execute()) {
                $message = "<div class='alert alert-success'>Video added successfully!</div>";
            } else {
                throw new Exception("Execute failed: " . $stmt->error);
            }
            $stmt->close();
        } catch (Exception $e) {
            $message = "<div class='alert alert-danger'>Error: " . $e->getMessage() . "</div>";
        }
    }
}

// Handle Delete
if (isset($_GET['delete'])) {
    $id = (int) $_GET['delete'];
    $stmt = $conn->prepare("DELETE FROM videos WHERE video_id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->close();
    header("Location: manage_videos.php?msg=deleted");
    exit();
}

// Fetch existing videos
$videos = $conn->query("SELECT * FROM videos ORDER BY created_at DESC");
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Video Feed - GameHub</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }

        .video-card {
            transition: transform 0.2s;
            border: none;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>

<body>
    <div class="container py-5">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>🎥 Manage Home Video Feed</h2>
            <a href="index.php" class="btn btn-outline-secondary">Back to Dashboard</a>
        </div>

        <?php echo $message; ?>

        <!-- Add Video Form -->
        <div class="card mb-5 p-4 shadow-sm">
            <h5 class="card-title mb-4">Add New Video to Feed</h5>
            <form method="POST" enctype="multipart/form-data">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Video Title</label>
                        <input type="text" name="title" class="form-control" placeholder="e.g. New Game Trailer"
                            required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Thumbnail URL</label>
                        <input type="url" name="thumbnail_url" class="form-control" placeholder="https://...">
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Option A: Upload Video File (MP4)</label>
                        <input type="file" name="video_file" class="form-control" accept="video/mp4,video/quicktime">
                        <small class="text-muted">Max size: 50MB</small>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Option B: Video URL (If already on server)</label>
                        <input type="text" name="video_url_manual" class="form-control"
                            placeholder="my_trailer.mp4 or https://...">
                    </div>
                </div>
                <button type="submit" name="add_video" class="btn btn-primary w-100">Add to Video Feed</button>
            </form>
        </div>

        <!-- Video List -->
        <div class="row row-cols-1 row-cols-md-3 g-4">
            <?php while ($v = $videos->fetch_assoc()) {
                $vurl = $v['video_url'];
                if (!filter_var($vurl, FILTER_VALIDATE_URL))
                    $vurl = '../../assets/videos/' . $vurl;
                ?>
                <div class="col">
                    <div class="card h-100 video-card">
                        <div class="ratio ratio-16x9">
                            <video src="<?php echo $vurl; ?>" muted class="card-img-top"></video>
                        </div>
                        <div class="card-body">
                            <h6 class="card-title">
                                <?php echo htmlspecialchars($v['title']); ?>
                            </h6>
                            <p class="small text-muted mb-0">Added:
                                <?php echo date('M d, Y', strtotime($v['created_at'])); ?>
                            </p>
                        </div>
                        <div class="card-footer bg-white border-top-0 pb-3">
                            <a href="?delete=<?php echo $v['video_id']; ?>" class="btn btn-sm btn-danger w-100"
                                onclick="return confirm('Remove this video?')">Remove Video</a>
                        </div>
                    </div>
                </div>
            <?php } ?>
        </div>
    </div>
</body>

</html>