<?php

namespace wp_opieka_globkurier;

class GlobKurierDocuments extends GlobKurier{
	
	public function tracking( $params ){
		$function = 'order/tracking';
		$method   = 'GET';
		
		$token = $this->api()->getToken();
		
		//orderNumber
		//format : A4 ZEBRA_PRINTER
		
		$response = $this->api()->getResponse( $function, $token, $params, $method );
		
		if( $response[ 'code' ] == 200 ){
			return $response[ 'data' ];
		} else{
			die( 'ERROR' );
		}
		
	}
	
	public function getOrderLabelPdf($hash)
	{
		$curl = curl_init();
		
		curl_setopt_array($curl, [
			CURLOPT_URL            => $this->api()->getOrderLabelUrl($hash),
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING       => '',
			CURLOPT_MAXREDIRS      => 10,
			CURLOPT_TIMEOUT        => 0,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST  => 'GET',
			CURLOPT_HTTPHEADER     => [
				'x-auth-token: '.$this->api()->getToken()
			],
		]);
		
		$response = curl_exec($curl);
		
		curl_close($curl);
		return $response;
	}
	
	public function getOrderProtocolPdf($hash)
	{
		$curl = curl_init();
		
		curl_setopt_array($curl, [
			CURLOPT_URL            => $this->api()->getOrderProtocolUrl($hash),
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING       => '',
			CURLOPT_MAXREDIRS      => 10,
			CURLOPT_TIMEOUT        => 0,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST  => 'GET',
			CURLOPT_HTTPHEADER     => [
				'x-auth-token: '.$this->api()->getToken()
			],
		]);
		
		$response = curl_exec($curl);
		
		curl_close($curl);
		return $response;
	}
	
	public function labels( $params ){
		$function = 'order/labels';
		$method   = 'GET';
		
		$token = $this->api()->getToken();
		
		$url = $this->api()->getResponse( $function, $token, $params, $method, $onlyUrl = TRUE );
		
		return ( $url );
	}
	
	public function hasLabels( $params ){
		$function = 'order/labels';
		$method   = 'GET';
		
		$token = $this->api()->getToken();
		
		$response = $this->api()->getResponse( $function, $token, $params, $method );
		
		return $response;
	}
	
	public function protocols( $params ){
		$function = 'order/protocol';
		$method   = 'GET';
		
		$token = $this->api()->getToken();
		
		//orderHashes
		
		$response = $this->api()->getResponse( $function, $token, $params, $method );
		
		if( $response[ 'code' ] == 200 ){
			wp_send_json_success( $response[ 'data' ] );
		} else{
			$errors = [];
			foreach ($response['data']['fields'] ?? [] as $key=>$error) {
				$errors []= $error;
			}
			
			wp_send_json_error( $errors );
		}
	}
	
	public function get( $params ){
		global $wpdb;
		global $globKurier;
		
		$start  = $params[ 'start' ] ?? 0;
		$length = $params[ 'length' ] ?? 10;
		
		$mataName = apply_filters( 'globkurier_wc_order_meta_name', 'globkurier_orders' );
		
		$order = [
			'by'   => 'post_id',
			'mode' => 'desc',
		];
		
		$where    = " WHERE meta_key = '{$mataName}'";
		$orderBy  = " ORDER BY {$order['by']} {$order['mode']}";
		$paginate = " LIMIT {$length} OFFSET {$start}";
		
		if( $params[ 'search' ] && $params[ 'search' ][ 'value' ] ){
			$searches = esc_sql( $params[ 'search' ][ 'value' ] );
			$searches = mb_split( ' ', $searches );
			$where    .= ' AND ( 1=1 ';
			foreach( $searches as $search ){
				$where .= " AND `meta_value` like '%{$search}%'";
			}
			$where .= ')';
		}
		
		$sql = "SELECT `meta_value`, `post_id` FROM `{$wpdb->postmeta}` {$where}";
		
		$limitedSql = $sql . $orderBy . $paginate;
		
		$s_orders     = $wpdb->get_results( $limitedSql, ARRAY_A );
		$total_orders = $wpdb->get_var( "SELECT count( `post_id` ) as `total` FROM `{$wpdb->postmeta}` {$where}" );
		
		$orders = [];
		
		foreach( $s_orders as $key => $_order ){
			$data = maybe_unserialize( maybe_unserialize( $_order[ 'meta_value' ] ) );
			
			$wcOrderId = $_order[ 'post_id' ];
			$wcOrder   = wc_get_order( $wcOrderId );
			
			$order = [];
			
			$order[ 'check_btn' ]             = TRUE;
			$order[ 'number' ]                = $data[ 'number' ];
			$order[ 'timestamp' ]             = $data[ 'date' ];
			$order[ 'date' ]                  = date( 'd.m.Y', $data[ 'date' ] );
			$order[ 'receiver_address_name' ] = $data[ 'data' ][ 'receiverAddress' ][ 'name' ];
			$order[ 'content' ]               = $data[ 'data' ][ 'content' ];
			$order[ 'shipment_weight' ]       = $data[ 'data' ][ 'shipment' ][ 'weight' ];
			$order[ 'carrier_name' ]          = $data[ 'carrier' ][ 'name' ];
			$order[ 'cod_value' ]             = $data[ 'cod' ][ 'value' ];
			$order[ 'payment_name' ]          = $data[ 'payment_name' ];
			$order[ 'price_net' ]             = number_format( round( $data[ 'price' ][ 'net' ], 2 ), 2 );
			$order[ 'get_status_btn' ]        = '';
			$order[ 'wc_order_link' ]         = $wcOrder ? $wcOrder->get_edit_order_url() : NULL;
			$order[ 'wc_order_id' ]           = $wcOrderId;
			$order[ 'hash' ]                  = $data[ 'hash' ];
//			$order[ 'order_label_url' ]       = $globKurier->api()->getOrderLabelUrl( $data[ 'hash' ] );
			$order[ 'order_label_url' ]       = $globKurier->api()->getOrderLabelPdfUrl( $data[ 'hash' ] );
			$order[ 'order_track_url' ]       = $globKurier->api()->getOrderTrackUrl( $data[ 'number' ] );
			$order[ 'hasLabel' ]              = FALSE;
			
			$orders[] = $order;
		}
		
		usort( $orders, function( $item1, $item2 ){
			return $item2[ 'timestamp' ] <=> $item1[ 'timestamp' ];
		} );
		
		$hashes = wp_list_pluck( $orders, 'hash' );
		
		$getAllLabels = $this->hasLabels( [
			'orderHashes' => $hashes
		] );
		
		//wszystkie zamowienia maja etykiety
		if( $getAllLabels[ 'code' ] == 200 ){
			foreach( $orders as &$order ){
				$order[ 'hasLabel' ] = TRUE;
			}
		} else if( isset( $getAllLabels[ 'data' ], $getAllLabels[ 'data' ][ 'fields' ] ) ){
			//ktores zamowienie nie ma etykiety
			$noLabels = $getAllLabels[ 'data' ][ 'fields' ];
			foreach( $orders as $key => &$order ){
				$apiOrderKey = "orderHashes[{$key}]";

				if( ! array_key_exists( $apiOrderKey, $noLabels ) ){
					$order[ 'hasLabel' ] = TRUE;
				}
			}
		}

		$json_data = [
			'draw'            => $params[ 'draw' ],
			'recordsTotal'    => $total_orders,
//			'recordsFiltered' => count($orders),
			'recordsFiltered' => $total_orders,
			'data'            => $orders
		];
		
		echo json_encode( $json_data );
		die;
	}
	
	public function getOrder( $params ){
		
		$function = 'order';
		$method   = 'GET';
		
		$token = $this->api()->getToken();
		
		$response = $this->api()->getResponse( $function, $token, $params, $method );
		
		return $response;
	}
	
}