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

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

class BCI extends Banco
{
    use withSubBancos;

    protected function columnMap(): array
    {
        return [
            'Fecha Transacción' => 'fecha',
            'Cargo $ (-)' => 'cargo',
            'Abono $ (+)' => 'abono',
            'Descripción' => 'glosa',
            'Saldo' => 'saldo',
            'Categoría' => 'categoria',
            'Centro costos' => 'centro_costo',
            'Detalle' => 'detalle',
            'Factura Boleta' => 'identificador',
            'RUT' => 'rut',
            'Nombres' => 'nombres',
        ];
    }
    protected function getFilename(UploadedFileInterface $uploadedFile): string
    {
        return '/tmp/cartola.xlsx';
    }
    protected function parseFile(string $filename): array
    {
        try {
            $reader = PhpSpreadsheet\IOFactory::createReader('Xlsx');
        } catch (PhpSpreadsheet\Reader\Exception $exception) {
            $this->logger->critical($exception, ['filename' => $filename]);
            return [];
        }
        $xlsx = $reader->load($filename);
        $worksheet = $xlsx->getActiveSheet();
        $rows = $worksheet->getRowIterator();

        $rows->seek(3);
        $row = $rows->current();
        $columnIterator = $row->getColumnIterator();
        $saldoFinal = 0;
        foreach ($columnIterator as $column) {
            if ($column->getValue() === null) {
                continue;
            }
            if ($column->getCalculatedValue() === 'Saldo Contable') {
                $columnIterator->next();
                $column = $columnIterator->current();
                $saldoFinal = (int) str_replace('.', '', $column->getCalculatedValue());
                break;
            }
        }
        $saldo = $saldoFinal;

        $data = [];
        $columns = [];
        $dataFound = false;
        foreach ($rows as $row) {
            if (!$dataFound and $worksheet->getCell([1, $row->getRowIndex()])->getCalculatedValue() !== null
                    and trim($worksheet->getCell([1, $row->getRowIndex()])->getCalculatedValue()) === 'Fecha Contable') {
                $dataFound = true;
                $columns = $this->getRowData($row);
                continue;
            }
            if (!$dataFound) {
                continue;
            }
            if ($worksheet->getCell([1, $row->getRowIndex()])->getValue() === null) {
                break;
            }
            $rowData = $this->getRowData($row);
            $rowData = array_combine($columns, $rowData);
            $rowData['Fecha Transacción'] = implode('-', array_reverse(explode('/', $rowData['Fecha Transacción'])));
            $rowData['Cargo $ (-)'] = (int) str_replace('.', '', $rowData['Cargo $ (-)'] ?? 0);
            $rowData['Abono $ (+)'] = (int) str_replace('.', '', $rowData['Abono $ (+)'] ?? 0);
            $rowData['Saldo'] = $saldo;
            $saldo = $saldo + $rowData['Cargo $ (-)'] - $rowData['Abono $ (+)'];
            unset($rowData['']);

            $data []= $rowData;
        }
        return array_reverse($data);
    }

    protected function getRowData(PhpSpreadsheet\Worksheet\Row $row): array
    {
        $data = [];
        $cells = $row->getColumnIterator();
        foreach ($cells as $cell) {
            $data []= $cell->getCalculatedValue();
        }
        return $data;
    }
}
