<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';

$db = Database::getInstance();

$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data['category_id'])) {
    Response::error('Invalid request');
}

$categoryId = (int)$data['category_id'];
if ($categoryId <= 0) {
    Response::error('Invalid category');
}

/* ================= FETCH IMAGE ================= */
$stmt = $db->prepare("
    SELECT image_path
    FROM retail_categories
    WHERE id = :id
");
$stmt->execute(['id' => $categoryId]);
$imagePath = $stmt->fetchColumn();

if (!$imagePath) {
    Response::error('No image to delete');
}

/* ================= DELETE FILE ================= */
$file = __DIR__ . '/../../../' . ltrim($imagePath, '/');
if (is_file($file)) {
    unlink($file);

    // Remove empty category directory
    $dir = dirname($file);
    if (is_dir($dir) && count(glob($dir . '/*')) === 0) {
        rmdir($dir);
    }
}

/* ================= UPDATE DB ================= */
$stmt = $db->prepare("
    UPDATE retail_categories
    SET image_path = NULL,
        image_alt  = NULL
    WHERE id = :id
");
$stmt->execute(['id' => $categoryId]);

Response::success('Image deleted successfully');
