<?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);

/**
 * ================= VALIDATION =================
 */
if (empty($data['variant_id'])) {
    Response::error('variant_id is required', 422);
}

$variantId = (int)$data['variant_id'];

/**
 * ================= ROLE CHECK =================
 */
$stmt = $db->prepare("
    SELECT r.name
    FROM employees e
    JOIN roles r ON r.id = e.role_id
    WHERE e.id = :id
");
$stmt->execute(['id' => $_SESSION['employee_id']]);
$role = $stmt->fetchColumn();

if (!in_array($role, ['Super Admin', 'Admin'], true)) {
    Response::error('You are not authorized to delete variants', 403);
}

/**
 * ================= CHECK VARIANT =================
 */
$stmt = $db->prepare("
    SELECT id
    FROM retail_product_variants
    WHERE id = :id
");
$stmt->execute(['id' => $variantId]);

if (!$stmt->fetchColumn()) {
    Response::error('Variant not found', 404);
}

/**
 * ================= HARD DELETE =================
 */
try {
    $stmt = $db->prepare("
        DELETE FROM retail_product_variants
        WHERE id = :id
    ");
    $stmt->execute(['id' => $variantId]);
} catch (Throwable $e) {
    Response::error('Failed to delete variant permanently', 500);
}

Response::success('Variant deleted permanently');
