<?php

function pmxe_wp_ajax_wpae_send_to_codebox(){
	if ( ! check_ajax_referer( 'wp_all_export_secure', 'security', false ) ){
		exit( json_encode(array('html' => __('Security check failed.', 'wp-all-export-pro'))) );
	}

	if ( ! current_user_can( PMXE_Plugin::$capabilities ) ){
		exit( json_encode(array('html' => __('Permission denied.', 'wp-all-export-pro'))) );
	}

	// Check if 'codeboxaction' is set and handle accordingly
	$codeboxAction = isset($_POST['codeboxaction']) ? wp_unslash($_POST['codeboxaction']) : '';

	if ($codeboxAction === 'revert') {
		\Wpae\Integrations\CodeBox::revertToFunctionsFile();

		exit( json_encode(array('html' => __('Successfully reverted to functions file.', 'wp-all-export-pro'))) );
	}

	$code = isset($_POST['code']) ? wp_unslash($_POST['code']) : '';

	if (empty($code)) {
		exit( json_encode(array('html' => __('No code provided.', 'wp-all-export-pro'))) );
	}

	$response = \Wpae\Integrations\CodeBox::saveSnippetToCodeBox($code);

	if ($response) {
		$uploads   = wp_upload_dir();
		$functions = $uploads['basedir'] . DIRECTORY_SEPARATOR . WP_ALL_EXPORT_UPLOADS_BASE_DIRECTORY . DIRECTORY_SEPARATOR . 'functions.php';
		$functions = apply_filters( 'export_functions_file_path', $functions );
		$currentFunctionsContent = file_get_contents($functions);
		
		if( \Wpae\Integrations\CodeBox::isUsingCodeBox($currentFunctionsContent)){
			exit( json_encode(array('html' => __('CodeBox is already in use.', 'wp-all-export-pro'))) );
		}
		
		$backupFunctions = str_replace('.php', '_backup.php', $functions);
		file_put_contents($backupFunctions, $currentFunctionsContent);

		$functionsContent = '<?php '."\n/**\n*\n* Do not edit this file directly. \n* The code is being managed by WPCodeBox.\n* Make edits there only.\n*\n**/\n\n".'\Wpae\Integrations\CodeBox::runSnippet('.$response.');'."\n\n?>";

		file_put_contents($functions, $functionsContent);

		exit( json_encode(array('html' => __('Code successfully sent to CodeBox.', 'wp-all-export-pro'), 'codeboxid' => $response, 'functions' => $functionsContent)) );
	} else {
		exit( json_encode(array('html' => __('Failed to send code to CodeBox.', 'wp-all-export-pro'))) );
	}
}
