<?php
// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: RecordFilterLastDiffusion.php,v 1.5.4.3 2026/06/19 14:02:08 jparis Exp $

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

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

class RecordFilterLastDiffusion extends RecordFilter
{
    public static $fields = [
        "field_nb_days" => [
            "type" => "number",
            "required" => true
        ]
    ];
    public function __construct(array $data, int $entityId = 0)
    {
        parent::__construct($data, $entityId);
    }

    public function filter(): array
    {
        $lastDiffusionDate = $this->getLastDiffusionDate();

        //Si on n'a pas de derniere diffusion on renvoie tout
        if (is_null($lastDiffusionDate)) {
            return $this->data;
        }

        if (empty($this->data)) {
            return [];
        }

        $nbDays = new \DateInterval("P" . abs(intval($this->fieldsValues->field_nb_days)) . "D");

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

        $lastDiffusionDate->add($nbDays);

        return $this->filterByCreateDate($lastDiffusionDate);
    }
}
