<?php

use Intellex\MailChimp\Enum\MergeFields;
use Intellex\MailChimp\Exception\ValidationException;

class SubscribersController extends NewsletterAppController {

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

	/**
	 * @param      $listId
	 * @param null $subscriberId
	 *
	 * @throws \Exception|ValidationException
	 */
	public function details($listId, $subscriberId = null) {
		$this->addAction('plus', __('Add New Subscriber'), [ P => 'newsletter', C => 'subscribers', A => 'details', $listId ], [ 'class' => 'btn btn-success' ]);
		$this->addAction('list', __('Back to list'), [ P => 'newsletter', C => 'lists', A => 'details', $listId ]);

		$list = $this->mailchimp()->lists()->get($listId);

		// Set the subscriber
		$subscriber = null;
		if ($subscriberId) {
			$data = $this->mailchimp()->subscribers()->get($listId, $subscriberId);
			$subscriber = [
				'email'      => $data->email,
				'first_name' => $data->fields[MergeFields::FNAME],
				'last_name'  => $data->fields[MergeFields::LNAME],
				'status'     => $data->status,
			];
		}

		// Save
		if (!empty($this->request->data)) {
			try {
				$subscriber = $this->request->data;
				$this->save($listId, $subscriber['email'], $subscriber['status'], $subscriber['first_name'], $subscriber['last_name']);

			} catch (ValidationException $ex) {
				$this->set('exceptions', $ex->getErrors());
				$this->Session->setFlash($ex->getDetail(), 'danger', false);
			}

		}

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

		$this->crumbs[] = __('Subscriber Details');

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

	/**
	 * @param string $listId    Unique Id of list where this email is subscribed.
	 * @param string $email     Email
	 * @param string $firstName First name.
	 * @param string $lastName  Last name.
	 * @param string $status    status of a subscriber.
	 *
	 * @throws \Exception|ValidationException
	 */
	private function save($listId, $email, $status, $firstName, $lastName) {

		try {
			$this->mailchimp()->subscribers()->manage($listId, $email, $status, $firstName, $lastName);

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

		} catch (ValidationException $ex) {
			$this->set('exceptions', $ex->getErrors());
			$this->Session->setFlash($ex->getDetail(), 'danger', false);
		}
	}
}
