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

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

class Occurrences extends Controller {

	protected function _doGetFormSettings( Context $context, array &$formStorage ) {
		// Init form
		$form = array(
			'occurrences' => array(
				'#type'      => 'tableselect',
				'#header'    => array(
					'start_date' => __( 'Date', 'directories-pro' ),
					'title'      => __( 'Title', 'directories-pro' ),
					'slot_id'    => __( 'Calendar Slot', 'directories-pro' ),
					'generated'  => __( 'Date Generated', 'directories-pro' ),
				),
				'#multiple'  => true,
				'#js_select' => true,
				'#options'   => array(),
				'#class'     => 'drts-data-table',
			),
		);
		// Set submit buttons
		$this->_submitButtons[] = array(
			'#btn_label' => __( 'Delete', 'directories-pro' ),
			'#btn_color' => 'danger',
			'#btn_size'  => 'lg',
		);

		// Ajax options
		// $this->_ajaxSubmit = true;
		$this->_ajaxOnSuccess         = 'function (result, target, trigger) {' . $this->_getAjaxOnSuccessJs( $context ) . '}';
		$this->_ajaxOnSuccessRedirect = false;

		// Init variables
		$sortable_headers = array( 'start_date', 'generated', 'slot_id' );
		$sort             = $context->getRequest()->asStr( 'sort', 'start_date', $sortable_headers );
		$order            = $context->getRequest()->asStr( 'order', 'DESC', array( 'ASC', 'DESC' ) );

		// Set sortable headers
		$extra_url_params = $this->_getExtraUrlParams( $context );
		$this->_makeTableSortable( $context, $form['occurrences'], $sortable_headers, $sort, $order, $extra_url_params );

		// Add rows
		$occurrences = $this->getModel( 'Occurrence', 'Calendar' )
			->entityId_is( $context->entity->getId() )
			->slotFieldName_is( $context->slot_field_name )
			->status_is( CalendarComponent::OCCURRENCE_STATUS_ACTIVE )
			->fetch( 100, 0, $sort, $order );
		foreach ( $occurrences as $occurrence ) {
			$form['occurrences']['#options'][ $occurrence->id ] = array(
				'start_date' => $occurrence->all_day
					? $this->_application->System_Date( $occurrence->start_date ) . ' - ' . __( 'All Day', 'directories-pro' )
					: $this->_application->System_Date_datetime( $occurrence->start_date ) . ' - ' . $this->_application->System_Date_datetime( $occurrence->end_date ),
				'title'      => $occurrence->title,
				'slot_id'    => $occurrence->slot_id,
				'generated'  => $this->_application->System_Date_datetime( $occurrence->created ),
			);
		}

		$form['sort']  = array(
			'#type'  => 'hidden',
			'#value' => $sort,
		);
		$form['order'] = array(
			'#type'  => 'hidden',
			'#value' => $order,
		);
		foreach ( $extra_url_params as $key => $value ) {
			$form[ $key ] = array(
				'#type'  => 'hidden',
				'#value' => $value,
			);
		}

		return $form;
	}

	protected function _getAjaxOnSuccessJs( Context $context ) {
		return 'if (!result.deleted) return;
var table = $(".drts-calendar-admin-manageoccurrences");
result.deleted.forEach(function (val) {
    var row = table.find("tr[data-row-id=\'" + val + "\']");
    if (row.length) DRTS.Form.deleteTableRow(row);
});';
	}

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

		$attr['deleted'] = array();
		foreach ( $this->getModel( 'Occurrence', 'Calendar' )
			->id_in( $form->values['occurrences'] )
			->slotFieldName_is( $context->slot_field_name )
			->fetch()
		as $occurrence ) {
			$occurrence->markRemoved()->commit();
			$attr['deleted'][] = $occurrence->id;
		}
		$context->setSuccess( $this->Url( $context->getRoute(), $this->_getExtraUrlParams( $context ) ), $attr );
	}

	protected function _getExtraUrlParams( Context $context ) {
		return array(
			'slot_field_name' => $context->slot_field_name,
			'entity_id'       => $context->entity->getId(),
		);
	}
}
