<?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 function Vvveb\__;
use Vvveb\Controller\Editor\Editor as EditorBase;
use function Vvveb\model;
use Vvveb\Plugins\Newsletter\System\Functions;
use function Vvveb\sanitizeFileName;
use Vvveb\System\Sites;

class Editor extends EditorBase {
	protected $type = 'newsletter_post';

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


	function save() {
		$post_id = $this->request->post['post_id'] ?? false;
		$html = $this->request->post['html'] ?? '';
		$file = $this->request->post['file'] ?? '';
		$name = $this->request->post['name'] ?? '';
		$url = $this->request->post['url'] ?? '';
		$startTemplateUrl = $this->request->post['startTemplateUrl'] ?? '';

		$success = false;
		$text = sprintf(__('Error saving %s!'),  __('newsletter'));

		if ($html) {
			if ($post_id) {
				$postModel = model($this->modelName);
				$post = $postModel->edit(['newsletter_post' => ['content' => $html], 'newsletter_post_id' => $post_id] + $this->global)[$this->type] ?? [];
				if ($post) {
					$success = true;
					$text = __('Elements saved!');
				} else {
				}
			} else if ($file) {
				$file = sanitizeFileName($file);
				$theme  = Sites::getTheme($this->global['site_id']);
				$templatesFolder = PUBLIC_PATH . 'plugins/newsletter/templates/';
				$themeFolder = PUBLIC_PATH . "themes/$theme/email/";

				if (strncmp($templatesFolder, $file, strlen($templatesFolder)) === 0) {
					$file = DIR_PLUGINS . 'newsletter' . DS . 'public' . DS . 'templates' . DS . str_replace($templatesFolder, '', $file);
				} else if (strncmp($themeFolder, $file, strlen($themeFolder)) === 0) {
					$file = DIR_THEMES . $theme . DS . 'email' . DS . str_replace($templatesFolder, '', $file);
				} else {
					$file = false;
				}

				if ($file && @file_put_contents($file, $html)) {
					$success = true;
					$text = __('File saved!');
				} else {
					$success = false;
					if (! is_writable($file)) {
						$text .= '<br>' . sprintf(__('%s is not writable!'), $file);
					} else {
						$text .= '<br>' . sprintf(__('Error saving %s!'), $file);
					}
				}
			}
		}


		$data = compact('file', 'name', 'url', 'startTemplateUrl');
		$data += ['success' => $success, 'message' => $text];

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

	protected function pages($theme = false, $urlParams = '') {
		$view = $this->view;
		$view->pages = [];

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

		$newsletter_post_id = $this->request->get['newsletter_post_id'] ?? null;


		//newsletters
		$postModel = model($this->modelName);
		$posts = $postModel->getAll(['limit' => 1000] + $this->global)[$this->type] ?? [];
		foreach ($posts as $post) {
			$id = $post[$this->type . '_id'];
			$url = $newsletterUrl . '&newsletter_post_id=' . $id;

			$view->pages[$id] = [
				'name'      => $post['name'],
				'file'      => '',
				'url'       => $url,
				'title'     => $post['name'],
				'post_id'   => $id,
				'folder'    => '',
				'className' => 'page',
			];
		}

		//templates
		$folder = DIR_PLUGINS . 'newsletter' . DS . 'public' . DS . 'templates';
		$templates = Functions::templatesList($folder);

		//change file path to url
		array_walk_recursive($templates, function (&$file) {
			$template = str_replace(DIR_PLUGINS . 'newsletter' . DS . 'public' . DS, '', $file);
			$file = PUBLIC_PATH . 'plugins/newsletter/' . $template;
		});

		$theme  = Sites::getTheme($this->global['site_id']);
		$folder = DIR_THEMES . $theme . DS . 'email';
		$themeTemplates = Functions::templatesList($folder);

		//change file path to url
		array_walk_recursive($themeTemplates, function (&$file) use ($theme) {
			$template = str_replace(DIR_PUBLIC, '', $file);
			$file = PUBLIC_PATH . $template;
		});

		$templates += $themeTemplates;

		foreach ($templates as $folderName => $files) {
			if (! is_array($files)) {
				$files = [$files];
			}

			foreach ($files as $name => $file) {
				$view->pages[$name] = [
					'name'      => $name,
					'file'      => $file,
					'url'       => $file,
					'title'     => $name,
					'post_id'   => null,
					'folder'    => $folderName,
					'className' => '',
				];
			}
		}


		if ($newsletter_post_id && isset($view->pages[$newsletter_post_id])) {
			$view->firstPage = $newsletter_post_id;
		}
	}

	function newsletter() {
		$newsletter_post_id = $this->request->get['newsletter_post_id'];
		if ($newsletter_post_id) {
			$postModel = model($this->modelName);
			$post = $postModel->get(['newsletter_post_id' => $newsletter_post_id]);
			if ($post) {
				die($post['content']);
			} else {
				$this->notFound();
			}
		} else {
			$this->notFound();
		}
	}

	function index() {
		parent::index();

		$this->view->options['inline-css'] = true;

		$admin_path                    = \Vvveb\adminPath();
		$controllerPath                = $admin_path . 'index.php?module=plugins/newsletter/editor';
		$this->view->saveUrl           = "$controllerPath&action=save";

		return 'editor/editor.html';
	}
}
