<?php
namespace SabaiApps\Directories\Component\Voting\Controller;

use SabaiApps\Directories\Controller;
use SabaiApps\Directories\Context;
use SabaiApps\Directories\Exception;
use SabaiApps\Directories\Request;

class VoteEntity extends Controller {

	protected function _doExecute( Context $context ) {
		// Check voting allowed
		$value        = $context->getRequest()->get( 'value' );
		$is_down_vote = null !== $value && is_numeric( $value ) && $value < 0;
		if ( ! $this->Voting_CanVote( $context->entity, $context->voting_type, $is_down_vote ) ) {
			if ( $this->getUser()->isAnonymous() ) {
				$context->setUnauthorizedError( $this->Entity_PermalinkUrl( $context->entity ) );
			} else {
				$context->setError( __( 'You do not have the permission to perform this action.', 'directories-pro' ) );
			}
			return;
		}

		// Check request token
		if ( ! $this->_checkToken( $context, 'voting_vote_entity', true ) ) {
			// Probably coming from login redirect, so show a voting button with token
			$voting_type = $this->Voting_Types_impl( $context->voting_type );
			$bundle      = $this->Entity_Bundle( $context->entity, '', true );
			$label       = sprintf( $voting_type->votingTypeInfo( $is_down_vote ? 'label_unaction' : 'label_action' ), $bundle->getLabel( 'singular' ) );
			$context->setView()->setInfo( $label )->setAttributes(
				array(
					'content' => $this->LinkTo(
						$label,
						$this->Url(
							$context->getRoute(),
							array(
								Request::PARAM_TOKEN => $this->Form_Form_createToken( 'voting_vote_entity', 1800, true ),
								'value'              => $value,
								'edit'               => 1, // prevent undo'ing vote
							)
						),
						array(
							'container' => $context->getContainer(),
							'post'      => true,
							'redirect'  => true,
							'btn'       => true,
							'icon'      => $voting_type->votingTypeInfo( 'icon' ),
						),
						array(
							'class' => DRTS_BS_PREFIX . 'btn ' . DRTS_BS_PREFIX . 'btn-primary ' . DRTS_BS_PREFIX . 'btn-lg',
						)
					),
				)
			);
			return;
		}

		try {
			$results = $this->Voting_Votes_cast(
				$context->entity,
				'voting_' . $context->voting_type,
				array( '' => $value ),
				array(
					'edit'    => $context->getRequest()->asBool( 'edit' ),
					'comment' => $context->getRequest()->asStr( 'comment' ),
				)
			);
		} catch ( Exception\IException $e ) {
			$context->setError( $e->getMessage() );
			return;
		}

		$result      = $results[''];
		$voting_type = $this->Voting_Types_impl( $context->voting_type );
		$attributes  = array(
			'type'      => $context->voting_type,
			'entity_id' => $context->entity->getId(),
			'num'       => $voting_type->votingTypeFormat( $result, 'num' ),
			'num_down'  => $voting_type->votingTypeFormat( $result, 'num_down' ),
		) + $result;
		$voting_type->votingTypeOnVoteEntity( $context->entity, $attributes, $context->getRequest() );
		$context->setSuccess( $this->Entity_PermalinkUrl( $context->entity ), $attributes );
	}
}
