<?php
namespace Gestoreasy\Core\Fiscal\Sped;

use PDO;
use Gestoreasy\Core\Tenant\ConnectionManager;
use Gestoreasy\Core\Fiscal\Sped\Blocks\Block0;
use Gestoreasy\Core\Fiscal\Sped\Blocks\BlockC;
use Gestoreasy\Core\Fiscal\Sped\Blocks\BlockE;
use Gestoreasy\Core\Fiscal\Sped\Blocks\Block1;
use Gestoreasy\Core\Fiscal\Sped\Blocks\BlockH;
use Gestoreasy\Core\Fiscal\Sped\Blocks\BlockK;
use Gestoreasy\Core\Fiscal\Sped\Blocks\Block9;

class SpedFiscalGenerator {
    private PDO $pdo;
    public function __construct(?PDO $pdo = null) { $this->pdo = $pdo ?: ConnectionManager::forTenant(); }

    /**
     * Generate full SPED file lines for given period and options.
     * Options may include: perfil (A/B/C), ind_ativ, cod_fin, cod_ver
     */
    public function generate(Period $period, array $options = []): array {
        $lines = [];
        // Ordem dos blocos: 0, C, D, E, H, K, 1
        $blocks = [ new Block0(), new BlockC(), new \Gestoreasy\Core\Fiscal\Sped\Blocks\BlockD(), new BlockE(), new BlockH(), new BlockK(), new Block1() ];
        foreach ($blocks as $b) { $lines = array_merge($lines, $b->generate($this->pdo, $period, $options)); }
        $b9 = new Block9();
        $lines = array_merge($lines, $b9->generate($this->pdo, $period, [ 'all_lines' => $lines, 'total_lines' => null ]));
        return $lines;
    }

    public function toTxt(array $lines): string {
        $norm = array_map(function($l){
            // Ensure line starts with '|', ends with '|'
            $s = trim($l);
            if ($s === '') return '';
            if ($s[0] !== '|') $s = '|'.$s;
            if (substr($s, -1) !== '|') $s = $s.'|';
            return $s;
        }, $lines);
        return implode("\r\n", $norm);
    }
}