<?php

class NewsletterController extends AppBackendController {

	public $uses = [ 'Newsletter' ];

	public function beforeFilter() {
		parent::beforeFilter();
		$this->set('modelClass', 'Newsletter');
		$this->set('controller', 'newsletter');
	}

	# Prepare template for sending
	public function prepare($model = null, $templateId = null) {

		# Prevent direct access to this page
		if ((!isset($this->request->data['Page']) || empty($this->request->data['Page'])) && !$this->Session->check('Newsletter.receivers')) {
			$this->Session->setFlash(__('Please select receivers first'), 'error');
			$this->redirect($this->referer);
		}

		# If there is no post data, check session.
		if (!isset($this->request->data['Page'])) {
			$this->request->data['Page'] = $this->Session->read('Newsletter.receivers');
		}

		# Instantiate receiver's module and get selected records
		$this->receiverModule = ClassRegistry::init($model);
		$items = $this->receiverModule->find('all', [
			'conditions' => [
				$this->$model->alias . ".id" => $this->request->data['Page']
			]
		]);

		# If existing template id provided, load it's data
		if (!empty($templateId)) {
			$template = $this->Newsletter->find('first', $templateId);
			$template['Newsletter']['newsletter_name'] = '';
			unset($template['Newsletter']['id']);
			$this->request->data['Newsletter'] = $template['Newsletter'];
		}

		# Write receivers in case there is error
		$this->Session->write('Newsletter.receivers', $this->request->data['Page']);
		$this->set('receiverModule', $this->receiverModule);
		$this->set('receivers', $items);

		# Maintain validation errors
		if ($this->Session->check('Newsletter.validation')) {
			$this->Newsletter->validationErrors = $this->Session->read('Newsletter.validation');
			$this->Session->delete('Newsletter.validation');
		}

	}

	# Send prepared template
	public function send() {
		try {
			# If there are no emails in request, redirect
			if (!isset($this->request->data['Receiver'])) {
				$this->Session->setFlash(__('Please select receivers first'), 'error');
				$this->redirect($this->redirect);
			}

			# Get receiver module and save current newsletter data.
			$receiverModule = ClassRegistry::init($this->request->data['Receiver']['class']);
			$newsletter = $this->request->data['Newsletter'];
			$newsletter['module'] = $receiverModule->alias;

			if (!$this->Newsletter->validates()) {
				$errors = $this->Newsletter->validationErrors;
				$this->Session->write('Newsletter.validation', $errors);
			}

			$newsletter = $this->Newsletter->save($newsletter);

			# If newsletter changed
			if (!$newsletter) {
				$this->Session->setFlash(__('Please check data'), 'error');
				$this->redirect($this->referal);
			}

			$newsletter = reset($newsletter);

			# Get all receivers
			$receivers = $receiverModule->find('all', [
				'conditions' => [
					$receiverModule->alias . '.id' => $this->request->data['Receiver'][$receiverModule->alias]['id']
				]
			]);

			# Send email for each receiver
			$failed = [];
			$succedded = [];
			foreach ($receivers as $receiver) {
				$receiver = reset($receiver);
				# Parse dynamic tags
				$mail = $this->Newsletter->parseEmail($newsletter, $receiver);

				# If parsing failed
				if (!$mail) {
					throw new Exception(__('Template bad'));
				}

				# Try to send email
				try {
					$CakeEmail = new CakeEmail();
					$CakeEmail->subject($mail['subject'])
						->viewVars($receiver)
						->to('boban@intellex.rs')
						->from('gateway@intellex.rs', $newsletter['from'])
						->emailFormat('html')
						->send($mail['text']);

					$succedded[] = $receiver['email'];
				} catch (Exception $e) {
					$failed[] = $receiver['email'];
					continue;
				}
			}

			# If all failed, notify the administrator
			if (count($failed) == count($receivers)) {
				$this->Session->setFlash(__('Mail sending failed for all receipent.'), 'error');
				$this->redirect($this->redirect);
			}

			# If some failed, notify how much
			if (count($failed) > 0) {
				$this->Session->setFlash(__('Mail sending done.') . ' ' . __('Number of failed:') . ' ' . count($failed), 'info');
			}

			# Pack newsletter data
			$newsletter['failed'] = serialize($failed);
			$newsletter['succedded'] = serialize($succedded);
			$this->Newsletter->save($newsletter);

			$this->Session->setFlash(__('Mail sending done.'), 'info');
			$this->Session->delete('Newsletter');

		} catch (Exception $e) {
			$this->Session->setFlash(__('Error occurred, please check template') . ' ' . $newsletter['newsletter_name'], 'error');
		}
		$this->redirect([ C => 'newsletters' ]);
	}

}
