<?php
declare(strict_types=1);

require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../core/Response.php';

$db = Database::getInstance();

/**
 * Input
 */
if (empty($_GET['product_id'])) {
    Response::error('product_id is required', 422);
}

$productId = (int)$_GET['product_id'];
$status    = $_GET['status'] ?? null;

/**
 * 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);
}

/**
 * Build query
 */
$where = "WHERE product_id = :pid";
$params = ['pid' => $productId];

if ($status) {
    $where .= " AND status = :status";
    $params['status'] = $status;
}

/**
 * Fetch variants
 */
$stmt = $db->prepare("
    SELECT
        id,
        variant_name,
        sku,
        size,
        firmness,
        thickness,
        mrp,
        selling_price,
        specifications,
        status,
        sort_order,
        created_at,
        updated_at
    FROM retail_product_variants
    $where
    ORDER BY sort_order ASC
");
$stmt->execute($params);

$variants = [];

foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $v) {
    $v['specifications'] = $v['specifications']
        ? json_decode($v['specifications'], true)
        : null;
    $variants[] = $v;
}

Response::success('Variants fetched successfully', [
    'product_id' => $productId,
    'variants'   => $variants
]);
