<?php

class VariationSorter
{
    private $sort_params = [
        'rankSet',
        'rankSize',
        'rankBox',
        'rankComplementType',
    ];

    public function sort($variations, $level = 0)
    {
        if ($level >= count($this->sort_params)) {
            return $variations;
        }

        $rankingFunction = $this->sort_params[$level];
        $categories = [];

        foreach ($variations as &$variation) {
            $rank = call_user_func([$this, $rankingFunction], $variation);
            $categories[$rank][] = $variation;
        }

        krsort($categories);

        $variations = [];
        foreach ($categories as $category) {
            $variations = array_merge($variations, $this->sort($category, $level + 1));
        }

        return $variations;
    }

    public function rankSet($variation)
    {
        return !$variation['set'];
    }

    public function rankSize($variation)
    {
        $complementTypeRank = $this->rankComplementType($variation);
        if ($complementTypeRank < 0) {
            return $complementTypeRank;
        }

        return (float) str_replace(',', '.', $variation['size_value']);
    }

    public function rankBox($variation)
    {
        if ($variation['damage']) {
            return 0;
        }
        if (isset($variation['campaign_codes']['T'])) {
            return 1;
        }

        return 2;
    }

    public function rankComplementType($variation)
    {
        $complementTypes = [
            '1F40000101' => -8, // Náplň bez rozprašovače
            '3D40000101' => -7, // Náplň
            '4D40000101' => -6, // Bez rozprašovače
            '5D40000101' => -5, // Twist and Spray
            '2G40000101' => -4, // Travel Spray
            '1QF0000101' => -3, // Rollerball
            '1G61000101' => -2, // S rozprašovačem
            '2D40000101' => -1, // Naplnitelný
        ];

        return $complementTypes[$variation['raw_id_complement_type']] ?? 0;
    }
}

/*
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:     function
 * Name:     sort_variation
 * Purpose:  sort_variation
 * -------------------------------------------------------------
 */
function smarty_modifier_sort_variations($variations)
{
    if (empty($variations)) {
        return $variations;
    }

    $sorter = new VariationSorter();

    return $sorter->sort($variations);
}
