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

use SabaiApps\Directories\Component\Form\Controller;
use SabaiApps\Directories\Component\Form\Form;
use SabaiApps\Directories\Context;

class ClearVotes extends Controller {

	protected function _doGetFormSettings( Context $context, array &$storage ) {
		$this->_submitButtons[]       = array(
			'#btn_label' => __( 'Delete', 'directories-pro' ),
			'#btn_color' => 'danger',
			'#btn_size'  => 'lg',
		);
		$this->_ajaxOnSuccess         = 'function (result, target, trigger) {
    if (!result.deleted) return;
    var table = $(".drts-voting-' . $context->voting_type . '-' . $context->entity->getId() . '");
    result.deleted.forEach(function (val) {
    var row = table.find("tr[data-row-id=\'" + val + "\']");
    if (row.length) DRTS.Form.deleteTableRow(row);
});
        }';
		$this->_ajaxOnSuccessRedirect = false;

		$type_impl     = $this->_application->Voting_Types_impl( $context->voting_type );
		$table_headers = $type_impl->votingTypeInfo( 'vote_table_headers' );
		unset( $table_headers['entity'] );
		$votes   = $this->_application->getModel( 'Vote', 'Voting' )
			->fieldName_is( 'voting_' . $context->voting_type )
			->entityId_is( $context->entity->getId() )
			->fetch();
		$options = array();
		foreach ( $votes as $vote ) {
			$options[ $vote->id ] = $type_impl->votingTypeTableRow( $vote, $table_headers );
		}

		return array(
			'votes'      => array(
				'#type'          => 'tableselect',
				'#header'        => $table_headers,
				'#options'       => $options,
				'#default_value' => array_keys( $options ),
				'#class'         => 'drts-data-table',
				'#size'          => 'sm',
				'#multiple'      => true,
			),
			'entity_id'  => array(
				'#type'          => 'hidden',
				'#default_value' => $context->entity->getId(),
			),
			'field_name' => array(
				'#type'          => 'hidden',
				'#default_value' => 'voting_' . $context->voting_type,
			),
		);
	}

	public function submitForm( Form $form, Context $context ) {
		if ( empty( $form->values['votes'] ) ) {
			return;
		}

		$this->getModel( 'Vote', 'Voting' )
			->fieldName_is( 'voting_' . $context->voting_type )
			->entityId_is( $context->entity->getId() )
			->id_in( $form->values['votes'] )
			->delete();

		$this->Voting_Votes_recalculate( $context->entity, 'voting_' . $context->voting_type );
		$context->setSuccess( null, array( 'deleted' => $form->values['votes'] ) );
	}
}
