<?php
class NBT_Order_Upload_Frontend {
	/**
	 * Class constructor.
	 */
	public function __construct() {
		add_action('wp_enqueue_scripts', array($this, 'embed_style'));

		

		// add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );

		add_action('woocommerce_before_add_to_cart_form', array($this, 'is_single_product') );
		add_filter('woocommerce_cart_item_name', array($this, 'woocommerce_cart_item_name'), 10, 3 );
		add_action( 'woocommerce_thankyou', array($this, 'nbt_woocommerce_payment_complete'), 10, 1 );

		add_action('woocommerce_order_item_meta_end', array($this, 'woocommerce_order_items_table'), 20, 3 );


		add_filter( 'body_class', array($this, 'nbt_body_classes'), 10, 1 );
		add_shortcode( 'nbt_upload', array($this, 'shortcode_ajax_upload'), 10, 1 );
		add_shortcode( 'nbt_order_upload', array($this, 'shortcode_nbt_order_upload'), 10, 1 );

	}

	public function shortcode_nbt_order_upload(){
		global $post;

		$product = wc_get_product($post->ID);

		echo '<input type="hidden" name="add-to-cart" value="'.$product->get_id().'">';

		$this->is_single_product($product);
	}

	public function is_single_product($_product = false){

		global $product, $wpdb;

		if($_product){
			$product = $_product;
		}

		$product_id = $product->get_id();
		$lists_file = @unserialize(WC()->session->get('order_upload'));

		if(get_post_meta($product_id, '_order_upload', true) == 'on'){?>
		<form action="" method="POST" class="ibenic_upload_form" enctype="multipart/form-data">
			<div id="nbt-order-upload">
				<div class="nbt-upload-zone">
					<div class="nbt-oupload-target"><?php echo __('Drop your file(s) here or click to add one!', 'nbt-solutions');?></div>
					<input class="nbt-upload-input" type="file" multiple="">
				</div>
				

				<div class="nbt-oupload-output">
	
					<div class="progress"><div class="progress-bar progress-bar-success progress-bar-striped"></div></div>
					<div class="nbt-oupload-body">
						<?php if(isset($lists_file[$product_id])){
							global $wpdb;
					    	$upload_dir = wp_upload_dir();
					    	$destination_folder = $upload_dir['baseurl'].'/nbt-order-uploads/';
							$lists_file = $lists_file[$product_id];
							foreach ($lists_file as $key => $attach_id) {
								$file = $wpdb->get_row( "SELECT post_title, post_name, post_mime_type FROM {$wpdb->prefix}posts WHERE ID = '".$attach_id."'" );
								if($file){
								$extension = explode('/', $file->post_mime_type);
								$filename = $file->post_name.'.'.$extension[1];
					    		$post_thumbnail_url = $destination_folder.'thumb_'.$filename;
							?>
							<div id="<?php echo $file->post_name;?>" class="nbt-file success">
								<div class="nbt-file-left"><img width="50" src="<?php echo $post_thumbnail_url;?>"></div>
								<div class="nbt-file-right">
									<div class="name"><?php echo $file->post_title;?> <i class="nbt-icon-cancel"></i></div>
									<div class="size"><?php echo NBT_Solutions_Order_Upload::format_size(get_post_meta($attach_id, '_wp_attached_size', true));?></div>
								</div>

							</div>
							<?php
								}
							}

						}?>
					</div>
				</div>

			</div>
		</form>
		<?php
		}
	}

	public function woocommerce_cart_item_name( $item_title, $product, $cart_item_key = null ) {
		global $wpdb;
		$return = $item_title;

		$product_id = $product['product_id'];
		$lists_file = @unserialize(WC()->session->get('order_upload'));
    	$upload_dir = wp_upload_dir();
    	$destination_folder = $upload_dir['baseurl'].'/nbt-order-uploads/';
		if(isset($lists_file[$product_id]) && $lfiles = $lists_file[$product_id]){
			$return .= '<div class="nbt-show-files"><a class="toggle-order-upload">'.wp_kses_data( sprintf( _n( '%d File', '%d Files', count($lfiles), 'nbt-solutions' ), count($lfiles) ) ).' <i class="nbt-icon-down-open"></i></a><ul style="display: none">';
			foreach ($lfiles as $key => $file) {

				$files = $wpdb->get_row( "SELECT post_title, post_name, post_mime_type FROM {$wpdb->prefix}posts WHERE ID = '".$file."'" );
				if($files){
					$extension = explode('/', $files->post_mime_type);
					$filename = $files->post_name.'.'.$extension[1];
					$post_thumbnail_url = $destination_folder.'thumb_'.$filename;


				
					$return .= '<li><div class="left-files"><img src="'.$post_thumbnail_url.'"></div><div class="right-files"><h4>'.$files->post_title.'</h4><p>'.NBT_Solutions_Order_Upload::format_size(get_post_meta($file, '_wp_attached_size', true)).'</p></div></li>';
				}
			}
			$return .= '</ul></div>';
		}

		if(get_post_meta($product_id, '_order_upload', true) == 'on' && NBT_Solutions_Order_Upload::is_osc()){
			$return .= '<div class="nbt-ou-fast"><a href="'.get_permalink(NBT_Solutions_Order_Upload::is_osc()).'?wc-product='.$product_id.'" class="btn btn-upload-fast" data-product_id="'.$product_id.'">'.__('Upload Files', 'nbt-solutions').'</a></div>';
		}
		
		return $return;
	}

	public function nbt_woocommerce_payment_complete($order_id){
		global $wpdb;

		$lists_file = @unserialize(WC()->session->get('order_upload'));
		if(!empty($lists_file)){
			update_post_meta($order_id, 'order_upload', $lists_file);
		}
		

		WC()->session->set( 'order_upload', null );
		$get_customer_id = WC()->session->get_customer_id();
		$wpdb->delete( $wpdb->prefix.'nbt_order_upload', array( 'ou_key' => $get_customer_id ) );
		error_log( "Payment has been received for order $order_id" );
	}

	public function woocommerce_order_items_table($item_id, $item, $order){
		global $wpdb;

		$return = '';
		$lists_file = get_post_meta($order->get_id(), 'order_upload', true);

    	$upload_dir = wp_upload_dir();
    	$destination_folder = $upload_dir['baseurl'].'/nbt-order-uploads/';

		foreach ( $order->get_items() as $product_info ) {
			$product_id = ( int ) apply_filters ( 'woocommerce_add_to_cart_product_id', $product_info ['product_id'] );

			
			if($product_info->get_id() == $item_id && isset($lists_file[$product_id]) && get_post_meta($product_id, '_order_upload', true) == 'on'){
				
				$lfiles = $lists_file[$product_id];

				$return .= '<div class="nbt-show-files"><a class="toggle-order-upload">'.wp_kses_data( sprintf( _n( '%d File', '%d Files', count($lfiles), 'nbt-solutions' ), count($lfiles) ) ).' <i class="nbt-icon-down-open"></i></a><ul style="display: none">';
				foreach ($lfiles as $key => $file) {

					$files = $wpdb->get_row( "SELECT post_title, post_name, post_mime_type FROM {$wpdb->prefix}posts WHERE ID = '".$file."'" );
					if($files){
						$extension = explode('/', $files->post_mime_type);
						$filename = $files->post_name.'.'.$extension[1];
						$post_thumbnail_url = $destination_folder.'thumb_'.$filename;


					
						$return .= '<li><div class="left-files"><img src="'.$post_thumbnail_url.'"></div><div class="right-files"><h4>'.$files->post_title.'</h4><p>'.NBT_Solutions_Order_Upload::format_size(get_post_meta($file, '_wp_attached_size', true)).'</p></div></li>';
					}
				}
				$return .= '</ul></div>';
			}

		}
		echo $return;
	}

	// public function woocommerce_order_details_after_customer_details($order){
	// 	WC()->session->set( 'order_upload', null );
	// }

	public function nbt_body_classes( $classes ) {
		global $post;

		if(isset($post) && get_post_meta($post->ID, '_order_upload', true) == 'on'){
			$classes[] = 'has-order-upload';
		}
	     
	    return $classes;  
	}

	public function shortcode_ajax_upload(){
		if(isset($_REQUEST['wc-product']) && is_numeric($_REQUEST['wc-product'])){
			$product_id = $_REQUEST['wc-product'];
			$product = wc_get_product($product_id);
			?>
			<div id="nbt-order-page">
				<?php $this->is_single_product($product);?>
				<div class="nbtou-forward">
					<?php if( !class_exists('NBT_Solutions_One_Step_Checkout') ){?>
					<a class="btn btn-ou-cart" href="<?php echo wc_get_cart_url();?>"><?php echo __('Cart', 'nbt-solutions');?></a>
					<?php }?>
					<a class="btn btn-ou-checkout" href="<?php echo wc_get_checkout_url();?>"><?php echo __('Checkout', 'nbt-solutions');?></a>
					<input type="hidden" name="add-to-cart" value="<?php echo $product_id;?>" />
				</div>
			</div>

			<?php
		}
	}
	/**
	 * Enqueue scripts and stylesheets
	 */
	public function embed_style() {

		if( ! defined('PREFIX_NBT_SOL')){
			wp_enqueue_style( 'order-upload-frontend', NBT_OUP_URL .'assets/css/frontend.css', array(), '20160615' );
			wp_enqueue_style( 'nbt-fonts-frontend', NBT_OUP_URL .'assets/css/nbt-fonts.css', array(), '20160615' );
		}

		
		wp_enqueue_script( 'order-upload-md5', NBT_OUP_URL . 'assets/js/md5.min.js', array( 'jquery' ), time(), true );
		if( ! defined('PREFIX_NBT_SOL')){
			wp_enqueue_script( 'order-upload-frontend', NBT_OUP_URL . 'assets/js/frontend.js', array( 'jquery' ), time(), true );
			wp_localize_script( 'order-upload-frontend', 'nbtou', array(
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'customer_id' => WC()->session->get_customer_id()
			));
		}
	}
}
new NBT_Order_Upload_Frontend();