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

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

class SetDiscountStatus 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, 'paymentgateway_admin_discounts', true ) ) {
			return;
		}

		// Fetch notification
		if ( ( ! $id = $context->getRequest()->asInt( 'id' ) )
			|| ( ! $discount = $this->Entity_Entity( 'post', $id ) )
			|| $discount->getBundleType() !== 'paymentgateway_discount'
			|| ( ! $bundle = $this->Entity_Bundle( $discount->getBundleName() ) )
			|| ! $this->HasPermission( 'directory_admin_directory_' . $bundle->group )
			|| ( ! $discount_data = $discount->getSingleFieldValue( 'paymentgateway_discount' ) )
		) {
			$context->setError( 'Invalid discount ID: ' . $id );
			return;
		}

		$discount_data['active'] = intval( $new_status = empty( $discount_data['active'] ) );

		$this->Entity_Save(
			$discount,
			array(
				'paymentgateway_discount' => $discount_data,
			)
		);

		// Send success response
		$context->setSuccess( false, array( 'status' => (int) $new_status ) ); // false required to send success messages
	}
}
