<?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', 'direction']);

$variantId = (int)$data['variant_id'];
$direction = $data['direction']; // up | down

if (!in_array($direction, ['up', 'down'], true)) {
    Response::error('Invalid direction', 422);
}

/**
 * ================= FETCH CURRENT VARIANT =================
 */
$stmt = $db->prepare("
    SELECT id, product_id, sort_order
    FROM retail_product_variants
    WHERE id = :id
");
$stmt->execute(['id' => $variantId]);
$current = $stmt->fetch(PDO::FETCH_ASSOC);

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

$db->beginTransaction();

try {
    /**
     * Find adjacent variant
     */
    $operator = $direction === 'up' ? '<' : '>';
    $orderBy  = $direction === 'up' ? 'DESC' : 'ASC';

    $stmt = $db->prepare("
        SELECT id, sort_order
        FROM retail_product_variants
        WHERE product_id = :pid
          AND sort_order $operator :current_order
        ORDER BY sort_order $orderBy
        LIMIT 1
    ");
    $stmt->execute([
        'pid' => $current['product_id'],
        'current_order' => $current['sort_order']
    ]);

    $adjacent = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$adjacent) {
        $db->rollBack();
        Response::success('Already at boundary');
    }

    /**
     * Swap sort_order
     */
    $stmt = $db->prepare("
        UPDATE retail_product_variants
        SET sort_order = :order
        WHERE id = :id
    ");

    $stmt->execute([
        'order' => $adjacent['sort_order'],
        'id'    => $current['id']
    ]);

    $stmt->execute([
        'order' => $current['sort_order'],
        'id'    => $adjacent['id']
    ]);

    $db->commit();

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

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