<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireLogin();

$id = $_GET['id'] ?? null;
if ($id) {
    // Fetch category to delete icon later
    $stmt = $pdo->prepare("SELECT icon_url FROM categories WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $cat = $stmt->fetch();

    if ($cat) {
        // Delete category from database
        $pdo->prepare("DELETE FROM categories WHERE id = :id")->execute([':id' => $id]);

        // Remove icon file if it exists
        if (!empty($cat['icon_url'])) {
            $iconPath = $cat['icon_url'];

            // If it's a full URL, extract the filename
            if (filter_var($iconPath, FILTER_VALIDATE_URL)) {
                $filename = basename(parse_url($iconPath, PHP_URL_PATH));
            } else {
                $filename = $iconPath; // Already a simple filename
            }

            if (!empty($filename)) {
                deleteFile('../assets/uploads/' . $filename);
            }
        }

        setFlash('success', 'Category deleted.');
    } else {
        setFlash('danger', 'Category not found.');
    }
} else {
    setFlash('danger', 'Invalid request.');
}

header('Location: categories.php');
exit;