<?php
namespace Incoviba\Service\Cartola;

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

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

    protected function parseFile(UploadedFileInterface $uploadedFile): array
    {
        $stream = $uploadedFile->getStream();
        $stream->seek(3);
        if ($stream->read(strlen('table')) === 'table') {
            return $this->processHtm($uploadedFile);
        }
        return $this->processXls($uploadedFile);
    }
    protected function columnMap(): array
    {
        return [
            'fecha' => 'fecha',
            'descripción' => 'glosa',
            'número de documentos' => 'documento',
            'nº documento' => 'documento',
            'cargos' => 'cargo',
            'abonos' => 'abono',
            'saldos' => 'saldo'
        ];
    }

    private function processXls(UploadedFileInterface $file): array
    {
        $filename = '/tmp/cartola.xls';
        $file->moveTo($filename);
        $xlsx = @PhpSpreadsheet\IOFactory::load($filename);
        $worksheet = $xlsx->getActiveSheet();
        $rows = $worksheet->getRowIterator(3);
        $dataFound = false;
        $columns = [];
        $data = [];
        foreach ($rows as $row) {
            $cells = $row->getCellIterator();
            $rowData = [];
            foreach ($cells as $cell) {
                if ($cell->getColumn() === 'A' and $cell->getCalculatedValue() !== null and strtolower($cell->getCalculatedValue()) === "fecha ") {
                    $cols = $row->getColumnIterator();
                    foreach ($cols as $col) {
                        $columns[$col->getColumn()] = trim(strtolower($col->getCalculatedValue()), '  ');
                    }
                    $dataFound = true;
                    break;
                }
                if ($cell->getColumn() === 'A' and $cell->getCalculatedValue() === null) {
                    $dataFound = false;
                    break;
                }
                if (!$dataFound) {
                    break;
                }
                $col = $columns[$cell->getColumn()];
                $value = $cell->getCalculatedValue();
                if ($col === 'fecha') {
                    if ((int) $cell->getValue() !== $cell->getValue()) {
                        $value = implode('-', array_reverse(explode('-', $cell->getValue())));
                    } else {
                        $value = PhpSpreadsheet\Shared\Date::excelToDateTimeObject($cell->getValue(), 'America/Santiago')->format('Y-m-d');
                    }
                }
                $rowData[$col] = $value;
            }
            if (count($rowData) > 0) {
                $data []= $rowData;
            }
        }
        unlink($filename);
        return $data;
    }
    private function processHtm(UploadedFileInterface $file): array
    {
        $filename = '/tmp/cartola.htm';
        $file->moveTo($filename);

        $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;
    }
}
