<?php

/**
 * Questo file è parte di Pongho.
 *
 * @author    Daniele Termini
 * @copyright Web Agency Meta Line S.r.l.
 * @package   Application\Admin
 */

namespace Application\Admin\Model;

use ActiveRecord\Base;

/**
 * @property int                        $id
 * @property string                     $namespace
 * @property string                     $filter
 * @property \Pongho\Utilities\DateTime $created_at
 * @property \Pongho\Utilities\DateTime $updated_at
 * @property int                        $user_id
 */
class Filter extends Base
{
    /**
     * Nome della tabella.
     *
     * @var string
     */
    public static $table_name = 'filters';

    /**
     * Restituisce i filtri deserializzati
     *
     * @return array
     */
    public function getFilters()
    {
        $filters = [];

        if ($this->filter) {
            /** @var $row \Pongho\Form\Repeater\RepeaterRow */
            foreach (unserialize($this->filter) as $filter) {
                // Evito i filtri malformati (es possibili vecchie versioni)
                if (!isset($filter['field']) || !isset($filter['operator']) || !isset($filter['valuefield']) || !isset($filter[$filter['valuefield']])) {
                    continue;
                }

                // Gestione casi particolari
                $filters[$filter['field']][$filter['operator']] = match ($filter['operator']) {
                    'DATEBETWEEN' => [$filter[$filter['valuefield']], $filter[$filter['valuefield'] . '_to']],
                    default       => $filter[$filter['valuefield']],
                };
            }

            return $filters;
        }

        return [];
    }
}
