<?php
session_start();

/**
 * Admin authentication
 */
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: admin_login.php");
    exit;
}

/**
 * Validate inputs
 */
$category = $_GET['category'] ?? '';
$file     = $_GET['file'] ?? '';

if ($category === '' || $file === '') {
    header("Location: admin.php?error=Invalid request");
    exit;
}

/**
 * Base upload directory
 * Adjust path if this file is inside /admin/
 */
$baseDir = realpath(__DIR__ . "/uploads/projects");

if ($baseDir === false) {
    header("Location: admin.php?error=Upload directory not found");
    exit;
}

/**
 * Resolve target file path
 */
$targetFile = realpath($baseDir . "/$category/$file");

/**
 * Security check – prevent path traversal
 */
if ($targetFile === false || strpos($targetFile, $baseDir) !== 0) {
    header("Location: admin.php?error=Invalid file path");
    exit;
}

/**
 * Check file existence
 */
if (!file_exists($targetFile)) {
    header("Location: admin.php?error=File not found");
    exit;
}

/**
 * Delete file
 */
if (unlink($targetFile)) {

    // Optional: remove category folder if empty
    $categoryDir = dirname($targetFile);
    if (is_dir($categoryDir) && count(scandir($categoryDir)) === 2) {
        rmdir($categoryDir);
    }

    header("Location: admin.php?success=" . urlencode("Media deleted successfully"));
} else {
    header("Location: admin.php?error=" . urlencode("Failed to delete media"));
}

exit;
