<?php
namespace Incoviba\Service\Contabilidad\Cartola;

use DateTimeImmutable;
use DOMDocument;
use Incoviba\Common\Ideal\Cartola\Banco;
use PhpOffice\PhpSpreadsheet;
use Psr\Http\Message\UploadedFileInterface;

class Security extends Banco
{
    use isExcel;

    public function processMovimientosDiarios(array $movimientos): array
    {
        $movimientos = array_reverse($movimientos);
        array_shift($movimientos);
        return $movimientos;
    }

    protected function getFilename(UploadedFileInterface $uploadedFile): string
    {
        $stream = $uploadedFile->getStream();
        $stream->seek(3);
        if ($stream->read(strlen('table')) === 'table') {
            return '/tmp/cartola.htm';
        }
        return '/tmp/cartola.xls';
    }
    protected function parseFile(string $filename): array
    {
        if (str_ends_with($filename, '.htm')) {
            return $this->processHtm($filename);
        }
        return $this->processXls($filename);
    }
    protected function columnMap(): array
    {
        return [
            'fecha' => 'fecha',
            'descripción' => 'glosa',
            'número de documentos' => 'documento',
            'nº documento' => 'documento',
            'n de docu' => 'documento',
            'cargos' => 'cargo',
            'abonos' => 'abono',
            'saldos' => 'saldo',
            'categoría' => 'categoria',
            'centro costos' => 'centro_costo',
            'centro costo' => 'centro_costo',
            'detalle' => 'detalle',
            'factura boleta' => 'identificador',
            'rut' => 'rut',
            'nombres' => 'nombres',
            'depto' => 'identificador',
        ];
    }

    private function processXls(string $filename): array
    {
        $xlsx = @PhpSpreadsheet\IOFactory::load($filename);
        $worksheet = $xlsx->getActiveSheet();

        $rowIterator = $worksheet->getRowIterator(3);
        $titleRow = $this->findTitlesRow($rowIterator, 'fecha', caseInsensitive: true);
        $columns = $this->grabTitlesRow($titleRow, toLower: true);
        $rowIterator->next();

        $titleValueMap = [
            'fecha' => 'fecha',
            'cargos' => 'int',
            'abonos' => 'int',
            'saldos' => 'int',
            'centro costo' => 'int',
            'centro costos' => 'int',
        ];
        $data = [];
        while ($rowIterator->valid()) {
            if ($this->isExitValue($rowIterator->current(), ['resúmen del período', 'resumen del período', 'Resúmen del período', 'Resumen del período', null])) {
                break;
            }
            $rowData = $this->grabRow($rowIterator->current(), $columns, process: true, titleValueMap: $titleValueMap);
            if (count($rowData) > 0) {
                $data []= $rowData;
            }
            $rowIterator->next();
        }
        return $data;
    }
    private function processHtm(string $filename): array
    {
        $domDocument = new DOMDocument();
        $domDocument->loadHTML('<body>' . file_get_contents($filename) . '</body>');

        $tables = $domDocument->getElementsByTagName('table');
        $table = $tables->item(4);

        $columns = [];
        $data = [];
        foreach ($table->getElementsByTagName('tr')->getIterator() as $rowIndex => $row) {
            if ($rowIndex === 0) {
                continue;
            }
            if (str_contains($row->textContent, 'cargos')) {
                foreach ($row->getElementsByTagName('td')->getIterator() as $cell) {
                    $columns []= trim($cell->textContent);
                }
                continue;
            }
            $rowData = [];
            foreach ($row->getElementsByTagName('td')->getIterator() as $colIndex => $cell) {
                $col = $columns[$colIndex];
                $value = trim($cell->textContent);
                if ($col === 'fecha') {
                    $value = DateTimeImmutable::createFromFormat('d/m/Y', $value)->format('Y-m-d');
                }
                if (in_array($col, ['cargos', 'abonos', 'saldos'])) {
                    $value = (float) str_replace(',', '.', $value);
                }
                $rowData[$col] = $value;
            }
            $data []= $rowData;
        }
        return $data;
    }
}
