<?php

/**
 * Vvveb
 *
 * Copyright (C) 2022  Ziadin Givan
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

namespace Vvveb\Plugins\Newsletter\Controller;

use Vvveb\Controller\Crud;
use function Vvveb\siteSettings;
use Vvveb\System\Cache;
use Vvveb\System\Sites;

class NewsletterList extends Crud {
	protected $type = 'newsletter_list';

	protected $modelName = 'Plugins\Newsletter\newsletter_list';

	//protected $model = 'newsletter_list';

	protected $controller = 'newsletter-list';

	protected $list = 'newsletter_list';

	protected $listController = 'lists';

	protected $module = 'plugins/newsletter';


	function listAutocomplete() {
		$listModel  = new \Vvveb\Sql\Plugins\Newsletter\Newsletter_listSQL();
		$text       = trim($this->request->get['text'] ?? '');

		$options = [
			'status' => 1,
			'search' => $text,
		] + $this->global;

		$results = $listModel->getAll($options);
		$search = [];

		if (isset($results['newsletter_list'])) {
			foreach ($results['newsletter_list'] as $list) {
				$search[$list['newsletter_list_id']] =  $list['name'];
			}
		}

		$this->response->setType('json');
		$this->response->output($search);
	}

	function newsletterAutocomplete() {
		$postModel  = new \Vvveb\Sql\Plugins\Newsletter\Newsletter_postSQL();
		$text       = trim($this->request->get['text'] ?? '');

		$options = [
			'status' => 1,
			'search' => $text,
		] + $this->global;

		$results = $postModel->getAll($options);
		$search = [];

		if (isset($results['newsletter_post'])) {
			foreach ($results['newsletter_post'] as $post) {
				$search[$post['newsletter_post_id']] =  $post['name'];
			}
		}

		$this->response->setType('json');
		$this->response->output($search);
	}

	function next() {
		$position  = $this->request->get['position'] ?? 0;
		$count     = $this->request->get['count'] ?? 0;
		$file      = $this->request->get['file'] ?? '';
		$providerName  = $this->request->get['provider'] ?? 'provider';
		$column    = $this->request->post['column'] ?? [];
		$data      = [];
		$results   = [];
		$maxrows   = 3;
		$i = 0;

		//$this->response->setType('json');
		$path = DIR_BACKUP . $file;

		if (($handle = fopen($path, 'r')) !== FALSE) {
			fseek($handle, $position, SEEK_SET);

			$providerClass = 'Vvveb\Plugins\ImportCsv\Provider\\' . $providerName;
			if (! class_exists($providerClass)) {
				$errorMessage         = __('Invalid provider!');
				$this->view->errors[] = $errorMessage;
				return;
			}

			$provider = new $providerClass();
			$provider->setColumns($column);

			while ((($data = fgetcsv($handle,null,',','"','\\')) !== FALSE) && $i < $maxrows) {
				$i++;
				$provider->processRow($data);
				$position = ftell($handle);
			}

			$count += $i;
			fclose($handle);
		}

		$last = ($data === false);
		$message = '';
		if ($last) {
			$message = __('Import finished!');
		}
		$url     = ['module'=> 'plugins/import-csv/settings', 'action' => 'next', 'file' => $file, 'provider' => $providerName, 'success' => $message, 'position' => $position, 'count' => $count, 'last' => $last, 'i' => $i, 'data' => $results];
		sleep(1);
		if ($this->request->isAjax()) {
			$this->response->setType('json');
			$this->response->output($url + ['url' => url($url)]);
		} else {
			$this->redirect(url($url));

			die('Processing');
		}

		return;
	}

	function import() {
		$column   = $this->request->post['column'];
		$provider = $this->request->get['provider'];
		$file = $this->request->get['file'];
		$position = 0;
		$count = 0;

		$url = ['module'=> 'plugins/import-csv/settings', 'action' => 'next', 'file' => $file, 'provider' => $provider, 'position' => $position, 'count' => $count];
		$this->view->provider = $provider;
		$this->view->column = $column;
		$this->view->nextUrl = url($url);
	}

	function test() {
		$this->view->success[]	= 'test sent!';
		$this->send();
	}

	function send() {
		$view = $this->view;

		$admin_path  = \Vvveb\adminPath();

		$controllerPath  = $admin_path . 'index.php?module=media/media';
		$view->scanUrl   = "$controllerPath&action=scan";
		$view->uploadUrl = "$controllerPath&action=upload";
		$view->linkUrl   = $admin_path . 'index.php?module=content/post&action=urlAutocomplete';
		$theme           = Sites::getTheme(SITE_ID) ?? 'default';
		$view->themeCss  = '';

		if (file_exists(DIR_THEMES . "$theme/css/admin-post-editor.css")) {
			$view->themeCss .= PUBLIC_PATH . "themes/$theme/css/admin-post-editor.css";
		} else {
			if (file_exists(DIR_THEMES . "$theme/css/style.css")) {
				$view->themeCss .= PUBLIC_PATH . "themes/$theme/css/style.css";
			}
		}

		foreach (['custom.css', 'fonts.css'] as $css) {
			if (file_exists(DIR_THEMES . "$theme/css/$css")) {
				$view->themeCss .= ',' . PUBLIC_PATH . "themes/$theme/css/$css";
			}
		}

		$site = siteSettings();
		$view->newsletter = $this->request->post['newsletter'] ?? [];
		$view->newsletter['from'] = $view->newsletter['from'] ?? $site['contact-email'];

		$admin_path    = \Vvveb\adminPath();
		$newsletterUrl = $admin_path . 'index.php?module=plugins/newsletter/editor&action=newsletter';
		$previewUrl = $admin_path . 'index.php?module=plugins/newsletter/editor&action=newsletter';
		$processUrl = $admin_path . 'index.php?module=plugins/newsletter/newsletter-list&action=import';

		$view->newsletter['preview_url'] = '';
		$newsletter_post_id = $view->newsletter['newsletter_post_id'] ?? $this->request->get['newsletter_post_id'] ?? null;
		$newsletter_list_id =  $view->newsletter['newsletter_list_id'] ?? $this->request->get['newsletter_list_id'] ?? null;

		if ($newsletter_post_id) {
			$view->newsletter['newsletter_post_id'] = $newsletter_post_id;
			$postModel  = new \Vvveb\Sql\Plugins\Newsletter\Newsletter_postSQL();
			if ($post = $postModel->get(['newsletter_post_id' => $newsletter_post_id])) {
				$view->newsletter['newsletter_post_id_text'] = $post['name'];
				$view->newsletter['subject'] = $post['name'];
			}

			$view->newsletter['preview_url'] = $previewUrl . '&newsletter_post_id=' . $newsletter_post_id;
		}

		if ($newsletter_list_id) {
			$view->newsletter['newsletter_list_id'] = $newsletter_list_id;
			$listModel  = new \Vvveb\Sql\Plugins\Newsletter\Newsletter_listSQL();
			if ($list = $listModel->get(['newsletter_list_id' => $newsletter_list_id])) {
				$view->newsletter['newsletter_list_id_text'] = $list['name'];
			}
		}

		$view->newsletter['step']        = 100;
		$view->newsletter['sleep_step']  = 1000;
		$view->newsletter['sleep_email'] = 100;
		$view->preview_url               = $previewUrl;
		$view->procedss_url              = $processUrl;

		$view->themeFonts = Cache::getInstance()->cache(APP, 'fonts-list-' . $theme, function () use ($theme) {
			$fonts = \Vvveb\System\Media\Font::themeFonts($theme);
			$names = [];

			if ($fonts) {
				foreach ($fonts as $font) {
					if (isset($font['font-family'])) {
						$names[$font['font-family']] = null;
					}
				}
			}

			return $names;
		}, 604800);
	}
}
