<?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, [
    'product_id',
    'variant_name',
    'size',
    'firmness',
    'thickness',
    'mrp',
    'selling_price'
]);

$productId   = (int)$data['product_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);
}

/**
 * Validate product
 */
$stmt = $db->prepare("SELECT id FROM retail_products WHERE id = :id");
$stmt->execute(['id' => $productId]);
if (!$stmt->fetch()) {
    Response::error('Retail product not found', 404);
}

/**
 * START TRANSACTION (important)
 */
$db->beginTransaction();

try {
    /**
     * Get next sort_order SAFELY
     */
    $stmt = $db->prepare("
        SELECT IFNULL(MAX(sort_order), 0) + 1
        FROM retail_product_variants
        WHERE product_id = :pid
    ");
    $stmt->execute(['pid' => $productId]);
    $sortOrder = (int)$stmt->fetchColumn();

    /**
     * Insert variant
     */
    $stmt = $db->prepare("
        INSERT INTO retail_product_variants (
            product_id,
            variant_name,
            sku,
            mrp,
            selling_price,
            size,
            firmness,
            thickness,
            specifications,
            status,
            sort_order
        ) VALUES (
            :product_id,
            :variant_name,
            :sku,
            :mrp,
            :selling_price,
            :size,
            :firmness,
            :thickness,
            :specs,
            'Active',
            :sort_order
        )
    ");

    $stmt->execute([
        'product_id'    => $productId,
        'variant_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,
        'sort_order'    => $sortOrder
    ]);

    $db->commit();

} catch (Throwable $e) {
    $db->rollBack();
    Response::error('Failed to add variant', 500);
}

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