<?php

namespace Roots\Sage\Extras;

use Roots\Sage\Config;
use Roots\Sage\Utils;
use Roots\Sage\Authorize;
/**
 * Add <body> classes
 */
function body_class($classes) {
  // Add page slug if it doesn't exist
  if (is_single() || is_page() && !is_front_page()) {
    if (!in_array(basename(get_permalink()), $classes)) {
      $classes[] = basename(get_permalink());
    }
  }

  // Add class if sidebar is active
  if (Config\display_sidebar()) {
    $classes[] = 'sidebar-primary';
  }

  return $classes;
}
add_filter('body_class', __NAMESPACE__ . '\\body_class');

/**
 * Clean up the_excerpt()
 */
function excerpt_more() {
  return ' &hellip; <a href="' . get_permalink() . '">' . __('Continued', 'sage') . '</a>';
}
add_filter('excerpt_more', __NAMESPACE__ . '\\excerpt_more');



/* Custom Post Type Brand  */
add_action( 'init', __NAMESPACE__ . '\\create_posttype' );
function create_posttype() {
	
	register_post_type( 'package',
		array(
		  'labels' => array(
				'name' => __( 'Package' ),
				'singular_name' => __( 'Package' )
		  ),
		  'public' => true,
		  'has_archive' => true,
		  'rewrite' => array('slug' => 'package'),
		  'supports' => array(
				'title',    
				'editor',
				'excerpt',
				'thumbnail',
				'page-attributes',
			)
		) 
	);

	// Add new taxonomy, make it hierarchical (like categories)
	$labels = array(
		'name'              => _x( 'Category', 'taxonomy general name' ),
		'singular_name'     => _x( 'Category', 'taxonomy singular name' ),
		'search_items'      => __( 'Search Category' ),
		'all_items'         => __( 'All Category' ),
		'parent_item'       => __( 'Parent Category' ),
		'parent_item_colon' => __( 'Parent Category:' ),
		'edit_item'         => __( 'Edit Category' ),
		'update_item'       => __( 'Update Category' ),
		'add_new_item'      => __( 'Add New Category' ),
		'new_item_name'     => __( 'New Category Name' ),
		'menu_name'         => __( 'Category' ),
	);

	$args = array(
		'hierarchical'      => true,
		'labels'            => $labels,
		'show_ui'           => true,
		'show_admin_column' => true,
		'query_var'         => true,
		'rewrite'           => array( 'slug' => 'package-cat' ),
	);

	register_taxonomy( 'package-cat', array( 'package' ), $args );

}

// AJAX
add_action( 'wp_ajax_buy_ticket_ajax', __NAMESPACE__ . '\\buy_ticket_ajax' );
add_action( 'wp_ajax_nopriv_buy_ticket_ajax', __NAMESPACE__ . '\\buy_ticket_ajax' );
function buy_ticket_ajax(){

	require ("AuthorizeNET.php");
	$login_id=Utils\get_theme_option('authorize_login');
	$transaction_key=Utils\get_theme_option('authorize_transaction_key'); //get_theme_option('authorize_transaction_key');
	$test_mode=Utils\get_theme_option('authorize_mode'); //get_theme_option('authorize_mode');
	
	$authorize=new Authorize\AuthorizeNET($login_id,$transaction_key,$test_mode);
	$customer_email=$_REQUEST['email'];
	$desc="PURCHASE INDIVIDUAL TICKETS";
	
	$quantity=$_REQUEST['quantity'];
	$price=$_REQUEST['price'];
	
	$first_name=$_REQUEST['first_name'];
	$last_name=$_REQUEST['last_name'];
		
	$address1=$_REQUEST['address1'];
	$address2=$_REQUEST['address2'];
	$city=$_REQUEST['city'];
	$state=$_REQUEST['state'];
	$country=$_REQUEST['country'];
	$postcode=$_REQUEST['postcode'];
	$phoneNumber = $_REQUEST['phoneNumber'];	
	
	$card_number=$_REQUEST['card_number'];
	$car_ccv=$_REQUEST['car_ccv'];
	$card_holder_name=$_REQUEST['card_holder_name'];
	$month=$_REQUEST['month'];
	$year=$_REQUEST['year'];
	
	$user_id=time().rand();
	
	$profile_id="";
	$payment_id="";
	$shipping_id="";
	$transaction_id="";
	
	$message="";
	$date=$month.'-'.$year;
	$rs3=$authorize->create_transaction($card_number,$date,$car_ccv,$price,$user_id,$first_name,$last_name,$address1,$city,$state,$postcode);
	if($rs3['response'])
	{
			$transaction_id=$rs3['transaction_id'];
	}else{
			$message=$rs3['error'];
	}
	/*
	// Create Customer Profile
	$rs=$authorize->create_profile_id($user_id,$customer_email,$desc);
	if($rs['response'])
	{
		$profile_id=$rs['profile_id'];
		// Create Payment  Profile
		$billto=array(
		'firstName'=>$first_name,
		'lastName'=>$last_name,
		'company'=>"",
		'address'=>$address1,
		'city'=>$city,
		'state'=>$state,
		'zip' =>$postcode,
		'country' =>$country,
		'phoneNumber'=>"",
		'faxNumber' =>"",
		'cardNumber'=>$card_number,
		'expirationDate'=>$year.'-'.$month,
		'security-code'=>$car_ccv
		);
		
		// CReate Payment profile
		$rs1=$authorize->create_payment_id($profile_id,$billto);
		if($rs1['response'])
		{
			$payment_id=$rs1['payment_id'];
			
			// Create Shipping profile
			$rs2=$authorize->create_shipping_id($profile_id,$billto);
			if($rs2['response'])
			{
				$shipping_id=$rs2['shipping_id'];
				
			}else{
				$message=$rs2['error'];
			}
		}else{
			$message=$rs1['error'];
		}
		
	}else{
		$message=$rs['error'];
	}
	if($profile_id !="" && $payment_id !="" && $shipping_id !="")
	{
		//$amount=$price*$quantity;
		$rs3=$authorize->create_transaction($profile_id,$payment_id,$shipping_id,$price,$user_id);
		if($rs3['response'])
		{
			$transaction_id=$rs3['transaction_id'];
		}else{
			$message=$rs3['error'];
		}
	}		
	//$transaction_id = 100;
	*/
	
	if($transaction_id !="")
	{
		$result=array('response'=>'sucess','message'=>'<p class="success">Thank you for your support!</p>');
		//Send to Customer 
		$subject = "PURCHASE INDIVIDUAL TICKETS";
		$to = $_REQUEST['email'];		
		$body = sprintf("Dear %s %s, <br/>", $first_name, $last_name);
		$body .= sprintf('<br/>Your ticket purchase has been completed.  We thank you for participating in UCP’S CHAMPIONS in LIFE NIGHT event. <br/>');
		$body .= sprintf('<p><span style="font-size:10px;">*For federal income tax purposes, you can deduct as a charitable contribution the price of this ticket less its fair market value.  We estimate the fair market value of this ticket to be $65, and so your charitable contribution is $135.</span> </p>');
		$body .= sprintf('<h3 style="text-transform:uppercase;padding:0;margin:0px;line-height:24px;">PURCHASE DETAILS:</h3>');
		$body .= sprintf('Transaction number: %s <br/>', $transaction_id);
		$body .= sprintf('Quantity: %s <br/>', $quantity);
		$body .= sprintf('Amount pay: $%s <br/><br/>', $price);
		$body .= sprintf('<h3 style="text-transform:uppercase;padding:0;margin:0px;line-height:24px;">EVENT INFORMATION:</h3>');
		$body .= sprintf('UCP’s Champions in Life Night<br/>Date: FRIDAY, OCTOBER 16th 2015<br/>Address: The Phoenician Resort<br/> 6000 E Camelback rd,<br/> Scottsdale, AZ 85251<br/><br/>');

		$body .= sprintf('If you have any questions feel free to contact: <br/> Veronica De La O <br/> (602) 943-5472 <br/>vdlo@ucpofcentralaz.org <br/><br/>');
		$body .= sprintf('We would be contacting you with sitting information as the date of the event approaches.<br/><br/>Sincerely,');
		$body .= "<p><img src='http://ucpofcentralaz.org/wp-content/uploads/2014/05/UCP_Logo-web.png' alt='logo' /></p>";
		$headers = 'From: UCP of Central Arizona <vdelao@ucpofcentralaz.org>' . "\r\n";
		$check = send_event_mail($to,$subject,$body,$headers);			
		
		//Send to Admin
		$subject = "NEW PURCHASE INDIVIDUAL TICKETS";
		$to = Utils\get_theme_option('event_email_admin');				
		$body = sprintf("Hello Veronica, <br/><br/>");
		$body .= sprintf('<h3 style="text-transform:uppercase;padding:0;margin:0px;line-height:24px;">New ticket(s) have been purchased by:</h3>');	
		$body .= sprintf('Customer: %s %s <br/>', $first_name,$last_name);
		$body .= sprintf('Phone number: %s <br/>', $phoneNumber);
		$body .= sprintf('Email: %s <br/>', $customer_email);
		$body .= sprintf('Address 1: %s <br/>', $address1);
		$body .= sprintf('Address 2: %s <br/>', $address2);
		$body .= sprintf('City/State: %s/%s <br/>', $city,$state);
		$body .= sprintf('Postal Code: %s <br/><br/>', $postcode);
		$body .= sprintf('<h3 style="text-transform:uppercase;padding:0;margin:0px;line-height:24px;">Purchase summary:</h3>');	
		$body .= sprintf('Quantity: %s <br/>', $quantity);
		$body .= sprintf('Amount : $%s <br/>', $price);				
		$body .= sprintf('Card number : %s <br/><br/>', FormatCreditCard($card_number));		
		$body .= 'Thank you!';		
		$headers = 'From: UCP of Central Arizona <'.$_REQUEST['email'].'>' . "\r\n";
		$check = send_event_mail($to,$subject,$body,$headers);			
		//$check = send_event_mail("donaldcody90@gmail.com",$subject,$body);			
	}else{
		$result=array('response'=>'error','message'=>'<p class="error">Error: '.$message.'</p>');	
	}
	echo json_encode($result);
	die;
} 

function FormatCreditCard($cc) {
    // REMOVE EXTRA DATA IF ANY
    $cc = str_replace(array('-', ' '), '', $cc);
    // GET THE CREDIT CARD LENGTH
    $cc_length = strlen($cc);
    $newCreditCard = substr($cc, -4);
    for ($i = $cc_length - 5; $i >= 0; $i--) {
        // ADDS HYPHEN HERE
        if ((($i + 1) - $cc_length) % 4 == 0) {
            $newCreditCard = '-' . $newCreditCard;
        }
        $newCreditCard = $cc[$i] . $newCreditCard;
    }   
    // REPLACE CHARACTERS WITH X EXCEPT LAST FOUR
    for ($i = 0; $i < strlen($newCreditCard) - 4; $i++) {
        if ($newCreditCard[$i] == '-') {
            continue;
        }
        $newCreditCard[$i] = 'X';
    }
    // RETURN THE FINAL FORMATED AND MASKED CREDIT CARD NO
    return $newCreditCard;
}

function send_event_mail($to,$subject,$body,$headers){
	add_filter( 'wp_mail_content_type', __NAMESPACE__ . '\\set_html_content_type' );	
	$sent = wp_mail( $to, $subject, $body,$headers );
	remove_filter( 'wp_mail_content_type', __NAMESPACE__ . '\\set_html_content_type' );
	return $sent;
}

function set_html_content_type() {
	return 'text/html';
}


add_action( 'wp_ajax_get_package', __NAMESPACE__ . '\\get_package' );
add_action( 'wp_ajax_nopriv_get_package', __NAMESPACE__ . '\\get_package' );
function get_package(){
	$id = $_POST['id'];
	$post = get_post($id);
	$taxonomy = 'package-cat';
	$terms = get_the_terms($id,$taxonomy);
	if(!empty($terms)) {
		$term = $terms[0];
		if($term->term_id != 3) {
			//echo sprintf('<h3 class="text-center t-bold package-special-title">%s</h3>',$term->name);		
		}
	}	
	echo sprintf('<h3 class="text-center t-bold">%s</h3>',$post->post_title);
	echo sprintf('<div class="text-center text-price">$%s</div>', get_post_meta($post->ID, 'package_price',true));
	echo sprintf('<div class="entry-content">');
	setup_postdata( $post );
	the_content();
	wp_reset_postdata( $post );
	echo "</div><br/>";
	?>
	<script type="text/javascript">
	jQuery('document').ready(function($){
		var inst_package = $('[data-remodal-id=remodal-package]').remodal();
		var inst_buy = $('[data-remodal-id=remodal-buy]').remodal();

		$('.extend_buy').click(function(){					
			inst_package.close();
			inst_buy.open();			
		});
	});	
	</script>
	<?php	
	die;
}
