<?php
// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: RecordFilterLastDate.php,v 1.1.4.2 2026/04/30 09:26:09 rtigero Exp $

namespace Pmb\DSI\Models\Filter\Entities\Record\RecordFilterLastDate;

use Pmb\DSI\Models\Filter\Entities\Record\RecordFilter;

class RecordFilterLastDate extends RecordFilter
{
    public static $fields = [
        "field_nb_days" => [
            "type" => "number",
            "required" => true
        ],
        "last_date" => [
            "type" => "date"
        ],
        "current_day" => [
            "type" => "checkbox"
        ]
    ];

    public function __construct(array $data, int $entityId = 0)
    {
        parent::__construct($data, $entityId);
    }

    public function filter(): array
    {
        $filteredData = [];
        $lastDate = null;

        if(isset($this->fieldsValues->current_day) && true == $this->fieldsValues->current_day) {
            $lastDate = new \Datetime();
        } else if(isset($this->fieldsValues->last_date) && !empty($this->fieldsValues->last_date)) {
            $lastDate = new \Datetime($this->fieldsValues->last_date);
        }

        //Si on n'a pas de dernière diffusion on renvoie tout
        if (is_null($lastDate)) {
            return $this->data;
        }
        $nbDays = new \DateInterval("P" . abs($this->fieldsValues->field_nb_days) . "D");

        // Rend l'intervalle négatif
        if ($this->fieldsValues->field_nb_days < 0) {
            $nbDays->invert = 1;
        }

        $lastDate->add($nbDays);

        foreach ($this->data as $id => $item) {
            $notice = new \notice($id);
            $date = \DateTime::createFromFormat("d/m/Y H:i:s", $notice->create_date);

            if (!$date) {
                // Ignore les entrées avec des dates invalides
                continue;
            }

            if ($date->format("U") > $lastDate->format("U")) {
                $filteredData[$id] = $item;
            }
        }

        return $filteredData;
    }
}
