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

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

class BlockK implements BlockInterface {
    public function id(): string { return 'K'; }

    public function generate(PDO $pdo, Period $period, array $options = []): array {
        $lines = [];
        // Itens de estoque escriturado (simplificado) a partir de products
        $items = $this->stockItems($pdo);
        $hasMovement = !empty($items);

        // K001 - Abertura do Bloco K (ind_mov: 0=com movimento, 1=sem movimento)
        $lines[] = sprintf('|K001|%d|', $hasMovement ? 0 : 1);

        if ($hasMovement) {
            $dt_est = str_replace('-', '', $period->endDate());
            foreach ($items as $it) {
                // |K200|DT_EST|COD_ITEM|QTD|IND_EST|COD_PART|
                $lines[] = sprintf(
                    '|K200|%s|%s|%.3f|%s|%s|',
                    $dt_est,
                    (string)$it['cod_item'],
                    (float)$it['qtd'],
                    '0', // IND_EST: 0 = saldo em estoque escriturado
                    ''   // COD_PART: não mapeado
                );
            }
        }

        // K230/K235 (produção e consumo) — geração condicional via payload
        foreach ($this->generateK230K235($pdo, $period, $options) as $ln) { $lines[] = $ln; }

        // K990 - Encerramento do Bloco K
        $qtd_lin_k = count($lines) + 1;
        $lines[] = sprintf('|K990|%d|', $qtd_lin_k);
        return $lines;
    }

    /**
     * Retorna itens de estoque escriturado a partir de products (qtd = estoque).
     */
    private function stockItems(PDO $pdo): array {
        $out = [];
        try {
            $stmt = $pdo->query('SELECT codigo, unidade, estoque FROM products ORDER BY id ASC');
            while ($row = $stmt->fetch()) {
                $qtd = (float)($row['estoque'] ?? 0);
                if ($qtd <= 0) { continue; }
                $out[] = [
                    'cod_item' => (string)($row['codigo'] ?? ''),
                    'unid' => (string)($row['unidade'] ?? ''),
                    'qtd' => $qtd,
                ];
            }
        } catch (\Throwable $e) { /* tolera ausência de tabela/colunas */ }
        return $out;
    }

    /**
     * Placeholder para geração de K230/K235.
     * Retorna array de linhas quando houver dados de produção/consumo.
     */
    private function generateK230K235(PDO $pdo, Period $period, array $options): array {
        $out = [];
        $k230 = is_array($options['k230'] ?? null) ? $options['k230'] : [];
        $k235 = is_array($options['k235'] ?? null) ? $options['k235'] : [];

        foreach ($k230 as $p) {
            $dt_ini = $this->ymd((string)($p['dt_ini'] ?? $period->startDate()));
            $dt_fin = $this->ymd((string)($p['dt_fin'] ?? $period->endDate()));
            $cod_item = (string)($p['cod_item'] ?? '');
            $qtd = (float)($p['qtd'] ?? 0);
            // |K230|DT_INI|DT_FIN|COD_ITEM|QTD|
            $out[] = sprintf('|K230|%s|%s|%s|%.3f|', $dt_ini, $dt_fin, $cod_item, $qtd);
        }

        foreach ($k235 as $c) {
            $dt_ini = $this->ymd((string)($c['dt_ini'] ?? $period->startDate()));
            $dt_fin = $this->ymd((string)($c['dt_fin'] ?? $period->endDate()));
            $cod_item = (string)($c['cod_item'] ?? '');
            $qtd = (float)($c['qtd'] ?? 0);
            // |K235|DT_INI|DT_FIN|COD_ITEM|QTD|
            $out[] = sprintf('|K235|%s|%s|%s|%.3f|', $dt_ini, $dt_fin, $cod_item, $qtd);
        }

        return $out;
    }

    private function ymd(string $d): string {
        $t = strtotime($d ?: '');
        if ($t === false) return str_replace('-', '', date('Y-m-d'));
        return str_replace('-', '', date('Y-m-d', $t));
    }
}