<?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\Crud;
use function Vvveb\humanReadable;
use function Vvveb\url;

class NewsletterMail extends Crud {
	protected string $type = 'newsletter_mail';

	protected string $modelName = 'Plugins\Newsletter\newsletter_mail';

	protected $type_id = 'email';

	//protected $model = 'newsletter_mail';

	protected string $controller = 'newsletter-mail';

	protected $mail = 'newsletter_mail';

	protected $mailController = 'mails';

	protected string $module = 'plugins/newsletter';

	function save() {
		$this->redirect = false;
		$newsletter_list_id = $this->request->get['newsletter_list_id'] ?? false;
		$this->global['newsletter_list_id'] = $newsletter_list_id;

		$result = parent::save();
		if ($result && isset($result[$this->type])) {
			$successMessage             = humanReadable(__($this->type)) . __(' saved!');
			$this->view->success['get'] = $successMessage;
			$this->session->set('success', ['get' => $successMessage]);
			$this->redirect(['module' => "{$this->module}/newsletter-mails", 'newsletter_list_id' => $newsletter_list_id, $this->type_id => $result[$this->type], 'success' => $successMessage]);
		} else {
			$this->view->errors[] = __('Error saving!');
		}
	}

	function index() {
		parent::index();
		$newsletter_list_id = $this->request->get['newsletter_list_id'] ?? false;

		$this->view->newsletter_url = url(['module' => "{$this->module}/newsletter-mails", 'newsletter_list_id' => $newsletter_list_id]);
		$this->view->newsletter_mail['newsletter_list_id'] = $this->view->newsletter_mail['newsletter_list_id'] ?? $newsletter_list_id;
	}
}
