<?php
namespace Gestoreasy\Core\Fiscal\Nfse\Providers;

use Gestoreasy\Core\Fiscal\Nfse\NfseProviderInterface;
use Gestoreasy\Core\Fiscal\TaxConfig;

class DefaultProvider implements NfseProviderInterface
{
    private string $uf;

    public function __construct(string $uf)
    {
        $this->uf = strtoupper($uf);
    }

    public function emit(\PDO $pdo, array $order, array $company, array $client): array
    {
        $valorTotal = (float)($order['valor_total'] ?? $order['valor_total_cents'] / 100.0 ?? 0.0);
        $config = TaxConfig::get($pdo);
        $opts = is_array($config['options'] ?? null) ? $config['options'] : [];
        $nfseOpts = $opts['nfse']['uf_rates'][$this->uf] ?? [];
        $issRate = (float)($nfseOpts['iss'] ?? 0.0);
        $issValor = round($valorTotal * ($issRate / 100.0), 2);

        $numero = $this->generateSequentialNumber($pdo);
        $verification = strtoupper(substr(hash('sha256', $numero . '-' . $this->uf . '-' . ($company['cnpj'] ?? '000')), 0, 8));

        return [
            'provider' => [
                'name' => 'DefaultProvider',
                'uf' => $this->uf,
                'rules' => [ 'iss_rate_percent' => $issRate ],
            ],
            'nfse' => [
                'numero' => $numero,
                'codigo_verificacao' => $verification,
                'data_emissao' => date('c'),
                'valor_servico' => $valorTotal,
                'valor_iss' => $issValor,
                'status' => 'autorizada',
            ],
        ];
    }

    private function generateSequentialNumber(\PDO $pdo): string
    {
        $base = date('Ymd');
        try {
            $r = $pdo->query('SELECT COUNT(*) AS c FROM service_documents WHERE tipo = "nfse"')->fetch();
            $seq = (int)($r['c'] ?? 0) + 1;
            return $base . str_pad((string)$seq, 5, '0', STR_PAD_LEFT);
        } catch (\Throwable $e) {
            return $base . '00001';
        }
    }
}