<?php

declare(strict_types=1);

namespace App\Models;

class Tax extends BaseModel
{
    protected string $table = 'impuestos';

    public function listByCompany(int $companyId): array
    {
        $stmt = $this->db()->prepare(
            'SELECT
                id,
                empresa_id,
                nombre,
                porcentaje,
                tipo,
                activo,
                (empresa_id IS NULL) AS es_global
             FROM impuestos
             WHERE empresa_id = :empresa_id
                OR empresa_id IS NULL
             ORDER BY es_global DESC, nombre ASC'
        );
        $stmt->execute([':empresa_id' => $companyId]);

        return $stmt->fetchAll() ?: [];
    }

    public function listActiveByCompany(int $companyId): array
    {
        $stmt = $this->db()->prepare(
            'SELECT
                id,
                empresa_id,
                nombre,
                porcentaje,
                tipo,
                activo,
                (empresa_id IS NULL) AS es_global
             FROM impuestos
             WHERE (empresa_id = :empresa_id OR empresa_id IS NULL)
               AND activo = 1
             ORDER BY es_global DESC, nombre ASC'
        );
        $stmt->execute([':empresa_id' => $companyId]);

        return $stmt->fetchAll() ?: [];
    }

    public function findAvailableForCompanyById(int $companyId, int $taxId): ?array
    {
        $stmt = $this->db()->prepare(
            'SELECT
                id,
                empresa_id,
                nombre,
                porcentaje,
                tipo,
                activo,
                (empresa_id IS NULL) AS es_global
             FROM impuestos
             WHERE id = :id
               AND (empresa_id = :empresa_id OR empresa_id IS NULL)
             LIMIT 1'
        );
        $stmt->execute([
            ':id' => $taxId,
            ':empresa_id' => $companyId,
        ]);

        $tax = $stmt->fetch();
        return $tax ?: null;
    }
}
