<?php
session_start();

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: admin-login");
    exit;
}

$baseDir = __DIR__ . "/../uploads/projects/";
$catFile = $baseDir . "categories.json";
$categories = file_exists($catFile)
    ? json_decode(file_get_contents($catFile), true)
    : [];
?>

<!DOCTYPE html>
<html>
<head>
<title>Project Media Manager</title>
<style>
body { font-family: Arial; padding: 30px; background:#f5f5f5; }
.card { background:#fff; padding:20px; margin-bottom:20px; border-radius:8px; }
.media-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(150px,1fr)); gap:15px; }
video,img { width:100%; border-radius:6px; }
button { padding:6px 12px; }
</style>
</head>
<body>

<h1>Project Media Manager</h1>
<a href="logout.php">Logout</a>

<div class="card">
<h2>Create Category</h2>
<form method="post" action="admin-actions.php">
<input type="text" name="category" required placeholder="Category name">
<button name="create_category">Add Category</button>
</form>
</div>

<?php foreach ($categories as $name => $slug): ?>
<div class="card">
<h2><?= htmlspecialchars($name) ?></h2>

<form method="post" enctype="multipart/form-data" action="admin-actions.php">
<input type="hidden" name="slug" value="<?= $slug ?>">
<input type="file" name="media[]" multiple required>
<button name="upload_media">Upload Media</button>
</form>

<div class="media-grid">
<?php
$mediaDir = $baseDir . $slug . "/media/";
if (is_dir($mediaDir)) {
    foreach (glob($mediaDir . "*") as $file) {
        $url = "../uploads/projects/$slug/media/" . basename($file);
        echo "<div>";
        if (preg_match('/mp4|webm|ogg$/i', $file)) {
            echo "<video controls src='$url'></video>";
        } else {
            echo "<img src='$url'>";
        }
        echo "
        <form method='post' action='admin-actions.php'>
            <input type='hidden' name='file' value='$file'>
            <button name='delete_media'>Delete</button>
        </form>
        </div>";
    }
}
?>
</div>
</div>
<?php endforeach; ?>

</body>
</html>
