<?php
namespace Incoviba\Service\Cartola;

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

class Itau extends Banco
{
    const CUENTA_CORRIENTE = 0;
    const ULTIMOS_MOVIMIENTOS = 1;

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

    protected function columnMap(): array
    {
        return [
            'Fecha' => 'fecha',
            'Número de operación' => 'documento',
            'Descripción' => 'glosa',
            'Depósitos o abonos' => 'abono',
            'Giros o cargos' => 'cargo',
            'Documentos' => 'documento',
            'Movimientos' => 'glosa',
            'Saldos' => 'saldo'
        ];
    }

    protected function parseFile(UploadedFileInterface $uploadedFile): array
    {
        $filename = '/tmp/cartola.xls';
        $uploadedFile->moveTo($filename);

        $reader = PhpSpreadsheet\IOFactory::createReader('Xls');
        $xlsx = $reader->load($filename);
        $sheet = $xlsx->getActiveSheet();

        $data = [];
        try {
            switch ($this->identifySheet($sheet)) {
                case self::CUENTA_CORRIENTE:
                    $data = $this->parseCuentaCorriente($sheet);
                    break;
                case self::ULTIMOS_MOVIMIENTOS:
                    $data = $this->parseUltimosMovimientos($sheet);
                    break;
            }
        } catch (PhpSpreadsheet\Exception $exception) {
            $this->logger->critical($exception);
        } finally {
            unlink($filename);
        }
        return $data;
    }
    protected function parseCuentaCorriente(PhpSpreadsheet\Worksheet\Worksheet $sheet): array
    {
        $found = false;
        $year = 0;
        $columns = [];
        $data = [];
        foreach ($sheet->getRowIterator() as $row) {
            if (!$found and $sheet->getCell("A{$row->getRowIndex()}")->getCalculatedValue() === 'Cartola Histórica') {
                $columnIndex = 'A';
                foreach ($row->getColumnIterator() as $column) {
                    if ($column->getValue() !== 'Periodo') {
                        continue;
                    }
                    $columnIndex = $column->getColumn();
                    break;
                }
                $dates = explode(' - ', $sheet->getCell("{$columnIndex}{$row->getRowIndex()}")->getCalculatedValue());
                $date = DateTimeImmutable::createFromFormat('d/m/Y', $dates[0]);
                $year = $date->format('Y');
            }
            if (!$found and $sheet->getCell("A{$row->getRowIndex()}")->getCalculatedValue() === 'Movimientos') {
                $found = true;
                foreach ($row->getColumnIterator() as $column) {
                    if ($column->getValue() === null) {
                        break;
                    }
                    $columns[$column->getColumn()] = trim($column->getValue());
                }
                continue;
            }
            if (!$found) {
                continue;
            }
            if ($sheet->getCell("A{$row->getRowIndex()}")->getValue() === null) {
                break;
            }
            $rowData = [];
            foreach ($columns as $columnIndex => $column) {
                $value = $sheet->getCell("{$columnIndex}{$row->getRowIndex()}")->getCalculatedValue();
                $mapped = $this->columnMap()[$column];
                if ($mapped === 'fecha') {
                    list($d, $m) = explode('/', $value);
                    $value = "{$year}-{$m}-{$d}";
                }
                if (in_array($mapped, ['cargo', 'abono', 'saldo'])) {
                    $value = (int) $value;
                }
                $rowData[$column] = $value;
            }
            $data []= $rowData;
        }

        return $data;
    }
    protected function parseUltimosMovimientos(PhpSpreadsheet\Worksheet\Worksheet $sheet): array
    {
        $found = false;
        $data = [];
        $columns = [];
        foreach ($sheet->getRowIterator() as $row) {
            if (!$found and $sheet->getCell("A{$row->getRowIndex()}")->getCalculatedValue() === 'Últimos Movimientos') {
                $found = true;
                continue;
            }
            if (!$found) {
                continue;
            }
            if (count($columns) === 0) {
                foreach ($row->getColumnIterator() as $cell) {
                    if ($cell->getValue() === null) {
                        break;
                    }
                    $columns[$cell->getColumn()] = trim($cell->getValue());
                }
                continue;
            }
            if ($sheet->getCell("A{$row->getRowIndex()}")->getValue() === null) {
                break;
            }
            $rowData = [];
            foreach ($columns as $columnIndex => $column) {
                $value = $sheet->getCell("{$columnIndex}{$row->getRowIndex()}")->getCalculatedValue();
                $mapped = $this->columnMap()[$column] ?? $column;
                if ($mapped === 'fecha') {
                    $value = PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value, 'America/Santiago')->format('Y-m-d');
                }
                if (in_array($mapped, ['abono', 'cargo', 'saldo'])) {
                    $value = (int) $value;
                }
                $rowData[$column] = $value;
            }
            $data []= $rowData;
        }
        return $data;
    }

    protected function identifySheet(PhpSpreadsheet\Worksheet\Worksheet $sheet): int
    {
        foreach ($sheet->getRowIterator(1, 10) as $row) {
            $value = $sheet->getCell("A{$row->getRowIndex()}")->getValue();
            if ($value === 'Estado de Cuenta Corriente') {
                return self::CUENTA_CORRIENTE;
            }
            if ($value === 'Consulta Saldos y Últimos movimientos') {
                return self::ULTIMOS_MOVIMIENTOS;
            }
        }
        throw new PhpSpreadsheet\Exception();
    }
}
