<?php

declare(strict_types=1);

namespace App\Models;

class PaymentMethod extends BaseModel
{
    protected string $table = 'metodos_pago';

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

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

    public function effectiveForCompany(int $companyId): array
    {
        $rows = $this->listForCompany($companyId);
        if ($rows === []) {
            return [];
        }

        $effective = [];
        $seenCodes = [];

        foreach ($rows as $row) {
            $code = strtolower(trim((string) ($row['codigo'] ?? '')));
            if ($code === '' || isset($seenCodes[$code])) {
                continue;
            }

            $row['codigo'] = $code;
            $effective[] = $row;
            $seenCodes[$code] = true;
        }

        return $effective;
    }

    public function findCompanyByCode(int $companyId, string $code): ?array
    {
        $stmt = $this->db()->prepare(
            'SELECT *
             FROM metodos_pago
             WHERE empresa_id = :empresa_id
               AND codigo = :codigo
             LIMIT 1'
        );
        $stmt->execute([
            ':empresa_id' => $companyId,
            ':codigo' => trim(strtolower($code)),
        ]);
        $row = $stmt->fetch();

        return $row ?: null;
    }

    public function existsCode(int $companyId, string $code): bool
    {
        $stmt = $this->db()->prepare(
            'SELECT 1
             FROM metodos_pago
             WHERE empresa_id = :empresa_id
               AND codigo = :codigo
             LIMIT 1'
        );
        $stmt->execute([
            ':empresa_id' => $companyId,
            ':codigo' => trim(strtolower($code)),
        ]);

        return (bool) $stmt->fetchColumn();
    }

    public function findAnyById(int $id): ?array
    {
        return $this->findById($id, null);
    }
}
