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

use PDO;
use Gestoreasy\Core\Fiscal\Sped\BlockInterface;
use Gestoreasy\Core\Fiscal\Sped\Period;

class Block9 implements BlockInterface {
    private array $countsByReg = [];
    public function id(): string { return '9'; }

    /**
     * Block 9 must be generated after other blocks to count records per REG.
     * Pass option 'all_lines' => array of lines previously generated.
     */
    public function generate(PDO $pdo, Period $period, array $options = []): array {
        $lines = [];
        $all = is_array($options['all_lines'] ?? null) ? $options['all_lines'] : [];
        $this->countsByReg = $this->countRegs($all);

        // 9001 - Abertura do bloco 9
        $lines[] = '|9001|0|';

        // 9900 - Registro do número de ocorrências por registro
        foreach ($this->countsByReg as $reg => $count) {
            $lines[] = sprintf('|9900|%s|%d|', $reg, $count);
        }

        // 9990 - Encerramento do Bloco 9
        $qtd_lin_9 = count($lines) + 1; // + 1 para 9999
        $lines[] = sprintf('|9990|%d|', $qtd_lin_9);

        // 9999 - Encerramento do arquivo digital
        $qtd_lin = (int)($options['total_lines'] ?? (count($all) + count($lines) + 1)); // +1 considerando 9999
        $lines[] = sprintf('|9999|%d|', $qtd_lin);

        return $lines;
    }

    private function countRegs(array $lines): array {
        $counts = [];
        foreach ($lines as $ln) {
            // line format starts with |REG|; REG = 4 chars typically, but block 0 uses 0000/0001 etc
            if (preg_match('/^\|([0-9A-Z]{4})\|/', $ln, $m)) {
                $reg = $m[1];
                $counts[$reg] = ($counts[$reg] ?? 0) + 1;
            }
        }
        // Include required own regs with at least 1 occurrence
        foreach (['9001','9900','9990','9999'] as $reg) {
            if (!isset($counts[$reg])) $counts[$reg] = 0; // será preenchido por este bloco
        }
        ksort($counts);
        return $counts;
    }
}