<?php

if( !defined( 'ABSPATH' ) ) exit;  // Exit if accessed directly

function wpgv__doajax_item_pdf_save_func() {
	$catid = sanitize_text_field(base64_decode($_POST['catid']));
	$itemid = sanitize_text_field(base64_decode($_POST['itemid']));
	$buyingfor = sanitize_text_field(base64_decode($_POST['buyingfor']));
	$for = sanitize_text_field(base64_decode($_POST['yourname']));
	$from = isset($_POST['recipientname']) ? sanitize_text_field(base64_decode($_POST['recipientname'])) : '';
	$value = sanitize_text_field(base64_decode($_POST['totalprice']));
	$message = sanitize_textarea_field(base64_decode($_POST['recipientmessage']));
	$code = $_POST['couponcode'];
	$shipping = sanitize_text_field(base64_decode($_POST['shipping']));
	$shipping_email = isset($_POST['shipping_email']) ? sanitize_email(base64_decode($_POST['shipping_email'])) : '';
	$firstname = isset($_POST['firstname']) ? sanitize_text_field(base64_decode($_POST['firstname'])) : '';
	$lastname = isset($_POST['lastname']) ? sanitize_text_field(base64_decode($_POST['lastname'])) : '';
	$receipt_email = isset($_POST['receipt_email']) ? sanitize_email(base64_decode($_POST['receipt_email'])) : '';
	$address = isset($_POST['address']) ? sanitize_text_field(base64_decode($_POST['address'])) : '';
	$pincode = isset($_POST['pincode']) ? sanitize_text_field(base64_decode($_POST['pincode'])) : '';
	$shipping_method = isset($_POST['shipping_method']) ? base64_decode($_POST['shipping_method']) : '';
	$paymentmethod = sanitize_text_field(base64_decode($_POST['paymentmethod']));

	global $wpdb;
	$voucher_table 	= $wpdb->prefix . 'giftvouchers_list';
	$setting_table 	= $wpdb->prefix . 'giftvouchers_setting';
	$setting_options = $wpdb->get_row( "SELECT * FROM $setting_table WHERE id = 1" );
	$image = get_attached_file(get_post_thumbnail_id($itemid)) ? get_attached_file(get_post_thumbnail_id($itemid)) : get_option('wpgv_demoimageurl');
	$voucher_bgcolor = wpgv_hex2rgb($setting_options->voucher_bgcolor);
	$voucher_color = wpgv_hex2rgb($setting_options->voucher_color);
	$currency = ($setting_options->currency_position == 'Left') ? $setting_options->currency.' '.$value : $value.' '.$setting_options->currency;
	$expiry = ($setting_options->voucher_expiry_type == 'days') ? date('d.m.Y',strtotime('+'.$setting_options->voucher_expiry.' days',time())) . PHP_EOL : $setting_options->voucher_expiry;

    $order_count = $wpdb->get_var( "SELECT COUNT(*) FROM $voucher_table" );
    if($order_count > 10) {
        $html = sprintf('Voucher Orders are more than 10. Please Upgrade Wordpress Gift Voucher Plugin to <a href="%s" target="_blank">premium</a> for more features and unlimited orders.', 'http://www.codemenschen.at/wordpress-gift-voucher-plugin/');
        die($html);
    }
    
	$upload = wp_upload_dir();
 	$upload_dir = $upload['basedir'];
 	$curr_time = time();
 	$upload_dir = $upload_dir . '/voucherpdfuploads/'.$curr_time.$_POST['couponcode'].'.pdf';
 	$upload_url = $curr_time.$_POST['couponcode'];

	$formtype = 'item';
	$preview = false;

	if ($setting_options->is_style_choose_enable) {
		$voucher_style = sanitize_text_field(base64_decode($_POST['style']));
		$style_image = get_post_meta($itemid, 'style'.($voucher_style+1).'_image', true);
		$image_attributes = get_attached_file( $style_image );
		$image = ($image_attributes) ? $image_attributes : get_option('wpgv_demoimageurl');
	} else {
		$voucher_style = $setting_options->voucher_style;
		$style_image = get_post_meta($itemid, 'style1_image', true);
		$image_attributes = get_attached_file( $style_image );
		$image = ($image_attributes) ? $image_attributes : get_option('wpgv_demoimageurl');
	}

	switch ($voucher_style) {
		case 0:
			require_once( WPGIFT__PLUGIN_DIR .'/templates/pdfstyles/style1.php');
        	break;
		case 1:
	    	require_once( WPGIFT__PLUGIN_DIR .'/templates/pdfstyles/style2.php');
    	    break;
		case 2:
	    	require_once( WPGIFT__PLUGIN_DIR .'/templates/pdfstyles/style3.php');
    	    break;
		default:
	    	require_once( WPGIFT__PLUGIN_DIR .'/templates/pdfstyles/style1.php');
    	    break;
	}

	$pdf->Output('F',$upload_dir);

	$wpdb->insert(
		$voucher_table,
		array(
			'order_type'		=> 'items',
			'itemcat_id' 		=> $catid,
			'item_id' 			=> $itemid,
			'buying_for'		=> $buyingfor,
			'from_name' 		=> $for,
			'to_name' 			=> $from,
			'amount'			=> $value,
			'message'			=> $message,
			'shipping_type'		=> $shipping,
			'shipping_email'	=> $shipping_email,
			'firstname'			=> $firstname,
			'lastname'			=> $lastname,
			'email'				=> $receipt_email,
			'address'			=> $address,
			'postcode'			=> $pincode,
			'shipping_method'	=> $shipping_method,
			'pay_method'		=> $paymentmethod,
			'expiry'			=> $expiry,
			'couponcode'		=> $code,
			'voucherpdf_link'	=> $upload_url,
			'voucheradd_time'	=> current_time( 'mysql' ),
			'payment_status'	=> 'Not Pay'
		)
	);

	$lastid = $wpdb->insert_id;
	WPGV_Gift_Voucher_Activity::record( $lastid, 'create', '', 'Voucher ordered by '.$for.', Message: '.$message );

    $preshipping_methods = explode(',', $setting_options->shipping_method);
    foreach ($preshipping_methods as $method) {
        $preshipping_method = explode(':', $method);
        if(trim($preshipping_method[1]) == $shipping_method) {
        	$value += trim($preshipping_method[0]);
        	break;
        }
    }
	$currency = ($setting_options->currency_position == 'Left') ? $setting_options->currency.' '.$value : $value.' '.$setting_options->currency;

	$return_url = get_site_url() .'/voucher-payment-successful/?voucheritem='.$lastid;
	$cancel_url = get_site_url() .'/voucher-payment-cancel/?voucheritem='.$lastid;
	$notify_url = get_site_url() .'/voucher-payment-successful/?voucheritem='.$lastid;

	if ($paymentmethod == 'Paypal') {

		$paypal_email = $setting_options->paypal_email;

		$querystring = '';
		if($setting_options->test_mode) {
			$querystring .= 'https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_xclick';
		} else {
			$querystring .= 'https://www.paypal.com/cgi-bin/webscr?cmd=_xclick';
		}
		$querystring .= "&business=".urlencode($paypal_email)."&";
		$querystring .= "item_name=".urlencode(get_the_title($itemid).' Voucher')."&";
    	$querystring .= "item_number=".urlencode($lastid)."&";
    	$querystring .= "amount=".urlencode($value)."&";
    	$querystring .= "currency_code=$setting_options->currency_code&";
    	if($shipping == 'shipping_as_post') {
    		$querystring .= "first_name=".urlencode($firstname)."&";
    		$querystring .= "last_name=".urlencode($lastname)."&";
    		$querystring .= "email=".urlencode($receipt_email)."&";
    	} elseif ($shipping == 'shipping_as_email') {
    		$querystring .= "first_name=".urlencode($for)."&";
    		$querystring .= "email=".urlencode($receipt_email)."&";
    	}
    	$querystring .= "custom=".urlencode($lastid)."&";
    	$querystring .= "return=".urlencode(stripslashes($return_url))."&";
    	$querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
    	// $querystring .= "notify_url=".urlencode($notify_url);

	    echo $querystring;
		
	} elseif($paymentmethod == 'Sofort') {

		$Sofortueberweisung = new Sofortueberweisung($setting_options->sofort_configure_key);

		$Sofortueberweisung->setAmount($value);
		$Sofortueberweisung->setCurrencyCode($setting_options->currency_code);

		$Sofortueberweisung->setReason($setting_options->reason_for_payment, $lastid);
		$Sofortueberweisung->setSuccessUrl($return_url, true);
		$Sofortueberweisung->setAbortUrl($cancel_url);
		$Sofortueberweisung->setNotificationUrl($notify_url);

		$Sofortueberweisung->sendRequest();

		if($Sofortueberweisung->isError()) {
			//SOFORT-API didn't accept the data
			echo $Sofortueberweisung->getError();
		} else {
			//buyer must be redirected to $paymentUrl else payment cannot be successfully completed!
			$paymentUrl = $Sofortueberweisung->getPaymentUrl();
			echo $paymentUrl;
		}
	} elseif ($paymentmethod == 'Stripe') {
		$stripesuccesspageurl = get_option('wpgv_stripesuccesspage');
		$stripeemail = ($receipt_email) ? $receipt_email : $shipping_email;
		echo '<div class="wpgvmodaloverlay"><div class="wpgvmodalcontent"><h4>'.get_the_title($itemid).'</h4><span class="wpgv-payment-errors"></span><form action="'.get_page_link($stripesuccesspageurl).'" method="POST" id="stripePaymentForm">
				<input type="hidden" name="orderid" value="'.$lastid.'">
    			<div class="payeremail">
        			<input type="email" name="email" placeholder="Email Address" class="wpgv-email" required value="'.$stripeemail.'">
    			</div>
    			<div class="paymentinfo">
        			<input type="text" name="card_num" placeholder="Card Number" size="20" autocomplete="off" class="wpgv-card-number" required>
    				<input type="text" name="cvc" placeholder="CVV" size="3" autocomplete="off" class="wpgv-card-cvc" required>
    				<input type="text" name="exp_month" placeholder="MM" size="2" class="wpgv-card-expiry-month" autocomplete="off" required>
    				<input type="text" name="exp_year" placeholder="YY" size="2" class="wpgv-card-expiry-year" autocomplete="off" required>
    			</div>
    			<button type="submit" id="wpgvpayBtn">Pay '.$currency.'</button>
    			<div class="wpgv-cancel"><a href="'.$cancel_url.'">Cancel Payment</a></div></form></div></div>
    			<script type="text/javascript">
					Stripe.setPublishableKey(\''.$setting_options->stripe_publishable_key.'\');

					function stripeResponseHandler(status, response) {
    					if (response.error) {
        					jQuery("#wpgvpayBtn").removeAttr("disabled");
        					jQuery(".wpgv-payment-errors").html(response.error.message);
    					} else {
        					var form$ = jQuery("#stripePaymentForm");
        					//get token id
        					var token = response["id"];
        					//insert the token into the form
        					form$.append("<input type=\'hidden\' name=\'stripeToken\' value=\'" + token + "\' />");
        					//submit form to the server
        					form$.get(0).submit();
    					}
					}
					jQuery(document).ready(function($) {
    					//on form submit
    					$("#stripePaymentForm").submit(function(event) {
        					//disable the submit button to prevent repeated clicks
        					$("#wpgvpayBtn").attr("disabled", "disabled");
        
 					       //create single-use token to charge the user
        					Stripe.createToken({
            					number: $(".wpgv-card-number").val(),
            					cvc: $(".wpgv-card-cvc").val(),
            					exp_month: $(".wpgv-card-expiry-month").val(),
            					exp_year: $(".wpgv-card-expiry-year").val()
        					}, stripeResponseHandler);
        
        					//submit from callback
					        return false;
    					});
					});
				</script>';
	} elseif($paymentmethod == 'Per Invoice') {
		echo $notify_url.'&per_invoice=1';
	}

	wp_die();
}
add_action('wp_ajax_nopriv_wpgv_doajax_item_pdf_save_func', 'wpgv__doajax_item_pdf_save_func');
add_action('wp_ajax_wpgv_doajax_item_pdf_save_func', 'wpgv__doajax_item_pdf_save_func');