<?php
namespace SabaiApps\Directories\Component\Notification\Controller\Admin;

use SabaiApps\Directories\Context;
use SabaiApps\Directories\Controller;

class SetNotificationStatus extends Controller {

	protected function _doExecute( Context $context ) {
		// Must be an Ajax request
		if ( ! $context->getRequest()->isAjax()
			|| $this->isDemoMode()
		) {
			$context->setBadRequestError();
			return;
		}

		// Check request token
		if ( ! $this->_checkToken( $context, 'notification_admin_notifications', true ) ) {
			return;
		}

		// Fetch notification
		if ( ( ! $id = $context->getRequest()->asInt( 'id' ) )
			|| ( ! $notification = $this->getModel( 'Notification', 'Notification' )->fetchById( $id ) )
		) {
			$context->setError( 'Invalid notification ID: ' . $id );
			return;
		}

		// Toggle status
		$notification->active = $notification->active ? 0 : 1;
		$notification->commit();

		// Send success response
		$context->setSuccess( dirname( dirname( $context->getRoute() ) ), array( 'active' => $notification->active ) );

		// Clear action to event map cache
		$this->getPlatform()->deleteCache( 'notification_action_event_map' );
	}
}
