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

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

class Itau extends Banco
{
    use isExcel;

    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',
            'Saldo diario' => 'saldo',
            'Documentos' => 'documento',
            'Movimientos' => 'glosa',
            'Saldos' => 'saldo',
            'Categoría' => 'categoria',
            'Centro costo' => 'centro_costo',
            'Detalle' => 'detalle',
            'Factura Boleta' => 'identificador',
            'RUT' => 'rut',
            'Nombres' => 'nombres',
            'Depto' => 'identificador',
        ];
    }
    protected function getFilename(UploadedFileInterface $uploadedFile): string
    {
        $ext = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
        return "/tmp/cartola.{$ext}";
    }
    protected function parseFile(string $filename): array
    {
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        $reader = PhpSpreadsheet\IOFactory::createReader(ucwords($ext));
        $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);
        }
        return $data;
    }
    protected function parseCuentaCorriente(PhpSpreadsheet\Worksheet\Worksheet $sheet): array
    {
        $titleValueMap = [
            'Giros o cargos' => 'int',
            'Depósitos o abonos' => 'int',
            'Saldos' => 'int',
            'Saldo diario' => 'int',
        ];
        $found = false;
        $year = 0;
        $columns = [];
        $data = [];
        $rowIterator = $sheet->getRowIterator();
        while ($rowIterator->valid()) {
            $row = $rowIterator->current();
            if ($sheet->getCell("A{$row->getRowIndex()}")->getCalculatedValue() === 'Cartola Histórica') {
                $range = $this->getDateRange($row);
                $year = $range[0]->format('Y');
                $rowIterator->next();
                continue;
            }
            if ($sheet->getCell("A{$row->getRowIndex()}")->getCalculatedValue() === 'Movimientos') {
                $found = true;
                $rowIterator->next();
                $row = $rowIterator->current();
                $columns = $this->grabTitlesRow($row);
                $rowIterator->next();
                continue;
            }
            if (!$found) {
                $rowIterator->next();
                continue;
            }
            if ($sheet->getCell("A{$row->getRowIndex()}")->getValue() === null) {
                break;
            }
            $rowData = $this->grabRow($row, $columns, process: true, titleValueMap: $titleValueMap);
            $fecha = explode('/', $rowData['Fecha']);
            $rowData['Fecha'] = "{$year}-{$fecha[1]}-{$fecha[0]}";
            $data []= $rowData;

            $rowIterator->next();
        }

        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') {
                    if ($value === '') {
                        continue;
                    }
                    $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;
        }
        // Remove empty rows
        return array_filter($data, function($data) {
            $empties = 0;
            foreach ($data as $field) {
                if ($field === '' or $field === null or $field === 0) {
                    $empties++;
                }
            }
            return $empties < count($data) - 1;
        });
    }

    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();
    }
    protected function getDateRange(PhpSpreadsheet\Worksheet\Row $row): array
    {
        $columnIndex = 'A';
        $columnIterator = $row->getColumnIterator();
        while ($columnIterator->valid()) {
            $column = $columnIterator->current();
            if (str_contains($column->getValue(), '-')) {
                $columnIndex = $column->getColumn();
                break;
            }
            $columnIterator->next();
        }
        $value = $row->getWorksheet()->getCell("{$columnIndex}{$row->getRowIndex()}")->getCalculatedValue();
        $dates = explode(' - ', $value);
        return array_map(function($date) {
            return DateTimeImmutable::createFromFormat('d/m/Y', $date);
        }, $dates);
    }
}
