<?php

class ListsController extends NewsletterAppController {

	/** @inheritdoc No model. */
	public $uses = [];

	/**
	 * Action: Show the list of all subscription lists.
	 */
	public function index() {
		// Set header actions
		$this->addAction('plus', __('Create new list'), [ P => 'newsletter', C => 'lists', A => 'create' ], [ 'class' => 'btn btn-success' ]);
		$this->addAction('list', __('Campaigns'), [ P => 'newsletter', C => 'campaigns', A => 'index' ]);

		$count = 100;
		$page = key_exists('page', $this->request->params['named']) ? $this->request->params['named']['page'] : 1;

		// Get all lists
		$lists = $this->mailchimp()->lists()->getAll($this->itemOffset($count), $count);

		// Set crumbs
		$this->crumbs[] = __('Subscription lists');

		$this->set(compact('lists', 'count', 'page'));

	}

	/**
	 * Action: Details of specific subscription list.
	 *
	 * @var string $id Unique Id of subscription list.
	 */
	public function details($listId) {
		$this->addAction('pencil', __('Edit list'), [ P => 'newsletter', C => 'lists', A => 'create', $listId ], [ 'class' => 'btn btn-success' ]);
		$this->addAction('plus', __('Add New Subscriber'), [ P => 'newsletter', C => 'subscribers', A => 'details', $listId ], [ 'class' => 'btn btn-success' ]);

		$this->addAction('list', __('All Lists'), [ P => 'newsletter', C => 'lists', A => 'index' ]);
		$this->addAction('list', __('Campaigns'), [ P => 'newsletter', C => 'campaigns', A => 'index' ]);

		// Get pagination parameters
		$count = 100;
		$page = key_exists('page', $this->request->params['named']) ? $this->request->params['named']['page'] : 1;

		// Get the subscribers
		$subscribers = $this->mailchimp()->lists()->getSubscribers($listId, $this->itemOffset($count), $count);
		$list = $this->mailchimp()->lists()->get($listId);

		// Set crumbs
		$this->crumbs[] = [ __('Subscription lists'), [ P => 'newsletter', C => 'lists', A => 'index' ] ];
		$this->crumbs[] = $listId ? __('Subscribers in %s', $list->name) : __('Create List');

		$this->set(compact('subscribers', 'list', 'count', 'page'));
	}

	/**
	 * Action: Create or edit list.
	 *
	 * @var string $listId Unique Id used if edit existing subscription list.. Defaults to null.
	 * @throws Exception
	 */

	public function create($listId = null) {
		if ($listId) {
			$this->addAction('plus', __('Add new subscriber'), [ P => 'newsletter', C => 'subscribers', A => 'details', $listId ], [ 'class' => 'btn btn-success' ]);
		}

		$this->addAction('list', __('All Lists'), [ P => 'newsletter', C => 'lists', A => 'index' ]);
		$this->addAction('list', __('Campaigns'), [ P => 'newsletter', C => 'campaigns', A => 'index' ]);

		$listData = $listId ? $this->mailchimp()->lists()->get($listId) : null;

		// Crumbs
		$this->crumbs[] = [ __('Subscription lists'), [ P => 'newsletter', C => 'lists', A => 'index' ] ];

		// Set the list
		$list = null;
		if ($listData) {
			$list = [
				'name'                => $listData->name,
				'contact'             => [
					'company'  => $listData->contact['company'],
					'address1' => $listData->contact['address1'],
					'city'     => $listData->contact['city'],
					'state'    => $listData->contact['state'],
					'zip'      => $listData->contact['zip'],
					'country'  => $listData->contact['country'],
				],
				'permission_reminder' => $listData->permission_reminder,
				'campaign_defaults'   => [
					'from_name'  => $listData->campaign_defaults['from_name'],
					'from_email' => $listData->campaign_defaults['from_email'],
					'subject'    => $listData->campaign_defaults['subject'],
					'language'   => $listData->campaign_defaults['language'],
				],
				'email_type_option'   => false
			];

			$this->crumbs[] = [ __('Subscribers in %s', $list['name']), [ P => 'newsletter', C => 'lists', A => 'details', $listId ] ];
			$this->crumbs[] = __('Edit List');

		} else {
			$this->crumbs[] = __('Create List');
		}

		// Save
		if (!empty($this->request->data)) {
			try {
				$data = $this->request->data;

				$list = [
					'name'                => $data['name'],
					'contact'             => [
						'company'  => $data['contact']['company'],
						'address1' => $data['contact']['address1'],
						'city'     => $data['contact']['city'],
						'state'    => $data['contact']['state'],
						'zip'      => $data['contact']['zip'],
						'country'  => $data['contact']['country'],
					],
					'permission_reminder' => $data['permission_reminder'],
					'campaign_defaults'   => [
						'from_name'  => $data['campaign_defaults']['from_name'],
						'from_email' => $data['campaign_defaults']['from_email'],
						'subject'    => $data['campaign_defaults']['subject'],
						'language'   => $data['campaign_defaults']['language'],
					],
					'email_type_option'   => false,
				];

				$this->mailchimp()->lists()->create($list, $listId);

				// Set message and redirect to the list details
				$this->Session->setFlash(__('List saved successfully'));
				$this->redirect([ P => 'newsletter', C => 'lists', A => 'index' ]);

			} catch (\Intellex\MailChimp\Exception\ValidationException $ex) {
				$this->set('exceptions', $ex->getErrors());
				$this->Session->setFlash(__('List cannot be saved'), 'danger');
			}
		}

		$this->set(compact('list'));
	}

	/**
	 * Action: Remove a campaign.
	 *
	 * @var string $id Unique ID of the campaign to delete.
	 */
	public function remove($id) {

		$success = $this->mailchimp()->lists()->delete($id);

		if ($success) {
			$this->backtrack(__('List has been successfully deleted.'));
		} else {
			$this->backtrack(__('List could not be deleted.'), 'danger', false);
		}
	}
}
