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

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

class SetPlanStatus extends Controller {

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

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

		// Fetch notification
		if ( ( ! $id = $context->getRequest()->asInt( 'id' ) )
			|| ( ! $status = $context->getRequest()->asStr( 'status', 'active' ) )
			|| ( ! $plan = $this->Entity_Entity( 'post', $id ) )
			|| $plan->getBundleType() !== 'paymentgateway_plan'
			|| ( ! $bundle = $this->Entity_Bundle( $plan->getBundleName() ) )
			|| ! $this->HasPermission( 'directory_admin_directory_' . $bundle->group )
			|| ( ! $plan_data = $plan->getSingleFieldValue( 'paymentgateway_plan' ) )
			|| ( $status !== 'active' && $plan_data['plan_type'] === 'addon' )
			|| ( ! $content_bundle = $this->Entity_Bundle( $plan_data['content_name'], $bundle->group ) )
			|| empty( $content_bundle->info['payment_enable'] )
		) {
			$context->setError( 'Invalid plan ID: ' . $id );
			return;
		}

		switch ( $status ) {
			case 'featured':
				$plan_data['featured'] = intval( $new_status = empty( $plan_data['featured'] ) );
				break;
			case 'active':
			default:
				$plan_data['active'] = intval( $new_status = empty( $plan_data['active'] ) );
		}

		$this->Entity_Save(
			$plan,
			array(
				'paymentgateway_plan' => $plan_data,
			)
		);

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