<?php
class NBT_Order_Upload_Ajax{

	protected static $initialized = false;
	
    /**
     * Initialize functions.
     *
     * @return  void
     */
    public static function initialize() {
        if ( self::$initialized ) {
            return;
        }

	    self::admin_hooks();
        self::$initialized = true;
    }


    public static function admin_hooks(){
		add_action( 'wp_ajax_nopriv_nbt_order_upload', array( __CLASS__, 'nbt_order_upload') );
		add_action( 'wp_ajax_nbt_order_upload', array( __CLASS__, 'nbt_order_upload') );

		add_action( 'wp_ajax_nopriv_nbt_ou_remove', array( __CLASS__, 'nbt_ou_remove') );
		add_action( 'wp_ajax_nbt_ou_remove', array( __CLASS__, 'nbt_ou_remove') );

		add_action( 'wp_ajax_nopriv_nbtou_remove_files', array( __CLASS__, 'nbtou_remove_files') );
		add_action( 'wp_ajax_nbtou_remove_files', array(  __CLASS__, 'nbtou_remove_files') );

		add_action( 'wp_ajax_nopriv_submit_files', array( __CLASS__, 'nbtou_submit_files') );
		add_action( 'wp_ajax_submit_files', array(  __CLASS__, 'nbtou_submit_files') );
    }

    public function nbt_ou_remove(){
    	global $wpdb;
    	$upload_dir = wp_upload_dir();
    	$destination_folder = $upload_dir['basedir'].'/nbt-order-uploads/';
    	$customer_id = WC()->session->get_customer_id();

		$file_id = $_REQUEST['file'];
		$product_id = absint($_REQUEST['product_id'] );

		$check_attachments = $wpdb->get_var( "SELECT ID FROM {$wpdb->prefix}posts WHERE post_name LIKE '%".$file_id."%' AND comment_count = 1 AND post_type = 'attachment'" );
		if($check_attachments){
			$rs = $wpdb->get_row( "SELECT ou_id, ou_value FROM {$wpdb->prefix}nbt_order_upload WHERE ou_key = '".$customer_id."'" );
			$order_upload = @unserialize($rs->ou_value);
			if($order_upload && isset($order_upload[$product_id])){
				
				if(($key = array_search($check_attachments, $order_upload[$product_id])) !== false) {
					$attach_id = $order_upload[$product_id][$key];
					$file = $wpdb->get_row( "SELECT post_name, post_mime_type FROM {$wpdb->prefix}posts WHERE ID = '".$attach_id."'" );

					$extension = explode('/', $file->post_mime_type);

					$filename = $file->post_name.'.'.$extension[1];
					
		    	
		    		

		    		$post_url = $destination_folder.$filename;
		    		$post_thumbnail_url = $destination_folder.'thumb_'.$filename;

		    		unlink($post_url);
		    		unlink($post_thumbnail_url);

		    		wp_delete_post($attach_id);

				    unset($order_upload[$product_id][$key]);

					$wpdb->update( 
						$wpdb->prefix.'nbt_order_upload', 
						array( 
							'ou_value' => serialize($order_upload),	// string
						), 
						array( 'ou_id' => $rs->ou_id ), 
						array( 
							'%s'	// value2
						), 
						array( '%s' ) 
					);
				}
			}

		}
		WC()->session->set('order_upload', serialize($order_upload));

		$count_files = 0;
		if($order_upload){
			foreach ($order_upload as $key => $value) {
				$count_files += count($value);
			}
		}

		update_post_meta($order_id, 'order_upload', $order_upload);

		$json['complete'] = true;
		$json['file_id'] = $file_id;
		$json['count'] = $count_files;
		echo wp_json_encode($json, TRUE);

    	wp_die();
    }


    public static function nbt_order_upload(){
    	global $wpdb;

		$usingUploader = 3;
		$fileErrors = array(
			0 => "There is no error, the file uploaded with success",
			1 => "The uploaded file exceeds the upload_max_files in server settings",
			2 => "The uploaded file exceeds the MAX_FILE_SIZE from html form",
			3 => "The uploaded file uploaded only partially",
			4 => "No file was uploaded",
			6 => "Missing a temporary folder",
			7 => "Failed to write file to disk",
			8 => "A PHP extension stoped file to upload" );
		$posted_data =  isset( $_POST ) ? $_POST : array();
		$file_data = isset( $_FILES ) ? $_FILES : array();
		$data = array_merge( $posted_data, $file_data );
		$response = array();
		$get_customer_id = WC()->session->get_customer_id();
		$response['customer_id'] = $get_customer_id;
		$limit_filesize = 2097152;
		$product_id = absint( $_REQUEST['product_id'] );


		// if( $usingUploader == 1 ) {
		// 	$uploaded_file = wp_handle_upload( $data['ibenic_file_upload'], array( 'test_form' => false ) );
		// 	if( $uploaded_file && ! isset( $uploaded_file['error'] ) ) {
		// 		$response['response'] = "SUCCESS";
		// 		$response['filename'] = basename( $uploaded_file['url'] );
		// 		$response['url'] = $uploaded_file['url'];
		// 		$response['type'] = $uploaded_file['type'];
		// 	} else {
		// 		$response['response'] = "ERROR";
		// 		$response['error'] = $uploaded_file['error'];
		// 	}
		// } elseif ( $usingUploader == 2) {
		// 	$attachment_id = media_handle_upload( 'ibenic_file_upload', 0 );
			
		// 	if ( is_wp_error( $attachment_id ) ) { 
		// 		$response['response'] = "ERROR";
		// 		$response['error'] = $fileErrors[ $data['ibenic_file_upload']['error'] ];
		// 	} else {
		// 		$fullsize_path = get_attached_file( $attachment_id );
		// 		$pathinfo = pathinfo( $fullsize_path );
		// 		$url = wp_get_attachment_url( $attachment_id );
		// 		$response['response'] = "SUCCESS";
		// 		$response['filename'] = $pathinfo['filename'];
		// 		$response['url'] = $url;
		// 		$type = $pathinfo['extension'];
		// 		if( $type == "jpeg"
		// 		|| $type == "jpg"
		// 		|| $type == "png"
		// 		|| $type == "gif" ) {
		// 			$type = "image/" . $type;
		// 		}
		// 		$response['type'] = $type;
		// 	}
		// } else {
			$upload_dir = wp_upload_dir();
			$upload_path = $upload_dir["basedir"]."/nbt-order-uploads/";
			$upload_url = $upload_dir["baseurl"]."/nbt-order-uploads/";
			if(!file_exists($upload_path)){
				mkdir($upload_path);
			}

			$image_allow = array('png', 'jpg', 'jpeg', 'gif', 'svg');

			$new_attachment = array();
			foreach ($data['nbt_files']['name'] as $key => $file_name) {
				$file_type = $data['nbt_files']['name'][$key];
				$file_tmp_name = $data['nbt_files']['tmp_name'][$key];
				$file_error = $data['nbt_files']['error'][$key];
				$file_size = $data['nbt_files']['size'][$key];

				$file_extension = pathinfo( $upload_path . "/" . $file_name );
				$file_rename = md5($get_customer_id.$file_size);
				$file_full_rename = $file_rename.'.'.$file_extension['extension'];

				$response_id = $file_rename;
				/* Check file exists in database */
				$check_attachments = $wpdb->get_var( "SELECT * FROM {$wpdb->prefix}posts WHERE post_name LIKE '%".$file_rename."%' AND comment_count = 1 AND post_type = 'attachment'" );
				if($check_attachments){
					$attach_id = $check_attachments;
					$complete = true;
					$response["response"][$response_id] = "SUCCESS";
				}else{
					if($file_error > 0){
						$response["response"][$response_id] = "ERROR";
			            $response["error"][$response_id] = $file_error[ $file_error ];
					} else {
						if(file_exists($upload_path . "/" . $file_full_rename)){
							$response["response"][$response_id] = "ERROR";
					        $response["error"][$response_id] = "File already exists.";
						} else {
							
							if($file_size <= $limit_filesize){
								if( move_uploaded_file( $file_tmp_name, $upload_path . "/" . $file_full_rename ) ){
									$response["response"][$response_id] = "SUCCESS";

				            		$u_path = str_replace('\\', '/', $upload_path . $file_full_rename);
				            		$u_path_gen = str_replace('\\', '/', $upload_path . 'thumb_'.$file_full_rename);
				            		$response["url"][$response_id] =  $upload_url . 'thumb_'.$file_full_rename;

								
						            		
						            if( $file_extension && isset( $file_extension["extension"] ) ){
						            	$type = $file_extension["extension"];
						            	if( $type == "jpeg" || $type == "jpg" || $type == "png" || $type == "gif" ) {
											$type = "image/" . $type;
										}
						            	$response["type"][$response_id] = $type;
						            }
						            self::make_thumb($u_path, $u_path_gen, 100, $type);

									$attachment = array(
										'post_mime_type' => $type,
										'post_title' => $file_name,
										'post_content' => '',
										'post_status' => 'inherit',
										'post_name' => $file_rename,
										'guid' => $response["url"]
									 );
									$attach_id = wp_insert_attachment( $attachment, $file_rename, 289 );
									require_once(ABSPATH . 'wp-admin/includes/image.php');
									$attach_data = wp_generate_attachment_metadata( $attach_id, $file_rename );
									wp_update_attachment_metadata( $attach_id, $attach_data );

									update_post_meta($attach_id, 'attachment_order_upload', true);
									update_post_meta($attach_id, '_wp_attached_size', $file_size);

									$wpdb->update( 
										$wpdb->posts, 
										array( 
											'comment_count' => '1',	// string
										), 
										array( 'ID' => $attach_id ), 
										array( 
											'%d'	// value2
										), 
										array( '%d' ) 
									);

									$complete = true;

									
								}else {
									$response["response"][$response_id] = "ERROR";
									$response["error"][$response_id] = "Upload Failed.";
						        }

							}else{
			            		$response["response"][$response_id] = "ERROR";
			            		$response["error"][$response_id] = "File is too large. Max file size is 2 MB.";
							}
						}
					}
				}
				$new_attachment[] = $attach_id;
			}




		if(isset($complete)){

			if ( $order_upload = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}nbt_order_upload WHERE ou_key = '".$get_customer_id."'" ) ) {
				$value_order = @unserialize($order_upload->ou_value);
				if(isset($value_order[$product_id])){
					if(!in_array($attach_id, $value_order[$product_id])){
						$value_order[$product_id] = array_merge($value_order[$product_id], $new_attachment);
					}
				}else{
					$value_order[$product_id] = $new_attachment;
				}

				$wpdb->update( 
					$wpdb->prefix.'nbt_order_upload', 
					array( 
						'ou_value' => serialize($value_order),	// string
						'ou_expiry' => time()	// integer (number) 
					), 
					array( 'ou_key' => $order_upload->ou_key ), 
					array( 
						'%s',	// value1
						'%d'	// value2
					), 
					array( '%d' ) 
				);
	
			}else{
				$value_order = array(
					$product_id => $new_attachment
				);
				$sql = "( '" . $get_customer_id . "', '". serialize($value_order)."', '". time() ."' )";
		

				$wpdb->query( "
					INSERT INTO {$wpdb->prefix}nbt_order_upload ( ou_key, ou_value, ou_expiry ) VALUES $sql;
					" );
			}
			WC()->session->set('order_upload', serialize($value_order));


		}
    	echo wp_json_encode($response);
    	wp_die();
    }

	public static function make_thumb($src, $dest, $desired_width, $ext) {
		switch ( $ext ) 
		{
		  case 'image/gif': $source_image = imagecreatefromgif($src); break;
		  case 'image/jpeg': $source_image = imagecreatefromjpeg($src); break;
		  case 'image/jpg': $source_image = imagecreatefromjpeg($src); break;
		  case 'image/png': $source_image = imagecreatefrompng($src); break;
		  default: trigger_error('Unsupported filetype!', E_USER_WARNING);  break;
		}

		/* read the source image */
		$width = imagesx($source_image);
		$height = imagesy($source_image);
		
		/* find the "desired height" of this thumbnail, relative to the desired width  */
		$desired_height = floor($height * ($desired_width / $width));
		
		/* create a new, "virtual" image */
		$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
		
		/* copy source image at a resized size */
		imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
		
		/* create the physical thumbnail image to its destination */
		imagejpeg($virtual_image, $dest);
	}
	public static function nbtou_remove_files(){

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

		$order_id = absint($_REQUEST['order_id'] );
		$file_id = absint($_REQUEST['file_number'] );
		$product_id = absint($_REQUEST['product_id'] );

		$order_upload = get_post_meta($order_id, 'order_upload', true);

		if(isset($order_upload[$product_id])){
			if(($key = array_search($file_id, $order_upload[$product_id])) !== false) {
				$attach_id = $order_upload[$product_id][$key];
	    		$path_file = wp_get_attachment_url($attach_id);
	    		$basename = basename($path_file);
	    		$post_url = $destination_folder.$basename;
	    		$post_thumbnail_url = $destination_folder.'thumb_'.$basename;

	    		unlink($post_url);
	    		unlink($post_thumbnail_url);

	    		wp_delete_post($attach_id);

			    unset($order_upload[$product_id][$key]);
			}
		}
		$count_files = 0;
		if($order_upload){
			foreach ($order_upload as $key => $value) {
				$count_files += count($value);
			}

		}

		update_post_meta($order_id, 'order_upload', $order_upload);

		$order_upload = get_post_meta($order_id, 'order_upload', true);
		
		$json['complete'] = true;
		$json['order_id'] = md5($file_id);
		$json['file_id'] = $file_id;
		$json['count'] = $count_files;

		echo wp_json_encode($json, TRUE);
		wp_die();
	}

    public function nbtou_submit_files(){
    	$order_id = absint($_REQUEST['order_id']);
    	$ans = $_REQUEST['ans'];

    	update_post_meta($order_id, '_order_upload_status', $ans);

    	$json['complete'] = true;

    	echo wp_json_encode($json, TRUE);

    	wp_die();
    }
}