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

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

function slug($text) {
    return strtolower(preg_replace('/[^a-z0-9]+/', '-', trim($text)));
}

if (isset($_POST['create_category'])) {
    $name = trim($_POST['category']);
    $slug = slug($name);
    $cats[$name] = $slug;
    mkdir($baseDir . "$slug/media", 0777, true);
    file_put_contents($catFile, json_encode($cats, JSON_PRETTY_PRINT));
}

if (isset($_POST['upload_media'])) {
    $slug = $_POST['slug'];
    foreach ($_FILES['media']['tmp_name'] as $i => $tmp) {
        $name = basename($_FILES['media']['name'][$i]);
        move_uploaded_file($tmp, $baseDir . "$slug/media/" . time() . "_" . $name);
    }
}

if (isset($_POST['delete_media'])) {
    if (file_exists($_POST['file'])) unlink($_POST['file']);
}

header("Location: admin-dashboard.php");
