<?php

namespace Modules\Parametrage\Facture\Repository;

use Helpers\Outil\ArrayHelper;
use Helpers\Outil\StringHelper;
use Helpers\QueryBuilder\AbsRepository;

class UblSchemaRepo extends AbsRepository
{
    /**
     * @return array{code:string,label:string,xpath?:string}[]
     */
    public function getSchema() :array
    {
        return require __DIR__ . '/../Data/ubl_field.php';
    }

    /**
     * @return ?array<mixed>
     */
    public function get(string $id)
    {
        return $this->getSchema()[ $id ] ?? null;
    }

    /**
     * @param array<mixed> $post
     * @return array<array<mixed>>
     */
    public function listField(array $post = [])
    {
        $list = $this->getSchema();

        //__________

        $listFilter = $this->parsePostPrefix($post, 'filter_');
        foreach ($listFilter as $key => $value) {
            if (str_starts_with($key, 'egal_')) {
                $key = StringHelper::removePrefix($key, 'egal_');
                $list = array_filter($list, function ($item) use ($key, $value) {
                    return $item[ $key ] == $value;
                });
            } else {
                $list = array_filter($list, function ($item) use ($key, $value) {
                    return str_contains(strtoupper($item[ $key ]), strtoupper($value));
                });
            }
        }

        //__________

        $listSort = $this->parsePostPrefix($post, 'tri_');
        if (!empty($listSort)) {
            usort($list, function ($a, $b) use ($listSort) {
                foreach ($listSort as $key => $value) {
                    $cmp = $value == 'ASC'
                        ? $a[$key] <=> $b[$key]
                        : $b[$key] <=> $a[$key];
                    if ($cmp != 0) {
                        return $cmp;
                    }
                }
                return 0;
            });
        }

        return array_values($list);// array_values is requiered by Paginator // TODO : clean up Paginator
    }

    /**
     * @param array<mixed> $post
     * @return array<mixed>
     */
    private function parsePostPrefix(array $post, string $prefix)
    {
        $tmp = [];
        foreach ($post as $key => $value) {
            if (! str_starts_with($key, $prefix)) {
                continue;
            }
            $tmp[ StringHelper::removePrefix($key, $prefix) ] = $value;
        }
        return $tmp;
    }
}
