<?php
/**
 * This file is part of FacturaScripts
 * Copyright (C) 2015-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\Retenciones;
use FacturaScripts\Core\Template\ModelClass;
use FacturaScripts\Core\Template\ModelTrait;
use FacturaScripts\Core\Tools;
use FacturaScripts\Core\Where;

/**
 * Class to manage the data of retenciones table
 *
 * @author Carlos García Gómez          <carlos@facturascripts.com>
 * @author Cristo M. Estévez Hernández  <cristom.estevez@gmail.com>
 * @author Rafael San José Tovar        <rafael.sanjose@x-netdigital.com>
 */
class Retencion extends ModelClass
{
    use ModelTrait;

    /** Indica si la retención está activa. @var bool */
    public $activa;

    /** Código identificativo de la retención. @var string */
    public $codretencion;

    /** Código de la subcuenta contable de retenciones. @var string */
    public $codsubcuentaret;

    /** Código de la subcuenta acreedora asociada. @var string */
    public $codsubcuentaacr;

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

    /** Porcentaje de retención aplicado. @var int */
    public $porcentaje;

    public function clear(): void
    {
        parent::clear();
        $this->activa = true;
        $this->porcentaje = 0.0;
    }

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

    public function loadFromPercentage(float $percentaje): bool
    {
        $where = [Where::eq('porcentaje', $percentaje)];
        $order = ['codretencion' => 'ASC'];
        return $this->loadWhere($where, $order);
    }

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

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

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

        $this->codsubcuentaret = empty($this->codsubcuentaret) ? null : $this->codsubcuentaret;
        $this->codsubcuentaacr = empty($this->codsubcuentaacr) ? null : $this->codsubcuentaacr;
        $this->descripcion = Tools::noHtml($this->descripcion);

        if (empty($this->porcentaje) || intval($this->porcentaje) < 1) {
            Tools::log()->warning('not-valid-percentage-retention');
            return false;
        }

        return parent::test();
    }

    public function url(string $type = 'auto', string $list = 'ListImpuesto?activetab=List'): string
    {
        return parent::url($type, $list);
    }

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

        return parent::saveInsert();
    }

    private function newLetterCode(): string
    {
        $desc = preg_replace('/[^A-Z]/i', '', strtoupper($this->descripcion ?? ''));
        $pct = (int)$this->porcentaje;

        // try 3 letters + percentage
        $prefix3 = substr($desc, 0, 3);
        if (strlen($prefix3) === 3) {
            $candidate = $prefix3 . $pct;
            if (false === $this->codretencionExists($candidate)) {
                return $candidate;
            }
        }

        // try 4 letters + percentage
        $prefix4 = substr($desc, 0, 4);
        if (strlen($prefix4) === 4) {
            $candidate = $prefix4 . $pct;
            if (false === $this->codretencionExists($candidate)) {
                return $candidate;
            }
        }

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

    private function codretencionExists(string $codretencion): bool
    {
        foreach (Retenciones::all() as $retencion) {
            if (strtoupper($retencion->codretencion) === strtoupper($codretencion)) {
                return true;
            }
        }

        return false;
    }
}
