<?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\Listing;
use function Vvveb\model;
use function Vvveb\sanitizeFileName;
use function Vvveb\url;

class NewsletterMails extends Listing {
	protected string $type = 'newsletter_mail';

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

	//protected $model = 'newsletter_mail';

	protected string $controller = 'newsletter-mail';

	protected string $list = 'newsletter_mail';

	protected string $listController = 'lists';

	protected $type_id = 'email';

	protected string $module = 'plugins/newsletter';

	function export() {
		$this->view->success[] = 'export';
		$newsletter_list_id = $this->request->get['newsletter_list_id'];
		if ($newsletter_list_id) {
			$columns = ['email', 'first_name', 'last_name'];

			$list = model($this->modelName);
			$options = ['newsletter_list_id' => $newsletter_list_id, 'limit' => 10000] + $this->global;
			$rows = $list->getAll($options)['newsletter_mail'] ?? [];

			header('Content-Type: text/csv');
			//header('Content-Length: ' . filesize($file));
			header('Content-Disposition: attachment; filename="list-' . intval($newsletter_list_id) . '.csv"');

			$fp = fopen('php://output', 'w');

			fputcsv($fp, $columns);

			foreach ($rows as $row) {
				fputcsv($fp, [$row['email'], $row['first_name'], $row['last_name']]);
			}

			fclose($fp);
			die();
		}
	}

	function import() {
		$newsletter_list_id = $this->request->get['newsletter_list_id'];
		$files = $this->request->files;

		//check for uploaded files
		if ($files) {
			$file = $files['file'];
			$fileName = sanitizeFileName($file['name']);
			$extension = strtolower(substr($fileName, strrpos($fileName, '.') + 1));
			$type  = $file['type'];
			$mimeType  = mime_content_type($file['tmp_name']);

			if ($mimeType != 'text/csv') {
				$errorMessage           = sprintf(__('Must upload .csv file!'), $fileName);
				$this->view->errors[]   = $errorMessage;

				return;
			}

			$list = model($this->modelName);

			if (($handle = fopen($file['tmp_name'], 'r')) !== FALSE) {
				if (($columns = fgetcsv($handle,null,',','"','\\')) !== FALSE) {
					$email = $first_name = $last_name = null; //column index
					foreach ($columns as $i => $col) {
						if (stripos($col, 'mail') !== false) {
							$email = $i;
						}

						if (stripos($col, 'first') !== false) {
							$first_name = $i;
						}

						if (stripos($col, 'last') !== false) {
							$last_name = $i;
						}

						if (stripos($col, 'name') !== false) {
							if ($first_name == null) {
								$first_name = $i;
							}
							if ($last_name == null) {
								$last_name = $i;
							}
						}
					}


					if ($email !== null) {
						while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
							$row = ['email' => $data[$email]];

							if ($first_name) {
								$row['first_name'] = $data[$first_name];
							}

							if ($last_name) {
								$row['last_name'] = $data[$last_name];
							}

							$list->add(['newsletter_mail' => $row, 'newsletter_list_id' => $newsletter_list_id]);
						}
					} else {
						$this->view->errors[] = __('No email column!');
					}
				}

				fclose($handle);
				$this->view->success[] = __('Import successful!');
			} else {
				$this->view->errors[] = __('Can\'t open file!');
			}
		}

		return $this->index();
	}

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

		//expand fields in the json
		if ($this->view->newsletter_mail) {
			foreach ($this->view->newsletter_mail as &$newsletter_mail) {
				$data = json_decode($newsletter_mail['data'] ?? '{}', true);

				if (is_array($data)) {
					$newsletter_mail += $data;
				}

				$newsletter_mail['edit-url'] .= '&newsletter_list_id=' . $newsletter_list_id;
			}
		}

		$this->view->addmail_url = url(['module' => $this->module . '/' . $this->controller, 'newsletter_list_id' => $newsletter_list_id]);
	}
}
