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

/**
 * A fee for the products.
 *
 * @author Carlos García Gómez <carlos@facturascripts.com>
 */
class Tarifa extends ModelClass
{
    use ModelTrait;

    const APPLY_COST = 'coste';
    const APPLY_PRICE = 'pvp';

    /** Base sobre la que se aplica la fórmula: coste o precio de venta. @var string */
    public $aplicar;

    /** Código identificativo de la tarifa. @var string */
    public $codtarifa;

    /** Indica si el precio calculado no puede superar el precio de venta. @var bool */
    public $maxpvp;

    /** Indica si el precio calculado no puede ser inferior al coste. @var bool */
    public $mincoste;

    /** Nombre de la tarifa. @var string */
    public $nombre;

    /** Porcentaje que se suma o resta en la fórmula de la tarifa. @var float */
    public $valorx;

    /** Importe fijo que se suma o resta en la fórmula de la tarifa. @var float */
    public $valory;

    /**
     * @param float $cost
     * @param float $price
     *
     * @return float
     */
    public function apply(float $cost, float $price): float
    {
        $finalPrice = 0.0;

        switch ($this->aplicar) {
            case self::APPLY_COST:
                $finalPrice += $cost + ($cost * $this->valorx / 100) + $this->valory;
                break;

            case self::APPLY_PRICE:
                $finalPrice += $price - ($price * $this->valorx / 100) - $this->valory;
                break;
        }

        $ext = $this->pipe('apply', $finalPrice, $cost, $price);
        if ($ext && is_numeric($ext)) {
            $finalPrice = $ext;
        }

        // Aplicar límite máximo de pvp si corresponde
        if ($this->maxpvp && $finalPrice > $price) {
            $finalPrice = (float)$price;
        }

        // Aplicar límite mínimo de coste (tiene prioridad sobre maxpvp)
        if ($this->mincoste && $finalPrice < $cost) {
            return (float)$cost;
        }

        return $finalPrice;
    }

    /**
     * @param Variante $variant
     * @param Producto $product
     *
     * @return float
     */
    public function applyTo($variant, $product): float
    {
        return $this->apply((float)$variant->coste, (float)$variant->precio);
    }

    public function clear(): void
    {
        parent::clear();
        $this->aplicar = self::APPLY_PRICE;
        $this->maxpvp = false;
        $this->mincoste = false;
        $this->valorx = 0.0;
        $this->valory = 0.0;
    }

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

    public function primaryDescriptionColumn(): string
    {
        return 'nombre';
    }

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

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

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

        return parent::test();
    }

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

        return parent::saveInsert();
    }
}
