<?php

namespace App\Libs\Services;

use Saloon\XmlWrangler\Data\Element;
use Saloon\XmlWrangler\XmlWriter;
use Illuminate\Support\Facades\Storage;

class FileService
{
    public function storeFile($data)
    {
        $uniqueName = md5(pathinfo($data['file']->getClientOriginalName(), PATHINFO_FILENAME) . microtime(true));
        $tempFileName = $uniqueName . '.' . $data['file']->getClientOriginalExtension();
        $data['file']->storeAs('temp_document', $tempFileName, 'private');
        return $tempFileName;
    }

    public function readExcelFile($event)
    {
        $staticDataTable = $event->contentTypeModel;
        $excel = $staticDataTable->document;
        $contentTypeSlug = $staticDataTable->lang_slug;

        if (empty($excel)) {
            return;
        }

        $path = config('path.internal.media');
        $fullPath = Storage::path($path . '/' . $excel->filename);
        $pathInfo = pathinfo($excel->filename);
        // $filenameWithoutExtension = $pathInfo['filename'];
        $filenameWithoutExtension = $contentTypeSlug;
        $inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($fullPath);
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
        $reader->setReadDataOnly(false);
        $spreadsheet = $reader->load($fullPath);
        $worksheet = $spreadsheet->getActiveSheet();

        $noEmptyColumnsIdx = [];
        foreach ($worksheet->getRowIterator() as $index => $row) {
            $cellIterator = $row->getCellIterator();

            if ($index === 1) {
                continue;
            }

            foreach ($cellIterator as $cellIndex => $cell) {
                if (!in_array($cellIndex, $noEmptyColumnsIdx) && $cell->getFormattedValue() !== "") {
                    $noEmptyColumnsIdx[] = $cellIndex;
                }
            }
        }

        $arrayValues = [];
        foreach ($worksheet->getRowIterator() as $index => $row) {
            $cellIterator = $row->getCellIterator();

            foreach ($cellIterator as $cellIndex => $cell) {
                if (in_array($cellIndex, $noEmptyColumnsIdx)) {
                    $arrayValues[$index][] = $cell->getFormattedValue();
                }
            }
        }

        $jsonData = json_encode($arrayValues);

        Storage::put($path . '/' . $filenameWithoutExtension . '.json', $jsonData);

        $staticDataTable->json_filename = $filenameWithoutExtension . '.json';
        $staticDataTable->save();

        if (count($arrayValues)) {
            $header = array_shift($arrayValues);
            $xmlWriter = new XmlWriter;

            $xmlFile = $xmlWriter->write('mappings', $this->xmlRows($arrayValues, $header));

            if (!empty($xmlFile)) {
                Storage::put($path . '/' . $filenameWithoutExtension . '.xml', $xmlFile);

                $staticDataTable->xml_filename = $filenameWithoutExtension . '.xml';
                $staticDataTable->save();
            }
        }
    }

    private function xmlRows($arrayRows, $header)
    {
        $arrayResult = [];

        foreach ($arrayRows as $value) {
            $efetArray = [];
            $functionArray = [];
            $stateArray = [];
            $flag = 1;

            foreach ($value as $keyCell => $cell) {
                if (empty($header[$keyCell])) {
                    continue;
                }

                if ($keyCell === 0) {
                    $efetArray[strtolower($this->getLastWord($header[$keyCell]))] = $cell;
                } else if ($keyCell === 1) {
                    $efetArray[strtolower($this->getLastWord($header[$keyCell]))] = $cell;
                } else {
                    if ($flag && stripos($header[$keyCell], 'state') === false) {
                        $functionArray['value'] = $cell;
                    } else {
                        $flag = 0;
                        $stateArray[str_replace(' ', '', ucwords($header[$keyCell]))] = $cell;
                        if (stripos($header[$keyCell], 'update') !== false) {
                            $stateArray[str_replace(' ', '', ucwords($header[$keyCell])) . 'Date'] = !empty($cell) ? date("Ymd", strtotime($cell)) : '';
                        }
                    }
                }
            }

            $elementsArray = [];

            if (count($efetArray)) {
                $elementsArray['EFET'] = Element::make()->setAttributes($efetArray);
            }

            if (count($functionArray)) {
                $elementsArray['EICFunction'] = Element::make()->setAttributes($functionArray);
            }

            if (count($stateArray)) {
                $elementsArray['state'] = Element::make()->setAttributes($stateArray);
            }

            $arrayResult['mapping'][] = Element::make($elementsArray)
            ->setAttributes([
                'type' => $this->removeLastWord($header[0]),
                strtolower($this->getLastWord($header[0])) . 'Name' => $header[0],
                strtolower($this->getLastWord($header[1])) . 'Name' => $header[1],
            ]);
        }

        return $arrayResult;
    }

    private function removeLastWord($string)
    {
        $words = explode(' ', $string);
        if (count($words) > 1) {
            array_pop($words);
        }
        $result = implode(' ', $words);
        return $result;
    }

    private function getLastWord($string)
    {
        $words = explode(' ', $string);
        return end($words);
    }
}
