<?php


namespace App\Repositories;


use App\Document;
use App\Http\Controllers\UserController;
use App\Message;
use App\ProjectType;
use App\User;
use App\Project;
use App\Article;
use Illuminate\Support\Facades\Log;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Pdf;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Helper\Sample;

class ProjectDocumentRepository extends DocumentBaseRepository
{

    public function resolveDocuments(User $user, $request)
    {
        $projectId = $request->get("orderToEdit");

        # Berechtigung prüfen
        if (!UserController::checkRight("editProjectTypes", $user))
            return redirect()->route('index');

        # Auftragstyp lesen
        $project = Project::find($projectId);
        if ($project == null) {
            return redirect()->back()->withErrors("Projekt nicht gefunden.");
        }

        $this->setDocumentRelationObject($project);
        $articleFieldsJson = json_decode($request->get('newArticleFileFields'));
        $articleFields = $articleFieldsJson->fields;

        $existingDocumentFieldsJson = json_decode($request->get('documentFileFields'));
        $existingDocumentFields = $existingDocumentFieldsJson->fields;


        parent::resolveDocuments($user, $request);

        foreach($articleFields as $articleField)
        {
            $articleId = explode("_", $articleField)[1];
            $article = Article::find($articleId);
            $articleDocumentRepository = new DocumentBaseRepository();
            $articleDocumentRepository->dropzoneName = $articleField;
            $articleDocumentRepository->setDocumentRelationObject($article);
            $articleDocumentRepository->resolveDocuments($user, $request);
        }

        foreach($existingDocumentFields as $existingDocumentField)
        {
            $versionDocumentRepository = new DocumentBaseRepository();
            $versionDocumentRepository->dropzoneName = $existingDocumentField;
            $versionDocumentRepository->resolveDocuments($user, $request);
        }

    }

    public function initializeProjectDocuments(Project $project)
    {
        $projectTemplates = $project->project_type->documentTemplates()->where("type", "=", "project")->get();
        $articleTemplates = $project->project_type->documentTemplates()->where("type", "=", "article")->get();
        $articles = $project->articles;

        foreach($projectTemplates as $projectTemplate)
        {
            $revision = $projectTemplate->document->copyToDocumentRelation($project);

            $explodedPath = explode(".", $revision->path);
            if(strtolower(end($explodedPath)) == "xlsx")
            {
                $this->setProjectVariableXlsx($project, $revision->path);
            }
            else if (strtolower(end($explodedPath)) == "docx")
            {
                $this->setProjectVariableDocx($project, $revision->path);
            }
        }

        foreach($articles as $article)
        {
            foreach($articleTemplates as $articleTemplate)
            {
                $revision = $articleTemplate->document->copyToDocumentRelation($article);

                $explodedPath = explode(".", $revision->path);
                if(strtolower(end($explodedPath)) == "xlsx")
                {
                    $this->setArticleVariableXlsx($article, $revision->path);
                }
                else if (strtolower(end($explodedPath)) == "docx")
                {
                    $this->setArticleVariableDocx($article, $revision->path);
                }
            }
        }

        $project->status = Project::$STATUS_CREATED;

        # Projekt zwischenspeichern, um ID zu erhalten
        try {
            $project->save();

            $successMessage = new Message();
            $successMessage->message_type = "success";
            $successMessage->title = "Projekt erfolgreich angelegt";
            $successMessage->subtitle = "Ihr Projekt <a href='/project/".$project->id."'><strong>".$project->project_nr."</strong></a> und zugehörige Dokumente wurden erfolgreich angelegt";
            $successMessage->save();

        } catch (\Exception $e) {
            Log::error("Fehler beim Anlegen eines neuen Projekts: " . $e->getMessage());
            return redirect()->back()->withErrors("Es ist ein Fehler aufgetreten");
        }
    }


    public function setArticleVariableDocx(Article $article, $path)
    {


        $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor(storage_path("app/public/uploads" . DocumentBaseRepository::BASE_PATH . $path));

        $articleVariables = $article->variables;
        $dictionary = [];

        foreach($articleVariables as $articleVariable)
        {
//            $dictionary[$articleVariable->variable->variable_title] = $articleVariable;
            $templateProcessor->setValue($articleVariable->variable->variable_title, $articleVariable->value);
        }



        $templateProcessor->saveAs(storage_path("app/public/uploads") . DocumentBaseRepository::BASE_PATH . $path);
    }

    public function setProjectVariableDocx(Project $project, $path)
    {

        $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor(storage_path("app/public/uploads" . DocumentBaseRepository::BASE_PATH . $path));


        $projectVariables = $project->variables;
//        $articles = $project->articles;
//        $dictionary = [];
//        $articleDictionary = [];
//        $articleDictionaryKeys = [];

        foreach($projectVariables as $projectVariable)
        {
            $templateProcessor->setValue($projectVariable->variable->variable_title, $projectVariable->value);
        }

        $templateProcessor->saveAs(storage_path("app/public/uploads") . DocumentBaseRepository::BASE_PATH . $path);
    }

    public function setArticleVariableXlsx(Article $article, $path)
    {
        $reader = IOFactory::createReader('Xlsx');
        $spreadsheet = $reader->load(storage_path("app/public/uploads" . DocumentBaseRepository::BASE_PATH . $path));

        $articleVariables = $article->variables;
        $dictionary = [];

        foreach($articleVariables as $articleVariable)
        {
            $dictionary[$articleVariable->variable->variable_title] = $articleVariable;
        }


        foreach ($spreadsheet->getWorksheetIterator() as $worksheet)
        {
            foreach ($worksheet->getRowIterator() as $row)
            {
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false);
                foreach ($cellIterator as $cell)
                {
                    if ($cell !== null)
                    {
                        if(preg_match_all("\$\{[^\}]*\}$", $cell->getValue(), $matchLines))
                        {
                            $curCellText = $cell->getValue();
                            foreach($matchLines as $matchLine)
                            {
                                foreach($matchLine as $match)
                                {
                                    $matchText = substr($match, 1, strlen($match) - 2);
                                    if(isset($dictionary[$matchText]))
                                    {
                                        $curCellText = str_replace("$".$match, $dictionary[$matchText]->value, $curCellText);
                                    }
                                }
                            }
                            $cell->setValue($curCellText);
                        }
                    }
                }
            }
        }

        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save(storage_path("app/public/uploads") . DocumentBaseRepository::BASE_PATH . $path);
    }

    public function setProjectVariableXlsx(Project $project, $path)
    {
        $reader = IOFactory::createReader('Xlsx');
        $spreadsheet = $reader->load(storage_path("app/public/uploads" . DocumentBaseRepository::BASE_PATH . $path));

        $projectVariables = $project->variables;
        $articles = $project->articles;
        $dictionary = [];
        $articleDictionary = [];
        $articleDictionaryKeys = [];

        foreach($projectVariables as $projectVariable)
        {
            $dictionary[$projectVariable->variable->variable_title] = $projectVariable;
        }

        foreach($articles as $key => $article)
        {
            $articleDictionary[$key] = [];
            foreach($article->variables as $articleVariable)
            {
                $articleDictionary[$key][$articleVariable->variable->variable_title] = $articleVariable;
                $articleDictionaryKeys[] = $articleVariable->variable->variable_title;
            }
        }


        foreach ($spreadsheet->getWorksheetIterator() as $worksheet)
        {
            foreach ($worksheet->getRowIterator() as $row)
            {
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false);
                foreach ($cellIterator as $cell)
                {
                    if ($cell !== null)
                    {
                        if(preg_match_all("\$\{[^\}]*\}$", $cell->getValue(), $matchLines))
                        {
                            $curCellText = $cell->getValue();
                            $cellColumn = $cell->getColumn();
                            $cellRow = $cell->getRow();
                            foreach($matchLines as $matchLine)
                            {
                                foreach($matchLine as $match)
                                {
                                    $matchText = substr($match, 1, strlen($match) - 2);
                                    if(isset($dictionary[$matchText]))
                                    {
                                        $curCellText = str_replace("$".$match, $dictionary[$matchText]->value, $curCellText);
                                    }
                                    else if(in_array($matchText, $articleDictionaryKeys))
                                    {
                                        foreach($articleDictionary as $key => $articleDictionaryItem)
                                        {
                                            if(isset($articleDictionaryItem[$matchText]))
                                            {
                                                $tmpCellText = str_replace("$" . $match, $articleDictionaryItem[$matchText]->value, $curCellText);
                                                $iterateArticleCell = $spreadsheet->getActiveSheet()->getCellByColumnAndRow(\PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($cellColumn) + $key, $cellRow);
                                                $iterateArticleCell->setValue($tmpCellText);
                                                $curCellText = $tmpCellText;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save(storage_path("app/public/uploads") . DocumentBaseRepository::BASE_PATH . $path);
    }

}