<?php
session_start();
if(!isset($_SESSION['admin'])) die("Unauthorized");

$base = "uploads/projects/";

/* CREATE CATEGORY */
if(isset($_POST['new_category'])){
    $slug = strtolower(trim(preg_replace('/[^a-z0-9]+/','-',$_POST['category'])));
    mkdir($base.$slug, 0777, true);
}

/* DELETE CATEGORY */
if(isset($_POST['delete_category'])){
    $dir = $base.$_POST['delete_category'];
    array_map('unlink', glob("$dir/*"));
    rmdir($dir);
}

/* UPLOAD MEDIA */
if(isset($_FILES['media'])){
    $cat = $_POST['cat'];
    move_uploaded_file($_FILES['media']['tmp_name'], $base.$cat."/".$_FILES['media']['name']);
}

/* DELETE MEDIA */
if(isset($_POST['delete_media'])){
    unlink($_POST['delete_media']);
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Project Media Manager</title>
<style>
body{font-family:Arial;background:#f4f6f9;padding:20px}
h2,h3{margin-top:30px}
.card{background:#fff;padding:20px;border-radius:10px;margin-bottom:30px}
input,select,button{padding:10px;margin-top:10px}
button{background:#0d6efd;color:#fff;border:none;border-radius:5px;cursor:pointer}
.delete{background:red}
.media-grid{display:flex;flex-wrap:wrap;gap:15px;margin-top:15px}
.media-item{width:150px;text-align:center}
.media-item img,video{width:100%;border-radius:8px}
</style>
</head>
<body>

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

<div class="card">
<h3>Create Category</h3>
<form method="post">
<input name="category" placeholder="Category name (e.g Solar Installation)" required>
<button name="new_category">Add Category</button>
</form>
</div>

<?php
$cats = glob($base."*", GLOB_ONLYDIR);
foreach($cats as $c):
$slug = basename($c);
?>

<div class="card">
<h3><?= ucwords(str_replace('-', ' ', $slug)); ?></h3>

<form method="post" onsubmit="return confirm('Delete category and all media?')">
<input type="hidden" name="delete_category" value="<?= $slug ?>">
<button class="delete">Delete Category</button>
</form>

<form method="post" enctype="multipart/form-data">
<input type="hidden" name="cat" value="<?= $slug ?>">
<input type="file" name="media" required>
<button>Upload Media</button>
</form>

<div class="media-grid">
<?php foreach(glob("$c/*.{jpg,png,mp4}",GLOB_BRACE) as $file): ?>
<div class="media-item">
<?php if(str_ends_with($file,'mp4')): ?>
<video controls></video>
<?php else: ?>
<img src="<?= $file ?>">
<?php endif; ?>
<form method="post" onsubmit="return confirm('Delete this file?')">
<input type="hidden" name="delete_media" value="<?= $file ?>">
<button class="delete">Delete</button>
</form>
</div>
<?php endforeach; ?>
</div>

</div>

<?php endforeach; ?>

</body>
</html>
