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

Validator::required($data, [
    'variant_id',
    'variant_name',
    'size',
    'firmness',
    'thickness',
    'mrp',
    'selling_price'
]);

$variantId   = (int)$data['variant_id'];
$variantName = trim($data['variant_name']);
$size        = $data['size'];
$firmness    = $data['firmness'];
$thickness   = trim($data['thickness']);
$mrp         = (float)$data['mrp'];
$sellPrice  = (float)$data['selling_price'];

$allowedSize = ['Single','Double','Queen','King','Custom'];
$allowedFirm = ['Soft','Medium','Firm','Custom'];

if (!in_array($size, $allowedSize, true)) {
    Response::error('Invalid size', 422);
}
if (!in_array($firmness, $allowedFirm, true)) {
    Response::error('Invalid firmness', 422);
}
if ($mrp <= 0 || $sellPrice <= 0 || $sellPrice > $mrp) {
    Response::error('Invalid pricing', 422);
}

/**
 * Check variant exists
 */
$stmt = $db->prepare("SELECT id FROM retail_product_variants WHERE id = :id");
$stmt->execute(['id' => $variantId]);
if (!$stmt->fetch()) {
    Response::error('Variant not found', 404);
}

/**
 * Update variant
 */
$stmt = $db->prepare("
    UPDATE retail_product_variants
    SET
        variant_name = :name,
        sku = :sku,
        mrp = :mrp,
        selling_price = :selling_price,
        size = :size,
        firmness = :firmness,
        thickness = :thickness,
        specifications = :specs,
        updated_at = NOW()
    WHERE id = :id
");

$stmt->execute([
    'name'          => $variantName,
    'sku'           => $data['sku'] ?? null,
    'mrp'           => $mrp,
    'selling_price' => $sellPrice,
    'size'          => $size,
    'firmness'      => $firmness,
    'thickness'     => $thickness,
    'specs'         => isset($data['specifications'])
                        ? json_encode($data['specifications'], JSON_UNESCAPED_UNICODE)
                        : null,
    'id'            => $variantId
]);

Response::success('Variant updated successfully');
