<?php
/**
 * Eventon ExIm - Export event to Eventbrite.
 *
 * @package mmt-eo-exim
 * @author MoMo Themes
 * @since v1.0
 */
class MMT_EO_ExIm_Export_Eventbrite {
	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'eventon_save_meta', array( $this, 'mmt_eo_exim_export_to_eventbrite' ), 10, 3 );

		add_action( 'eventon_add_meta_boxes', array( $this, 'mmt_eo_exim_export_meta_box' ) );
	}

	/**
	 * Add Export Metabox
	 */
	public function mmt_eo_exim_export_meta_box() {
		add_meta_box(
			'mmt_eo_exim_export_mb',
			esc_html__( 'Export Event', 'mmt-eo-exim' ),
			array(
				$this,
				'mmt_eo_exim_export_meta_box_content',
			),
			'ajde_events',
			'side',
			'high'
		);
	}

	/**
	 * Export MetaBox Content
	 */
	public function mmt_eo_exim_export_meta_box_content() {
		global $post, $eventon;
		$event_pmv                       = ( ! empty( $post ) ) ? get_post_custom( $post->ID ) : null;
		$evcal_export_to_eventbrite_done = ( ! empty( $event_pmv['evcal_export_to_eventbrite_done'] ) ) ? $event_pmv['evcal_export_to_eventbrite_done'][0] : null;

		if ( 'yes' === $evcal_export_to_eventbrite_done ) :
			?>
			<p style='text-align: center;opacity: 0.5;padding: 5px;background-color: #F0F0F0;border-radius:6px'>
				<?php esc_html_e( 'Already exported ot Eventbrite!', 'mmt-eo-exim' ); ?>
			</p>
			<?php
		else :
			?>
		<div class="mmt-eo-ei-admin-block" id="mmt-eo-ei-metabox-form">
			<?php wp_nonce_field( 'mmt_eo_exim_export_event', 'mmt_eo_exim_export_event_nonce' ); ?>
				<span class="mmt-eo-ei-admin-toggle-container" afteryes="evo_eb_export_export_event_ay">
					<label class="switch">
					<?php $checked = ( 'on' === $evcal_export_to_eventbrite_done ) ? 'checked' : ''; ?>
						<input type="checkbox" class="switch-input" name="evo_eb_export_export_event" <?php echo esc_html( $checked ); ?>>
						<span class="switch-label" data-on="Yes" data-off="No"></span>
						<span class="switch-handle"></span>
					</label>
				</span>
				<span class="mmt-eo-ei-toggle-container-label">
					<?php esc_html_e( 'Export to Eventbrite.', 'mmt-eo-exim' ); ?>
				</span>
				<div id="evo_eb_export_export_event_ay" class="afteryes">
					<div class="mmt-eo-ei-block">
						<label class="mmt-full-width">
							<?php
							esc_html_e( 'Select event status', 'mmt-eo-exim' );
							?>
						</label>
						<select class="mmt-full-width" name="evo_eb_export_export_event_status" autocomplete="off">
							<option value="draft"><?php esc_html_e( 'Draft', 'mmt-eo-sxim' ); ?></option>
							<option value="publish"><?php esc_html_e( 'Publish', 'mmt-eo-sxim' ); ?></option>
						</select>
					</div>
					<div class="mmt-eo-ei-block-ticket mmt-eo-ei-block-hidden">
						<div class="mmt-eo-ei-block">
							<label class="mmt-full-width">
								<?php
								esc_html_e( 'Ticket Class', 'mmt-eo-exim' );
								?>
							</label>
							<input class="mmt-full-width" name="evo_eb_export_export_event_tclass"/>
						</div>
						<div class="mmt-eo-ei-block">
							<label class="mmt-full-width">
								<?php
								esc_html_e( 'Capacity', 'mmt-eo-exim' );
								?>
							</label>
							<input class="mmt-full-width" name="evo_eb_export_export_event_capacity"/>
						</div>
						<div class="mmt-eo-ei-block">
							<label class="mmt-full-width">
								<?php
								esc_html_e( 'Ticket Type', 'mmt-eo-exim' );
								?>
							</label>
							<select class="mmt-full-width" name="evo_eb_export_export_event_ttype" autocomplete="off">
								<option value="free"><?php esc_html_e( 'Free', 'mmt-eo-sxim' ); ?></option>
								<option value="paid"><?php esc_html_e( 'Paid', 'mmt-eo-sxim' ); ?></option>
							</select>
						</div>
						<div class="mmt-eo-ei-block-ticket-price mmt-eo-ei-block-hidden">
							<label class="mmt-full-width">
								<?php
								esc_html_e( 'Ticket Cost', 'mmt-eo-exim' );
								?>
							</label>
							<input class="mmt-full-width" name="evo_eb_export_export_event_tcost"/>
						</div>
					</div>
				</div>
			</div>
		</div>
			<?php
		endif;
	}
	/**
	 * Export Event to Eventbrite
	 *
	 * @param int       $fields Post ID.
	 * @param int       $post_ID Post.
	 * @param EVO_Event $evo_event Update or not.
	 */
	public function mmt_eo_exim_export_to_eventbrite( $fields, $post_ID, $evo_event ) {
		global $mmt_eo_exim;

		// Check if our nonce is set.
		if ( ! isset( $_POST['mmt_eo_exim_export_event_nonce'] ) ) {
			return;
		}

		// Verify that the nonce is valid.
		if ( ! wp_verify_nonce( $_POST['mmt_eo_exim_export_event_nonce'], 'mmt_eo_exim_export_event' ) ) {
			return;
		}
		$mmt_eo_exim_options = get_option( 'mmt_eo_exim_options' );

		$token               = isset( $mmt_eo_exim_options['eb_private_token'] ) ? $mmt_eo_exim_options['eb_private_token'] : '';
		$organizer_id        = isset( $mmt_eo_exim_options['eb_export_organizer'] ) ? $mmt_eo_exim_options['eb_export_organizer'] : '';
		$eb_default_currency = isset( $mmt_eo_exim_options['eb_default_currency'] ) ? $mmt_eo_exim_options['eb_default_currency'] : 'USD';
		if ( empty( $organizer_id ) ) {
			return;
		}
		$event_id = $post_ID;
		if ( empty( $event_id ) ) {
			return;
		}
		$evo_event = new EVO_Event( $event_id );
		$epmv      = get_post_custom( $post_ID );
		// If already Posted.
		if ( isset( $epmv['evcal_export_to_eventbrite_done'][0] ) && 'yes' === $epmv['evcal_export_to_eventbrite_done'][0] ) {
			return;
		}
		if ( isset( $_POST['evo_eb_export_export_event'] ) && 'on' === $_POST['evo_eb_export_export_event'] ) {
			update_post_meta( $event_id, 'evcal_export_to_eventbrite_done', 'yes' );
			$event_status_set = isset( $_POST['evo_eb_export_export_event_status'] ) ? $_POST['evo_eb_export_export_event_status'] : 'draft';

			$new_event   = get_post( $event_id );
			$event       = array();
			$srow        = $epmv['evcal_srow'][0];
			$erow        = isset( $epmv['evcal_erow'][0] ) ? $epmv['evcal_erow'][0] : $srow + 60;
			$date_format = get_option( 'date_format' );
			$start_date  = gmdate( 'Y-m-d\TH:i:s', $srow );
			$end_date    = gmdate( 'Y-m-d\TH:i:s', $erow );

			$event['event.name.html']      = get_the_title( $event_id );
			$event['event.summary']        = get_the_content( $event_id );
			$event['event.start.timezone'] = empty( get_option( 'timezone_string' ) ) ? 'Asia/Kathmandu' : get_option( 'timezone_string' );
			$event['event.end.timezone']   = empty( get_option( 'timezone_string' ) ) ? 'Asia/Kathmandu' : get_option( 'timezone_string' );
			$event['event.start.utc']      = $start_date . 'Z';
			$event['event.end.utc']        = $end_date . 'Z';
			$event['event.currency']       = $eb_default_currency;

			// For repeating events.
			$repeat_intervals = isset( $epmv['repeat_intervals'][0] ) ? $epmv['repeat_intervals'][0] : '';
			$freq             = isset( $epmv['evcal_rep_freq'][0] ) ? $epmv['evcal_rep_freq'][0] : '';
			$repeat           = isset( $epmv['evcal_repeat'][0] ) ? $epmv['evcal_repeat'][0] : '';
			if ( isset( $epmv['evcal_repeat'][0] ) && 'yes' === $epmv['evcal_repeat'][0] && 'custom' !== $freq ) {
				if ( $evo_event->is_repeating_event() ) {
					$repeat_intervals         = $evo_event->get_repeats();
					$event['event.is_series'] = 'true';
				}
			}
			$eventbrite_create_event = 'https://www.eventbriteapi.com/v3/organizations/' . $organizer_id . '/events/';
			$args                    = array(
				'headers' => array(
					'Content-Type'  => 'application/x-www-form-urlencoded',
					'Authorization' => 'Bearer ' . $token,
				),
				'body'    => $event,
			);
			if ( 'custom' === $freq && 'yes' === $mmt_eo_exim_options['evo_eb_exports_enable_custom_repeat'] && 'yes' === $repeat ) {
				// Do not create event, conitue on repeat events.
				$freq = 'custom';
			} else {
				$response = wp_remote_post( $eventbrite_create_event, $args );
				$json     = wp_remote_retrieve_body( $response );
				$details  = json_decode( $json );

				$eventbrite_id = isset( $details->id ) ? $details->id : null;
				if ( ! empty( $eventbrite_id ) ) {
					if ( 'publish' === $event_status_set ) {
						$ticket_name = isset( $_POST['evo_eb_export_export_event_tclass'] ) ? $_POST['evo_eb_export_export_event_tclass'] : esc_html__( 'Basic', 'mmt-eo-exim' );
						$ticket_type = isset( $_POST['evo_eb_export_export_event_ttype'] ) ? $_POST['evo_eb_export_export_event_ttype'] : 'free';
						$capacity    = isset( $_POST['evo_eb_export_export_event_capacity'] ) ? $_POST['evo_eb_export_export_event_capacity'] : 50;

						$ticket_args['ticket_class.name']           = $ticket_name;
						$ticket_args['ticket_class.quantity_total'] = $capacity;
						if ( 'free' === $ticket_type ) {
							$ticket_args['ticket_class.free'] = true;
						} else {
							$cost = isset( $_POST['evo_eb_export_export_event_tcost'] ) ? $_POST['evo_eb_export_export_event_tcost'] : 22;

							$ticket_args['ticket_class.cost'] = $eb_default_currency . ', ' . $cost;
						}

						$eventbrite_ticket_class = 'https://www.eventbriteapi.com/v3/events/' . $eventbrite_id . '/ticket_classes/';
						$args                    = array(
							'headers' => array(
								'Content-Type'  => 'application/x-www-form-urlencoded',
								'Authorization' => 'Bearer ' . $token,
							),
							'body'    => $ticket_args,
						);

						$response  = wp_remote_post( $eventbrite_ticket_class, $args );
						$json      = wp_remote_retrieve_body( $response );
						$details   = json_decode( $json );
						$ticket_id = isset( $details->id ) ? $details->id : null;
						if ( ! empty( $ticket_id ) ) {
							$eventbrite_update_event = 'https://www.eventbriteapi.com/v3/events/' . $eventbrite_id . '/publish/';
							$args                    = array(
								'headers' => array(
									'Content-Type'  => 'application/x-www-form-urlencoded',
									'Authorization' => 'Bearer ' . $token,
								),
							);

							$response = wp_remote_post( $eventbrite_update_event, $args );
							$json     = wp_remote_retrieve_body( $response );
							$details  = json_decode( $json );
							//result [published] => 1.
						}
					}
				}
			}
			if ( $evo_event->is_repeating_event() && isset( $epmv['evcal_repeat'][0] ) && 'yes' === $epmv['evcal_repeat'][0] ) {
				// For Repeat Events.
				if ( 'daily' === $freq ) {
					$freq    = 'DAILY';
					$seconds = 86400;
				} elseif ( 'monthly' === $freq ) {
					$freq    = 'MONTHLY';
					$seconds = 86400 * 30;
				} elseif ( 'weekly' === $freq ) {
					$seconds = 86400 * 7;
				} elseif ( 'yearly' === $freq ) {
					$freq    = 'YEARLY';
					$seconds = 86400 * 365;
				} else {
					$freq = 'custom';
				}
				$repeat_intervals = $evo_event->get_repeats();
				if ( is_array( $repeat_intervals ) && 'custom' !== $freq ) {
					$parent_event_id = $details->id;

					$revent['schedule.occurrence_duration'] = $seconds;
					$revent['schedule.recurrence_rule']     = 'DTSTART:' . $start_date . 'Z' . "\nRRULE:FREQ=" . $freq . ';COUNT=' . count( $repeat_intervals );
					$eventbrite_create_event                = 'https://www.eventbriteapi.com/v3/events/' . $parent_event_id . '/schedules/';
					$args                                   = array(
						'headers' => array(
							'Content-Type'  => 'application/x-www-form-urlencoded\r\n',
							'Authorization' => 'Bearer ' . $token,
						),
						'body'    => $revent,
					);

					$response = wp_remote_post( $eventbrite_create_event, $args );
					$json     = wp_remote_retrieve_body( $response );
					$details  = json_decode( $json );

				} elseif ( ! empty( $repeat_intervals ) && 'custom' === $freq && 'yes' === $mmt_eo_exim_options['evo_eb_exports_enable_custom_repeat'] ) {
					$repeat_intervals = $evo_event->get_repeats();
					foreach ( $repeat_intervals as $ri ) {
						$srow       = (int) $ri[0];
						$erow       = (int) $ri[1];
						$start_date = gmdate( 'Y-m-d\TH:i:s', $srow );
						$end_date   = gmdate( 'Y-m-d\TH:i:s', $erow );

						$event['event.start.utc'] = $start_date . 'Z';
						$event['event.end.utc']   = $end_date . 'Z';
						$eventbrite_create_event  = 'https://www.eventbriteapi.com/v3/organizations/' . $organizer_id . '/events/';
						$args                     = array(
							'headers' => array(
								'Content-Type'  => 'application/x-www-form-urlencoded\r\n',
								'Authorization' => 'Bearer ' . $token,
							),
							'body'    => $event,
						);

						$response = wp_remote_post( $eventbrite_create_event, $args );
						$json     = wp_remote_retrieve_body( $response );
						$details  = json_decode( $json );
					}
				}
			}
		}
	}
}
new MMT_EO_ExIm_Export_Eventbrite();
