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

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

class Mes extends Banco
{
    public function is(string $filename): bool
    {
        if (!str_ends_with($filename, 'xlsx')) {
            return false;
        }
        try {
            $reader = PhpSpreadsheet\IOFactory::createReader('Xlsx');
        } catch (PhpSpreadsheet\Reader\Exception) {
            return false;
        }
        $xlsx = $reader->load($filename);
        $sheet = $xlsx->getActiveSheet();
        $subtitle = $sheet->getCell('A2')->getCalculatedValue();
        return trim($subtitle) === 'Cartola de cuenta corriente';
    }

    protected function columnMap(): array
    {
        return [
            'Fecha' => 'fecha',
            'Descripción' => 'glosa',
            'N° Documento' => 'identificador',
            'Cheques y otros cargos' => 'cargo',
            'Depósitos y Abono' => 'abono',
            'Saldo diario' => '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);
        $sheet = $xlsx->getActiveSheet();

        $valueColumns = [
            'cargo',
            'abono',
            'saldo',
        ];
        $found = false;
        $columns = [];
        $data = [];
        foreach ($sheet->getRowIterator() as $row) {
            if (!$found and $sheet->getCell("A{$row->getRowIndex()}")->getCalculatedValue() === 'Fecha') {
                $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] ?? $column;
                if ($mapped === 'fecha') {
                    if (is_int($value)) {
                        $value = PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value)->format('Y-m-d');
                    } else {
                        $value = implode('-', array_reverse(explode('/', $value)));
                    }
                }
                if (in_array($mapped, $valueColumns)) {
                    $value = (int) $value;
                }
                $rowData[$column] = $value;
            }

            $data []= $rowData;
        }
        return $data;
    }
}
