<?php    
defined('BASEPATH') OR exit('No direct script access allowed');
error_reporting(0);
class Developer_api extends CI_Controller { 

	public function __construct()
	{
		parent::__construct();
		header('X-Robots-Tag: noindex');
	}

	function jewelry_upload() {
		exit;
		$field['from_date'] = '01/01/2023';
		$field['to_date'] = '01/09/2023';

		$jewelryRecord = $this->getJewelry($field);
		if(empty($jewelryRecord)) {
			exit;
		}
		//--------------------------------------------------------------------------
		
		foreach ($jewelryRecord as $row) {
			$sku = $row['sku'];
			$checkQuery = $this->db->query("select id from curl_buying_report where tran_no = '$sku' ")->result();
			if(!empty($checkQuery)) {
				continue;
			}

			$recordJson = $this->jewelryJson($row);
			//print_ex($recordJson);

			$curl = curl_init();
			curl_setopt_array($curl, array(
			  CURLOPT_URL => 'https://api.rdidiamonds.com/v2/listener/mdj/product/update',
			  CURLOPT_RETURNTRANSFER => true,
			  CURLOPT_ENCODING => "",
			  CURLOPT_MAXREDIRS => 10,
			  CURLOPT_TIMEOUT => 30,
			  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			  CURLOPT_CUSTOMREQUEST => "POST",
			  CURLOPT_POSTFIELDS => $recordJson,
			  CURLOPT_HTTPHEADER => array(
			    'Authorization: C7wdteWCqr9EBwNu',
			    'Content-Type: application/json'
			  ),
			));
			$response = curl_exec($curl);
			$err = curl_error($curl);
			curl_close($curl);
			//--------------------------------------------------------------------------
			$dataIn = array(
				'response' => $response,
				'error' => $err,
				'added_at' => date('Y-m-d h:i'),
				'report_date' => date('Y-m-d h:i'),
				'data' => $recordJson,
				'tran_no' => $row['sku'] ?? '1',
				'type' => 'jewelry_upload',
			);
			$this->common_model->insertData('curl_buying_report', $dataIn);

		}
		
	}

	function jewelry_update() {
		//Trans_Date
		//--------------------------------------------------------------------------
		// $field['from_date'] = '01/31/2023';
		// $field['to_date'] =  '01/31/2023';
		$field['from_date'] = date("m/d/Y", strtotime("- 1 day"));
		$field['to_date'] = date("m/d/Y", strtotime("+ 1 day"));		

		$jewelryRecord = $this->getJewelry($field);
		if(empty($jewelryRecord)) {
			exit;
		}
		//print_ex($jewelryRecord);
		//--------------------------------------------------------------------------
		foreach ($jewelryRecord as $row) {
			$sku = $row['sku'];
			$product_status = $row['Product_Status'];
			$report_date = $row['Trans_Date'];

			$where = " tran_no = '$sku' and product_status = '$product_status' and report_date = '$report_date'";
			$checkQuery = $this->db->query("select id from curl_jewelry_upload where $where ")->result();
			if(!empty($checkQuery)) {
				continue;
			}

			$recordJson = $this->jewelryJson($row);

			$curl = curl_init();
			curl_setopt_array($curl, array(
			  CURLOPT_URL => 'https://api.rdidiamonds.com/v2/listener/mdj/product/update',
			  CURLOPT_RETURNTRANSFER => true,
			  CURLOPT_ENCODING => "",
			  CURLOPT_MAXREDIRS => 10,
			  CURLOPT_TIMEOUT => 30,
			  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			  CURLOPT_CUSTOMREQUEST => "POST",
			  CURLOPT_POSTFIELDS => $recordJson,
			  CURLOPT_HTTPHEADER => array(
			    'Authorization: C7wdteWCqr9EBwNu',
			    'Content-Type: application/json'
			  ),
			));
			$response = curl_exec($curl);
			$err = curl_error($curl);
			curl_close($curl);
			//--------------------------------------------------------------------------
			if(!empty($sku)) {
				$this->db->delete('curl_jewelry_upload', ['tran_no' => $row['sku']]);
			}

			$dataIn = array(
				'response' => $response,
				'error' => $err,
				'added_at' => date('Y-m-d h:i'),
				'report_date' => $row['Trans_Date'],
				'item_date' => $row['Item_Date'],
				'data' => $recordJson,
				'tran_no' => $row['sku'] ?? '1',
				'product_status' => $row['Product_Status'] ?? '0',
				'type' => 'jewelry_update',
			);
			$this->db->insert('curl_jewelry_upload', $dataIn);

		}
		
	}

	function jewelry_update_new() {
		//Item_Date
		//--------------------------------------------------------------------------
		// $field['from_item_date'] = '26/01/2023';
		// $field['to_item_date'] = '31/01/2023';
		$field['from_item_date'] = date("d/m/Y");
		$field['to_item_date'] = date("d/m/Y", strtotime("+ 1 day"));
		
		$jewelryRecord = $this->getJewelry($field);
		if(empty($jewelryRecord)) {
			exit;
		}		
		//--------------------------------------------------------------------------
		foreach ($jewelryRecord as $row) {
			
			$sku = $row['sku'];
			$item_date = $row['Item_Date'];
			$where = " tran_no = '$sku' and item_date = '$item_date'";
			
			$checkQuery = $this->db->query("select id from curl_jewelry_upload where $where ")->result();
			if(!empty($checkQuery)) {
				continue;
			}

			$recordJson = $this->jewelryJson($row);

			$curl = curl_init();
			curl_setopt_array($curl, array(
			  CURLOPT_URL => 'https://api.rdidiamonds.com/v2/listener/mdj/product/update',
			  CURLOPT_RETURNTRANSFER => true,
			  CURLOPT_ENCODING => "",
			  CURLOPT_MAXREDIRS => 10,
			  CURLOPT_TIMEOUT => 30,
			  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			  CURLOPT_CUSTOMREQUEST => "POST",
			  CURLOPT_POSTFIELDS => $recordJson,
			  CURLOPT_HTTPHEADER => array(
			    'Authorization: C7wdteWCqr9EBwNu',
			    'Content-Type: application/json'
			  ),
			));
			$response = curl_exec($curl);
			$err = curl_error($curl);
			curl_close($curl);
			//--------------------------------------------------------------------------
			$this->db->delete('curl_jewelry_upload', ['tran_no' => $row['sku']]);

			$dataIn = array(
				'response' => $response,
				'error' => $err,
				'added_at' => date('Y-m-d h:i'),
				'report_date' => $row['Trans_Date'],
				'item_date' => $row['Item_Date'],
				'data' => $recordJson,
				'tran_no' => $row['sku'] ?? '1',
				'product_status' => $row['Product_Status'] ?? '0',
				'type' => 'jewelry_update_new',
			);
			$this->db->insert('curl_jewelry_upload', $dataIn);

		}
		
	}

	private function jewelryJson($row) {

		$body = '<p>';
		$body .= (hasValue($row['Jewelry_Type'])) ? 'Jewelry Type : '.$row['Jewelry_Type'] : '';
		$body .= (hasValue($row['Jewelry_Style'])) ? '<br>Jewelry Style : '.$row['Jewelry_Style'] : '';
		$body .= (hasValue($row['Metal_Type'])) ? '<br>Metal Type : '.$row['Metal_Type'] : '';
		$body .= (hasValue($row['Metal_Wt'])) ? '<br>Metal Weight : '.$row['Metal_Wt'].' g' : '';
		$body .= (hasValue($row['Ring_Size'])) ? '<br>Ring Size : '.$row['Ring_Size'] : '';
		$body .= (hasValue($row['BRAND'])) ? '<br>Brand : '.$row['BRAND'] : '';
		$body .= (hasValue($row['Length'])) ? '<br>Measurement : '.$row['Length'].' inches' : '';

		$body .= (hasValue($row['Center_Stone_Type'])) ? '<br>Center Stone : Stone Type : '.$row['Center_Stone_Type'] : '';
		$body .= (hasValue($row['Center_Shape'])) ? '<br>Center Stone : Shape : '.$row['Center_Shape'] : '';
		$body .= (hasValue($row['Center_Wt'])) ? '<br>Center Stone : Stone Weight : '.$row['Center_Wt'] : '';
		$body .= (hasValue($row['Center_Quantity'])) ? '<br>Center Stone : Quantity : '.$row['Center_Quantity'] : '';
		$body .= (hasValue($row['Center_Color'])) ? '<br>Center Stone : Color : '.$row['Center_Color'] : '';
		$body .= (hasValue($row['Center_Clarity'])) ? '<br>Center Stone : Clarity : '.$row['Center_Clarity'] : '';

		for ($i=1; $i < 6; $i++) { 

            $Side_Stone_Type = 'Side_Stone_Type'.$i;
            $Side_Shape = 'Side_Shape'.$i;
            $Side_Color = 'Side_Color'.$i;
            $Side_Clarity = 'Side_Clarity'.$i;
            $Side_Wt = 'Side_Wt'.$i;
            $Side_Quantity = 'Side_Quantity'.$i;

			$body .= (hasValue($row[$Side_Stone_Type])) ? '<br>Side Stone '.$i.' : Stone Type : '.$row[$Side_Stone_Type] : '';
			$body .= (hasValue($row[$Side_Shape])) ? '<br>Side Stone '.$i.' : Shape : '.$row[$Side_Shape] : '';
			$body .= (hasValue($row[$Side_Wt])) ? '<br>Side Stone '.$i.' : Stone Weight : '.$row[$Side_Wt] : '';
			$body .= (hasValue($row[$Side_Quantity])) ? '<br>Side Stone '.$i.' : Quantity : '.$row[$Side_Quantity] : '';
			$body .= (hasValue($row[$Side_Color])) ? '<br>Side Stone '.$i.' : Color : '.$row[$Side_Color] : '';
			$body .= (hasValue($row[$Side_Clarity])) ? '<br>Side Stone '.$i.' : Clarity : '.$row[$Side_Clarity] : '';
		}

		$body .= '</p>';

		$data = [			
			    'sku' => $row['sku'],
			    'barcode' => $row['Barcode'],
			    'body' => $body,
			    'retail_price' => $row['Retail_Price'],
			    'wholesale_price' => $row['Wholesale_Price'],
			    'compare_at_price' => $row['Compare_at_Price'],
			    'cost_per_item' => $row['Cost_Per_Item'],
			    'custom_product_type' => $row['Custom_Product_Type'],
			    'fulfillment_service' => $row['Fulfillment_Service'],
			    'grams' => $row['Grams'],
			    'handle' => $row['Handle'],
			    'inventory_policy' => $row['Inventory_Policy'],
			    'inventory_qty' => $row['Inventory_Qty'],
			    'inventory_tracker' => $row['Inventory_Tracker'],
			    'product_status' => $row['Product_Status'],
			    'published' => $row['Published'],
			    'requires_shipping' => $row['Requires_Shipping'],
			    'seo_description' => $row['Seo_Description'],
			    'seo_title' => $row['Seo_Title'],
			    'taxable' => $row['Taxable'],
			    'title' => $row['Title'],
		];

		return json_encode($data);
	}

	private function getJewelry($field = []) {
		$record = [];
		$token = $this->get_token();

		$curl = curl_init();
		curl_setopt_array($curl, array(
		  CURLOPT_URL => APIURL.'/jewelry-list',
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => "",
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 30,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => "POST",
		  CURLOPT_POSTFIELDS => http_build_query($field),
		  CURLOPT_HTTPHEADER => array(
		    "Accept: */*",
		    "Authorization: Bearer ".$token			    
		  ),
		));
		$response = curl_exec($curl);

		$err = curl_error($curl);
		curl_close($curl);
		if (empty($err)){		
		  $response = json_decode($response, true);
		  $record = $response['record'];
		  $code = $response['code'];
		}

		return $record;
	}

	private function get_token() 
	{		
		$token = $this->session->userdata('memo_token');

		if(empty($token)) 
		{
			$curl = curl_init();
			curl_setopt_array($curl, array(
			CURLOPT_URL => APIURL."/get-token",
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => "",
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 30,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => "POST",
			CURLOPT_POSTFIELDS => "username=".APIUSER."&password=".APIPASSWORD."",
			CURLOPT_HTTPHEADER => array(
				  "Accept: */*",
				  "Content-Type: application/x-www-form-urlencoded",
				),
			));
			$response = curl_exec($curl);
			$err = curl_error($curl);
			curl_close($curl);
			if (empty($err)){
				$response = json_decode($response, true);
				$token = $response['token'];
				$this->session->set_userdata('memo_token',$token);
			}	
		}	

		return $token;
	}


}
