<?php
/**
 * This file is part of FacturaScripts
 * Copyright (C) 2013-2025 Carlos Garcia Gomez <carlos@facturascripts.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

namespace FacturaScripts\Core\Model;

use FacturaScripts\Core\DataSrc\Series;
use FacturaScripts\Core\Template\ModelClass;
use FacturaScripts\Core\Template\ModelTrait;
use FacturaScripts\Core\Tools;

/**
 * A series of invoicing or accounting, to have different numbering
 * in each series.
 *
 * @author Carlos García Gómez <carlos@facturascripts.com>
 */
class Serie extends ModelClass
{
    use ModelTrait;

    /** Canal contable asociado a la serie. @var int */
    public $canal;

    /** Código identificativo de la serie. @var string */
    public $codserie;

    /** Descripción de la serie de facturación. @var string */
    public $descripcion;

    /** Identificador del diario contable asociado. @var int */
    public $iddiario;

    /** Indica si los documentos de la serie se emiten sin impuestos. @var bool */
    public $siniva;

    /** Tipo de serie: simplificada, rectificativa u ordinaria. @var string */
    public $tipo;

    public function clear(): void
    {
        parent::clear();
        $this->siniva = false;
    }

    public function clearCache(): void
    {
        parent::clearCache();
        Series::clear();
    }

    public function delete(): bool
    {
        if ($this->isDefault()) {
            Tools::log()->warning('cant-delete-default-serie');
            return false;
        }

        return parent::delete();
    }

    public function install(): string
    {
        // needed dependencies
        new Diario();

        return parent::install();
    }

    /**
     * Returns True if this is the default serie.
     *
     * @return bool
     */
    public function isDefault(): bool
    {
        return $this->codserie === Tools::settings('default', 'codserie');
    }

    public static function primaryColumn(): string
    {
        return 'codserie';
    }

    public static function tableName(): string
    {
        return 'series';
    }

    public function test(): bool
    {
        $this->codserie = trim($this->codserie ?? '');
        if ($this->codserie && 1 !== preg_match('/^[A-Z0-9_\+\.\-]{1,4}$/i', $this->codserie)) {
            Tools::log()->error(
                'invalid-alphanumeric-code',
                ['%value%' => $this->codserie, '%column%' => 'codserie', '%min%' => '1', '%max%' => '4']
            );
            return false;
        }

        $this->descripcion = Tools::noHtml($this->descripcion);

        return parent::test();
    }

    protected function saveInsert(): bool
    {
        if (empty($this->codserie)) {
            $this->codserie = $this->newLetterCode();
        }

        return parent::saveInsert();
    }

    private function newLetterCode(): string
    {
        // try prefixes from the description (1 to 4 chars)
        $desc = preg_replace('/[^A-Z0-9_\+\.\-]/i', '', strtoupper($this->descripcion ?? ''));
        for ($len = 1; $len <= 4; $len++) {
            $candidate = substr($desc, 0, $len);
            if (strlen($candidate) === $len && false === $this->codserieExists($candidate)) {
                return $candidate;
            }
        }

        // fall back to A-Z
        for ($letter = 'A'; $letter <= 'Z'; $letter++) {
            if (false === $this->codserieExists($letter)) {
                return $letter;
            }
        }

        return (string)$this->newCode();
    }

    private function codserieExists(string $codserie): bool
    {
        foreach (Series::all() as $serie) {
            if (strtoupper($serie->codserie) === strtoupper($codserie)) {
                return true;
            }
        }

        return false;
    }
}
