<?php
require_once __DIR__ . '/includes/session_check.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/activity_logger.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['filename'])) {
    $userId = $_SESSION['user_id'] ?? 0;
    $username = $_SESSION['username'] ?? 'Unknown';

    $filename = basename($_POST['filename']); // Sanitize filename
    $filepath = __DIR__ . '/galeria/' . $filename;

    if (file_exists($filepath) && is_file($filepath)) {
        if (unlink($filepath)) {
            log_activity($userId, 'Image Deleted', 'User ' . $username . ' deleted image: ' . $filename);
            header('Location: gallery.php?success=deleted');
        } else {
            log_activity($userId, 'Image Deletion Failed', 'User ' . $username . ' failed to delete image: ' . $filename);
            header('Location: gallery.php?error=delete_failed');
        }
    } else {
        log_activity($userId, 'Image Deletion Failed', 'User ' . $username . ' attempted to delete non-existent or invalid file: ' . $filename);
        header('Location: gallery.php?error=invalid_file');
    }
} else {
    header('Location: gallery.php');
}
?>