<?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();
$data = json_decode(file_get_contents('php://input'), true);

/**
 * ================= VALIDATION =================
 */
Validator::required($data, ['variant_id', 'status']);

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

$allowedStatus = ['Active', 'InActive'];

if (!in_array($status, $allowedStatus, true)) {
    Response::error('Invalid status value', 422);
}

/**
 * ================= 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', 'SEO Manager'], true)) {
    Response::error('You are not authorized to update variant status', 403);
}

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

$currentStatus = $stmt->fetchColumn();

if (!$currentStatus) {
    Response::error('Variant not found', 404);
}

/**
 * ================= NO-OP GUARD =================
 */
if ($currentStatus === $status) {
    Response::error('Variant already in requested status', 409);
}

/**
 * ================= UPDATE STATUS =================
 */
$stmt = $db->prepare("
    UPDATE retail_product_variants
    SET
        status = :status,
        updated_at = NOW()
    WHERE id = :id
");
$stmt->execute([
    'status' => $status,
    'id'     => $variantId
]);

Response::success(
    $status === 'Active'
        ? 'Variant activated successfully'
        : 'Variant deactivated successfully'
);
