<?php
declare(strict_types=1);

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

$db = Database::getInstance();

try {
    $data = json_decode(file_get_contents('php://input'), true);
    Validator::required($data, ['category_id']);

    $categoryId = (int)$data['category_id'];

    /* ================= CHECK PRODUCT CONNECTION ================= */
    $stmt = $db->prepare("
        SELECT COUNT(*) 
        FROM retail_products
        WHERE category_id = :id
    ");
    $stmt->execute(['id' => $categoryId]);

    if ((int)$stmt->fetchColumn() > 0) {
        Response::error(
            'Category is connected to one or more retail products. Please reassign or delete products first.'
        );
        exit;
    }

    /* ================= HARD DELETE ================= */
    $stmt = $db->prepare("
        DELETE FROM retail_categories
        WHERE id = :id
        LIMIT 1
    ");
    $stmt->execute(['id' => $categoryId]);

    if ($stmt->rowCount() === 0) {
        Response::error('Category not found or already deleted.');
        exit;
    }

    Response::success('Retail category deleted successfully');

} catch (PDOException $e) {

    // Handles FK constraints or permission issues safely
    Response::error(
        'Unable to delete category due to database constraints.'
    );
}
