<?php

use Intellex\MailChimp\Client;
use Intellex\MailChimp\Config;

/**
 * Class NewsletterAppController
 */
class NewsletterAppController extends AppBackendController {

	public $helpers = [ 'Newsletter.ChimpForm' ];

	/** @inheritdoc */
	public function beforeFilter() {
		parent::beforeFilter();

		// Set the base crumbs
		$this->crumbs[] = [
			__('Newsletters'), [ P => 'newsletter', C => 'campaigns', A => 'index' ]
		];
	}

	/**
	 * Initialize Mailchimp
	 */
	protected function mailchimp() {
		$config = new Config(Configure::read('Feature.mailchimp_api_key'));
		return new Client($config);
	}

	/**
	 * Get the offset for the pagination.
	 *
	 * @param int $count The number of items per page.
	 *
	 * @return int The offset to show, base on the number of items per page and the current page.
	 */
	protected function itemOffset($count) {

		// Get the current page
		$page = key_exists('page', $this->request->params['named'])
			? $this->request->params['named']['page']
			: 1;

		// Get the offset
		$offset = ceil(($page - 1) * $count);

		// Set the pagination options
		$this->set('paging', compact('count', 'page', 'offset'));

		// Return the offset
		return $offset;
	}

}
