<?php

declare(strict_types=1);

namespace App\CoreModule\Presenters;

use App\CoreModule\Model\AdressManager;
use App\CoreModule\Model\EventManager;
use App\CoreModule\Model\ContactManager;
use App\Model\MailManager;
use App\Presenters\BasePresenter;
use Nette\Application\AbortException;
use Nette\Application\BadRequestException;
use Nette\Application\UI\Form;
use Nette\Database\UniqueConstraintViolationException;
use Nette\Utils\ArrayHash;

class AdressPresenter extends BasePresenter {

	public $adressManager;
	public $contactManager;
	public $eventManager;
	public $mailManager;
	
	public function __construct(AdressManager $adressManager, ContactManager $contactManager, EventManager $eventManager, MailManager $mailManager) {
		parent::__construct();

		$this->adressManager = $adressManager;
		$this->contactManager = $contactManager;
		$this->eventManager = $eventManager;
		$this->mailManager = $mailManager;
	}

	public function renderDefault($url = null) {

		if (!($adress = $this->adressManager->getAdress($url)))
			$this->error();

		$this->template->adress = $adress;

		if ($this->user->isLoggedIn()) $this->template->username = $this->user->identity->name;

		$this->template->contacts = $this->contactManager->getContacts($url);
		$this->template->contactsadmin = $this->contactManager->getContactsAdmin($url);
		$this->template->contactManager = $this->contactManager;
		$this->template->adressManager = $this->adressManager;

	}

	public function renderList() {
		$this->template->adresses = $this->adressManager->getAdresses();

		$this->template->adressManager = $this->adressManager;

		if ($this->user->isLoggedIn()) $this->template->username = $this->user->identity->name;

	}

	#CSV Import
	public function actionImport($url) {

		if (!($adress = $this->adressManager->getAdress($url)))
			$this->error(); 

		$this->template->adress = $adress; 

		$this->template->url = $url;
		if ($this->user->isLoggedIn()) $this->template->username = $this->user->identity->name;
	}

	public function renderEditor() {	
		if ($this->user->isLoggedIn()) $this->template->username = $this->user->identity->name;
		$this->template->url = $this->getParameter('url');
	}

	public function actionRemove($url = null) {
		$this->adressManager->removeAdress($url);
		$this->flashMessage('Adresář byl úspěšně odstraněn.');
		$this->redirect('Adress:list');
	}

	#Cely adresar
	public function actionSendall($url = null) {

		$adress_id = $url;
		$invitation_id = $this->mailManager->idToInvitation($url);
	
		$this->mailManager->allMail($adress_id, $invitation_id);

		$this->flashMessage('Pozvánky úspěšně odeslány.');
		$this->redirect('Adress:list');
	}

	#Jeden kontakt
	public function actionSendone($url = null, $id = null) {

		$contact_id = $url;
		$invitation_id = $this->mailManager->contactToInvitation($id);

		$this->mailManager->oneMail($contact_id, $invitation_id);

		$this->flashMessage('Pozvánka úspěšně odeslána.');
		$this->redirect('Adress:', $id);
	}

	#Odhlaseni odberu
	public function actionOdhlasit($url = null) {
		$this->mailManager->odhlasitOdber($url);

		$this->flashMessage('Odhlášení odběru pozvánek bylo úspěšné!');
		$this->redirect('Administration:login');
	}


	public function actionEditor($url) {

		if (is_numeric($url)) { //zda je url číslo

			if (!($adress = $this->adressManager->getAdress($url))) 
				$this->flashMessage('Adresář nebyl nalezen.'); 
			else $this->redirect('Adress:', $adress->adress_id);

		} else {

			if (!($adress = $this->adressManager->getAdressKey($url))) 
				$this->flashMessage('Adresář nebyl nalezen.'); 
			else $this->redirect('Adress:', $adress->adress_id);

		}

	}

	#import CSV form
	protected function createComponentImportForm() {
        $form = new Form;
        $form->addProtection();
		$form->addUpload('csv')
		->setHtmlAttribute('class','form-control form')
		->setRequired()
		->addRule(Form::MAX_FILE_SIZE, 'Maximální velikost souboru je 2 mB.', 2 * 1024 * 1024)->setHtmlAttribute('class','form-control form');
        $form->addSubmit('save', 'Import')->setHtmlAttribute('class','btn btn-secondary form-btn');
        $form->onSuccess[] = function (Form $form, ArrayHash $values) {

        	$value = $_FILES["csv"]["tmp_name"];

			$fileOpen = fopen($value, 'r');	

       		$id = $this->getParameter('url');
       		$created_at = date("Y-m-d H:i:s");

        	$i = 1;

        	while ($row = fgets($fileOpen, 1024)) {

            	if ($i > 0) {
                	$cols = preg_split("/;|,|:/", $row);
                	$data = [
                    	'mail' => $cols[0],
                    	'name' => $cols[1],
                	];
                	$this->adressManager->saveCsvData($data, $id, $created_at);
            	}$i++;
        	}

        	$this->redirect('Adress:', $id);
		};
		
        return $form;
    }
    

	protected function createComponentEditorForm() {

		$form = $this->formFactory->create();
		$form->addHidden('adress_id');
		$form->addHidden('name');
		$form->addSubmit('save', 'Uložit adresář')->setHtmlAttribute('class','btn btn-secondary form-btn-b');
		$form->onSuccess[] = [$this, "editorFormSucceeded"];

		return $form;
	}

	public function editorFormSucceeded(Form $form, ArrayHash $values) {
		$adress_name = $this->getParameter('url');
		$event_url = $this->getParameter('url');

		$this->adressManager->provedZapis($form, $event_url, $adress_name, $values);

		$this->flashMessage('Adresář byl úspěšně uložen.');
		$this->redirect('Adress:list');
	}

}
