<?php


/**
 * Postback Routes
 */


add_action( 'admin_init', 'rafflepress_pro_export_contestants' );
add_action( 'admin_init', 'rafflepress_pro_export_entries' );




/**
 * Rewrite EndPoints Routes
 */

add_action( 'init', 'rafflepress_pro_add_rules' );

function rafflepress_pro_add_rules() {
	add_rewrite_rule(
		'^rafflepress/([0-9]+)/?',
		'index.php?rafflepress_page=rafflepress_render&rafflepress_id=$matches[1]',
		'top'
	);
	add_rewrite_rule(
		'^rp/([0-9]+)/?',
		'index.php?rafflepress_page=rafflepress_render&rafflepress_id=$matches[1]',
		'top'
	);
}


function rafflepress_pro_add_custom_slug( $slug ) {
	if ( ! empty( $slug ) ) {
		add_rewrite_rule(
			'^' . $slug . '/([0-9]+)/?',
			'index.php?rafflepress_page=rafflepress_render&rafflepress_id=$matches[1]',
			'top'
		);
		flush_rewrite_rules();
	}
}

// Add the vars so that WP recognizes it
add_filter( 'query_vars', 'rafflepress_pro_add_query_var' );

function rafflepress_pro_add_query_var( $vars ) {
	$vars[] = 'rafflepress_page';
	$vars[] = 'rafflepress_id';
	return $vars;
}

add_action( 'template_redirect', 'rafflepress_pro_routes' );

function rafflepress_pro_routes() {
	 $rafflepress_id = get_query_var( 'rafflepress_id' );
	if ( empty( $rafflepress_id ) ) {
		// referral id
		if ( ! empty( $_GET['rpid'] ) ) {
			$rafflepress_id = absint( $_GET['rpid'] );
		}
	}

	if ( ! empty( $rafflepress_id ) ) {
		//$rafflepress_id = get_query_var('rafflepress_id');
		$c = ob_get_contents();
		if ( $c ) {
			@ob_end_clean();
		}

		header( 'Cache-Control: no-cache, no-store, must-revalidate, max-age=0' ); // HTTP 1.1.
		header( 'Cache-Control: post-check=0, pre-check=0', false );
		header( 'Pragma: no-cache' ); // HTTP 1.0.
		header( 'Expires: 0 ' );

		require_once RAFFLEPRESS_PRO_PLUGIN_PATH . 'resources/views/rafflepress-giveaway.php';
		exit();
	}
}


/**
 * Admin Menu Routes
 */

add_action( 'admin_menu', 'rafflepress_pro_create_menus' );

function rafflepress_pro_create_menus() {
	$menu_capability = apply_filters( 'rafflepress_menu_capability', 'edit_others_posts' );

	// Return if current user does not have specified menu capability
	if ( ! current_user_can( $menu_capability ) ) {
		return; }

	// get notifications count
	$notification        = '';
	$n                   = new RafflePress_Notifications();
	$notifications_count = $n->get_count();

	$rafflepress_settings = get_option( 'rafflepress_settings' );
	$rafflepress_app_settings = json_decode( $rafflepress_settings );
	if ( isset( $rafflepress_app_settings ) ) {
		if ( isset( $rafflepress_app_settings->disable_rafflepress_notifications ) ) {
			if ( $rafflepress_app_settings->disable_rafflepress_notifications === true ) {
				$notifications_count = 0;
			}
		}
	}

	
	// check for invalid license
	$rafflepress_a = get_option( 'rafflepress_per' );
	if(empty($rafflepress_a)){
		//$notifications_count = 1;
	}

	

	if ( ! empty( $notifications_count ) ) {
		$notification = '<span class="update-plugins"><span class="plugin-count">' . $notifications_count . '</span></span>';
	}

	add_menu_page(
		'RafflePress',
		'RafflePress ' . $notification,
		$menu_capability,
		'rafflepress_pro',
		'rafflepress_pro_dashboard_page',
		'data:image/svg+xml;base64,' . ' ',
		apply_filters( 'rafflepress_top_level_menu_postion', 58 )
	);

	add_submenu_page(
		'rafflepress_pro',
		__( 'Giveaways', 'rafflepress-pro' ),
		__( 'Giveaways', 'rafflepress-pro' ),
		$menu_capability,
		'rafflepress_pro',
		'rafflepress_pro_dashboard_page'
	);

	add_submenu_page(
		'rafflepress_pro',
		__( 'Add New', 'rafflepress-pro' ),
		__( 'Add New', 'rafflepress-pro' ),
		$menu_capability,
		'rafflepress_pro_add_new',
		'rafflepress_pro_add_new_page'
	);

	add_submenu_page(
		'rafflepress_pro',
		__( 'Settings', 'rafflepress-pro' ),
		__( 'Settings', 'rafflepress-pro' ),
		$menu_capability,
		'rafflepress_pro_settings',
		'rafflepress_pro_settings_page'
	);

	add_submenu_page(
		'rafflepress_pro',
		__( 'About Us', 'rafflepress-pro' ),
		__( 'About Us', 'rafflepress-pro' ),
		$menu_capability,
		'rafflepress_pro_about_us',
		'rafflepress_pro_about_us_page'
	);

	if ( RAFFLEPRESS_PRO_BUILD == 'lite') {
		add_submenu_page(
			'rafflepress_pro',
			__( 'Get Pro', 'rafflepress-pro' ),
			'<span id="rp-lite-admin-menu__upgrade">' . __( 'Get Pro', 'rafflepress-pro' ) . '</span>',
			'read',
			'rafflepress_pro_get_pro',
			'rafflepress_pro_get_pro_page'
		);
		// add upgrade link color and blank target
		add_action( 'admin_footer', 'seedprod_pro_upgrade_link_class' );
		function seedprod_pro_upgrade_link_class() {
			echo "<script>jQuery(function($) { $('#rp-lite-admin-menu__upgrade').parent().attr('target','_blank'); $('#rp-lite-admin-menu__upgrade').parent().parent().addClass('rp-lite-admin-menu__upgrade_wrapper')});</script>";
		}

	}

	add_submenu_page(
		'rafflepress_pro',
		__( 'Builder', 'rafflepress-pro' ),
		__( 'Builder', 'rafflepress-pro' ),
		'read',
		'rafflepress_pro_builder',
		'rafflepress_pro_builder_page'
	);

	add_submenu_page(
		'rafflepress_pro',
		'Debug',
		'Debug',
		'read',
		'rafflepress_pro_debug',
		'rafflepress_pro_debug_page'
	);
}

add_action( 'admin_head', 'rafflepress_pro_remove_menus' );

function rafflepress_pro_remove_menus() {
	remove_submenu_page( 'rafflepress_pro', 'rafflepress_pro_builder' );
	remove_submenu_page( 'rafflepress_pro', 'rafflepress_pro_debug' );
}

// Add nonce to 'Add New' submenu URL for CSRF protection via JavaScript
add_action( 'admin_footer', 'rafflepress_pro_add_nonce_to_menu' );

function rafflepress_pro_add_nonce_to_menu() {
	// Only run on admin pages where the menu is visible
	if ( ! current_user_can( apply_filters( 'rafflepress_menu_capability', 'edit_others_posts' ) ) ) {
		return;
	}
	
	$nonce = wp_create_nonce( 'rafflepress_add_new' );
	?>
	<script type="text/javascript">
	jQuery(document).ready(function($) {
		// Find the "Add New" menu item and add nonce to its href
		$('a[href*="page=rafflepress_pro_add_new"]').each(function() {
			var currentHref = $(this).attr('href');
			if (currentHref.indexOf('_wpnonce=') === -1) {
				$(this).attr('href', currentHref + '&_wpnonce=<?php echo $nonce; ?>');
			}
		});
	});
	</script>
	<?php
}

function rafflepress_pro_dashboard_page() {
	 require_once RAFFLEPRESS_PRO_PLUGIN_PATH . 'resources/views/dashboard.php';
}

function rafflepress_pro_add_new_page() {
	// Check capabilities first
	$menu_capability = apply_filters( 'rafflepress_menu_capability', 'edit_others_posts' );
	if ( ! current_user_can( $menu_capability ) ) {
		wp_die( __( 'Sorry, you are not allowed to access this page.', 'rafflepress-pro' ) );
	}
	
	// This function should never be called due to admin_init redirect,
	// but exists to satisfy WordPress submenu requirements
	wp_die( __( 'This page should redirect automatically. Please try again.', 'rafflepress-pro' ) );
}


function rafflepress_pro_builder_page() {
	require_once RAFFLEPRESS_PRO_PLUGIN_PATH . 'resources/views/builder.php';
}

function rafflepress_pro_debug_page() {
	 $log = get_option( 'rafflepress_log' );
	echo 'Debug Log (Clear query param: rp-clear-debug=1)';
	echo( $log );
	echo '<br>';
	echo '<br><br>Debug On or Off (Enable query param: rp-enable=1 for on and rp-enable=2 for off)';
	echo( get_option( 'rafflepress_enable_log' ) );

	// clear log
	if ( ! empty( $_GET['rp-clear-debug'] ) ) {
		update_option( 'rafflepress_log', '' );
	}
	// turn on or off debug
	if ( ! empty( $_GET['rp-enable'] ) && $_GET['rp-enable'] == '1' ) {
		update_option( 'rafflepress_enable_log', true );
	}
	if ( ! empty( $_GET['rp-enable'] ) && $_GET['rp-enable'] == '2' ) {
		update_option( 'rafflepress_enable_log', false );
	}
}

/* Short circuit new request */

// Secure POST and AJAX handler for giveaway creation
add_action( 'admin_post_rafflepress_create_giveaway', 'rafflepress_pro_create_giveaway_handler' );
add_action( 'wp_ajax_rafflepress_pro_create_giveaway', 'rafflepress_pro_create_giveaway_handler' );


/* Redirect to SPA */

add_action( 'admin_init', 'rafflepress_pro_redirect_to_site', 1 );

function rafflepress_pro_redirect_to_site() {
	// settings page
	if ( isset( $_GET['page'] ) && $_GET['page'] == 'rafflepress_pro_settings' ) {
		wp_redirect( 'admin.php?page=rafflepress_pro#/settings' );
		exit();
	}

	// add new page - redirect to Vue template chooser (secure creation via AJAX)
	if ( isset( $_GET['page'] ) && $_GET['page'] == 'rafflepress_pro_add_new' ) {
		// Verify nonce before redirect to prevent CSRF attacks
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( $_GET['_wpnonce'], 'rafflepress_add_new' ) ) {
			wp_die( __( 'Security check failed. Please try again.', 'rafflepress-pro' ), __( 'Security Error', 'rafflepress-pro' ), array( 'response' => 403 ) );
		}
		wp_redirect( 'admin.php?page=rafflepress_pro_builder&_wpnonce=' . wp_create_nonce( 'rafflepress_nonce' ) . '&id=0#/template' );
		exit();
	}

	// builder page security check - for direct access
	if ( isset( $_GET['page'] ) && $_GET['page'] == 'rafflepress_pro_builder' ) {
		// Get giveaway ID from URL parameter
		$giveaway_id = isset( $_GET['id'] ) ? $_GET['id'] : '';
		
		// CSRF Protection for new giveaway mode (id=0 or empty)
		if ( empty( $giveaway_id ) || $giveaway_id == '0' ) {
			// New giveaway mode requires nonce verification
			if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( $_GET['_wpnonce'], 'rafflepress_nonce' ) ) {
				wp_die(
					__( 'Security check failed. Please try again.', 'rafflepress-pro' ),
					__( 'Security Error', 'rafflepress-pro' ),
					array( 'response' => 403 )
				);
			}
		}
		
		// Capability check - ensure user can manage giveaways
		$required_capability = apply_filters( 'rafflepress_builder_capability', 'edit_others_posts' );
		if ( ! current_user_can( $required_capability ) ) {
			wp_die(
				__( 'You do not have sufficient permissions to access the giveaway builder.', 'rafflepress-pro' ),
				__( 'Insufficient Permissions', 'rafflepress-pro' ),
				array( 'response' => 403 )
			);
		}
	}

	//  about us page
	if ( isset( $_GET['page'] ) && $_GET['page'] == 'rafflepress_pro_about_us' ) {
		wp_redirect( 'admin.php?page=rafflepress_pro#/aboutus' );
		exit();
	}

	// getpro page
	if ( isset( $_GET['page'] ) && $_GET['page'] == 'rafflepress_pro_get_pro' ) {
		wp_redirect( rafflepress_pro_upgrade_link( 'wp-sidebar-menu' ) );
		exit();
	}
}


/**
 * Ajax Request Routes
 */

if ( defined( 'DOING_AJAX' ) ) {
	add_action( 'wp_ajax_rafflepress_pro_dismiss_settings_lite_cta', 'rafflepress_pro_dismiss_settings_lite_cta' );
	add_action( 'wp_ajax_rafflepress_pro_save_settings', 'rafflepress_pro_save_settings' );
	add_action( 'wp_ajax_rafflepress_pro_save_api_key', 'rafflepress_pro_save_api_key' );
	
	add_action( 'wp_ajax_rafflepress_pro_deactivate_api_key', 'rafflepress_pro_deactivate_api_key' );
	
	add_action( 'wp_ajax_rafflepress_pro_save_template', 'rafflepress_pro_save_template' );
	add_action( 'wp_ajax_rafflepress_pro_save_giveaway', 'rafflepress_pro_save_giveaway' );
	add_action( 'wp_ajax_rafflepress_pro_create_giveaway', 'rafflepress_pro_create_giveaway_handler' );
	add_action( 'wp_ajax_rafflepress_pro_save_slug', 'rafflepress_pro_save_slug' );
	add_action( 'wp_ajax_rafflepress_pro_get_utc_offset', 'rafflepress_pro_get_utc_offset' );
	add_action( 'wp_ajax_rafflepress_pro_save_publish', 'rafflepress_pro_save_publish' );
	add_action( 'wp_ajax_rafflepress_pro_giveaway_datatable', 'rafflepress_pro_giveaway_datatable' );
	add_action( 'wp_ajax_rafflepress_pro_duplicate_giveaway', 'rafflepress_pro_duplicate_giveaway' );
	add_action( 'wp_ajax_rafflepress_pro_get_giveaway_list', 'rafflepress_pro_get_giveaway_list' );
	add_action( 'wp_ajax_rafflepress_pro_archive_selected_giveaways', 'rafflepress_pro_archive_selected_giveaways' );
	add_action( 'wp_ajax_rafflepress_pro_unarchive_selected_giveaways', 'rafflepress_pro_unarchive_selected_giveaways' );
	add_action( 'wp_ajax_rafflepress_pro_delete_archived_giveaways', 'rafflepress_pro_delete_archived_giveaways' );
	add_action( 'wp_ajax_rafflepress_pro_end_giveaway', 'rafflepress_pro_end_giveaway' );
	add_action( 'wp_ajax_rafflepress_pro_start_giveaway', 'rafflepress_pro_start_giveaway' );
	add_action( 'wp_ajax_rafflepress_pro_enable_disable_giveaway', 'rafflepress_pro_enable_disable_giveaway' );

	add_action( 'wp_ajax_rafflepress_pro_get_automation_tool_list', 'rafflepress_pro_get_automation_tool_list' );

	add_action( 'wp_ajax_rafflepress_pro_entries_report_datatable', 'rafflepress_pro_entries_report_datatable' );
	add_action( 'wp_ajax_rafflepress_pro_ps_results_datatable', 'rafflepress_pro_ps_results_datatable' );
	add_action( 'wp_ajax_rafflepress_pro_entries_datatable', 'rafflepress_pro_entries_datatable' );
	add_action( 'wp_ajax_rafflepress_pro_valid_selected_entries', 'rafflepress_pro_valid_selected_entries' );
	add_action( 'wp_ajax_rafflepress_pro_invalid_selected_entries', 'rafflepress_pro_invalid_selected_entries' );
	add_action( 'wp_ajax_rafflepress_pro_delete_invalid_entries', 'rafflepress_pro_delete_invalid_entries' );
	add_action( 'wp_ajax_rafflepress_pro_pick_winners', 'rafflepress_pro_pick_winners' );


	add_action( 'wp_ajax_rafflepress_pro_contestants_resend_email', 'rafflepress_pro_contestants_resend_email' );
	add_action( 'wp_ajax_rafflepress_pro_contestants_datatable', 'rafflepress_pro_contestants_datatable' );
	add_action( 'wp_ajax_rafflepress_pro_confirm_selected_contestants', 'rafflepress_pro_confirm_selected_contestants' );
	add_action( 'wp_ajax_rafflepress_pro_unconfirm_selected_contestants', 'rafflepress_pro_unconfirm_selected_contestants' );
	add_action( 'wp_ajax_rafflepress_pro_invalid_selected_contestants', 'rafflepress_pro_invalid_selected_contestants' );
	add_action( 'wp_ajax_rafflepress_pro_delete_invalid_contestants', 'rafflepress_pro_delete_invalid_contestants' );

	add_action( 'wp_ajax_rafflepress_pro_get_font', 'rafflepress_pro_get_font' );
	add_action( 'wp_ajax_rafflepress_pro_get_plugins_list', 'rafflepress_pro_get_plugins_list' );

	add_action( 'wp_ajax_rafflepress_pro_install_addon', 'rafflepress_pro_install_addon' );
	add_action( 'wp_ajax_rafflepress_pro_activate_addon', 'rafflepress_pro_activate_addon' );
	add_action( 'wp_ajax_rafflepress_pro_deactivate_addon', 'rafflepress_pro_deactivate_addon' );

	add_action( 'wp_ajax_rafflepress_pro_install_automation', 'rafflepress_pro_install_automation' );
	add_action( 'wp_ajax_rafflepress_pro_activate_automation', 'rafflepress_pro_activate_automation' );
	add_action( 'wp_ajax_rafflepress_pro_deactivate_automation', 'rafflepress_pro_deactivate_automation' );

	add_action( 'wp_ajax_rafflepress_pro_install_addon', 'rafflepress_pro_install_addon' );
	add_action( 'wp_ajax_rafflepress_pro_deactivate_addon', 'rafflepress_pro_deactivate_addon' );
	add_action( 'wp_ajax_rafflepress_pro_activate_addon', 'rafflepress_pro_activate_addon' );
	add_action( 'wp_ajax_rafflepress_pro_plugin_nonce', 'rafflepress_pro_plugin_nonce' );

	add_action( 'wp_ajax_rafflepress_pro_action_token', 'rafflepress_pro_action_token' );
	add_action( 'wp_ajax_nopriv_rafflepress_pro_action_token', 'rafflepress_pro_action_token' );

	add_action( 'wp_ajax_rafflepress_pro_giveaway_api', 'rafflepress_pro_giveaway_api' );
	add_action( 'wp_ajax_nopriv_rafflepress_pro_giveaway_api', 'rafflepress_pro_giveaway_api' );

	add_action( 'wp_ajax_rafflepress_pro_giveaway_comment', 'rafflepress_pro_giveaway_comment' );
	add_action( 'wp_ajax_nopriv_rafflepress_pro_giveaway_comment', 'rafflepress_pro_giveaway_comment' );

	add_action( 'wp_ajax_nopriv_rafflepress_pro_run_one_click_upgrade', 'rafflepress_pro_run_one_click_upgrade' );
	add_action( 'wp_ajax_rafflepress_pro_upgrade_license', 'rafflepress_pro_upgrade_license' );
}


/*
 * Zapier
 */

add_action( 'init', 'rafflepress_pro_zapier_callback' );


/*
 * Force License Recheck
 */
add_action( 'init', 'rafflepress_pro_force_license_recheck' );

add_action( 'init', 'rafflepress_pro_deactivate_license' );


