<?php namespace Intellex\MailChimp\Api;

use Intellex\Curly\Method;
use Intellex\MailChimp\Resource\ResourceCampaign;

/**
 * Class ListApi
 *  Handles all templates API operations.
 *
 * @package Intellex\MailChimp\Api
 */
class ApiCampaign extends ApiAbstract {

	/**
	 * Get all of the campaigns for the account.
	 *
	 * @param int $offset
	 * @param int $count
	 *
	 * @return ResourceCampaign[] The list of found campaigns.
	 * @throws \Exception|\Intellex\MailChimp\Api\ValidationException
	 */
	public function getAll($offset = 0, $count = 100) {
		$campaigns = $this->curl([ 'campaigns', [ $offset, $count, 'sort_field' => 'create_time', 'sort_dir' => 'DESC' ] ])->getContent();

		// Convert
		foreach ($campaigns['campaigns'] as $i => $campaign) {
			$campaigns['campaigns'][$i] = new ResourceCampaign($campaign);
		}

		return $campaigns;
	}

	/**
	 * Get a campaign by its unique ID.
	 *
	 * @param string $campaignId The unique ID of the campaign.
	 *
	 * @return ResourceCampaign The found campaign, or null if not found.
	 * @throws \Exception|\Intellex\MailChimp\Api\ValidationException
	 */
	public function get($campaignId) {

		$campaign = $this->curl([ 'campaigns', $campaignId ])->getContent();

		return new ResourceCampaign($campaign);;
	}

	/**
	 * Create new campaign
	 *
	 * @param string $listId   name of the new template.
	 * @param string $title    name of the new template.
	 * @param string $subject  name of the new template.
	 * @param string $fromName name of the new template.
	 * @param string $replyTo  name of the new template.
	 *
	 * @return \Intellex\Curly\Response $response
	 * @throws \Exception|\Intellex\MailChimp\Api\ValidationException
	 */
	public function create($campaignId = null, $listId, $title, $subject, $fromName, $replyTo) {
		$data = [
			'type'       => 'regular',
			'recipients' => [
				'list_id' => $listId
			],
			'settings'   => [
				'title'        => $title,
				'subject_line' => $subject,
				'from_name'    => $fromName,
				'reply_to'     => $replyTo
			],
		];

		$response = $this->curl([ 'campaigns', $campaignId ], $data, $campaignId ? Method::PATCH : Method::POST);

		// Make sure the request is accepted
		if ($response->getCode() !== 200) {
			throw new \Exception("Unable to save Campaign.");
		}

		return new ResourceCampaign($response->getContent());
	}

	/**
	 * Delete existing campaign
	 *
	 * @param string $campaignId unique Id of campaign
	 *
	 * @return bool True on success.
	 * @throws \Exception|\Intellex\MailChimp\Api\ValidationException
	 */
	public function delete($campaignId) {
		return empty($this->curl([ 'campaigns', $campaignId ], [], Method::DELETE)->getRawData());
	}

	/**
	 * Schedule existing campaign
	 *
	 * @param string $campaignId unique Id of campaign
	 * @param string $time       time for The date and time in UTC to schedule the campaign for delivery.
	 *                           Campaigns may only be scheduled to send on the quarter-hour (:00, :15, :30, :45).
	 *                           Example: 2017-02-04T19:13:00+00:00
	 * @param bool   $timewarp   Campaigns scheduled with Timewarp are localized based on the recipients’ time zones.
	 * @param bool   $batchDelay Choose whether the campaign should use Batch Delivery. Cannot be set to true for campaigns using Timewarp.
	 *
	 * @return string $response
	 * @throws \Exception|\Intellex\MailChimp\Api\ValidationException     *
	 */
	public function schedule($campaignId, $time, $timewarp = true, $batchDelay = false) {
		$data = [
			'schedule_time' => $time,
			'timewarp'      => $timewarp,
			'batch_delay'   => $batchDelay
		];

		$response = $this->curl([ 'campaigns', $campaignId, 'actions', 'schedule' ], $data, Method::POST)->getContent();

		return $response;
	}

	/**
	 * @param string $campaignId unique Id of campaign.
	 * @param string $html       The raw HTML for the campaign.
	 *
	 * @return bool
	 * @throws \Exception|\Intellex\MailChimp\Api\ValidationException
	 */
	public function setContent($campaignId, $html) {
		$data = [
			'html' => $html
		];

		$response = $this->curl([ 'campaigns', $campaignId, 'content' ], $data, Method::PUT)->getContent();

		return $response;
	}

	/**
	 * @param string $campaignId unique Id of campaign.
	 *
	 * @return bool
	 * @throws \Exception|\Intellex\MailChimp\Api\ValidationException
	 */
	public function getContent($campaignId) {
		$response = $this->curl([ 'campaigns', $campaignId, 'content' ])->getContent();
		return $response;
	}

	/**
	 * Unschedule existing campaign
	 *
	 * @param string $campaignId unique Id of campaign
	 *
	 * @return bool True on success.
	 * @throws \Exception|\Intellex\MailChimp\Api\ValidationException
	 */
	public function unSchedule($campaignId) {

		$this->curl([ 'campaigns', $campaignId, 'actions', 'unschedule' ], '', Method::POST)->getContent();

		return true;
	}

	/**
	 * Schedule existing campaign
	 *
	 * @param string $campaignId unique Id of campaign
	 * @param array  $emails     An array of email addresses to send the test email to.
	 * @param string $sendType   html\plaintext Choose the type of test email to send.
	 *
	 * @return bool True on success.
	 * @throws \Exception|\Intellex\MailChimp\Api\ValidationException
	 */
	public function test($campaignId, $emails, $sendType = 'html') {
		$data = [
			'test_emails' => $emails,
			'send_type'   => $sendType
		];

		$this->curl([ 'campaigns', $campaignId, 'actions', 'test' ], $data, Method::POST)->getRawData();

		return true;
	}


	/**
	 * Send existing campaign
	 *
	 * @param string $campaignId unique Id of campaign
	 *
	 * @return bool True on success.
	 * @throws \Exception|\Intellex\MailChimp\Api\ValidationException
	 */
	public function send($campaignId) {
		$campaignSent = $this->curl([ 'campaigns', $campaignId, 'actions', 'send' ], '', Method::POST)->getRawData();

		return true;
	}

	/**
	 * Cancel a Campaign after you send, before all of your recipients receive it
	 *
	 * @param string $campaignId unique Id of campaign
	 *
	 * @return bool True on success.
	 * @throws \Exception|\Intellex\MailChimp\Api\ValidationException
	 */
	public function cancelSending($campaignId) {
		$campaignSent = $this->curl([ 'campaigns', $campaignId, 'actions', 'cancel-send' ], '', Method::POST)->getRawData();

		return true;
	}
}