<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Pagination\Paginator;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;


use App\Models\User;
use Illuminate\Support\Facades\View;
use App\Models\Diamond;



class Vdb_product_raw extends Controller { 

	function getAllVdbDiamonds() {
		$records = array();
	
		$total_record = 0;
		$total_update = 0;
		$total_insert = 0;
		$total_delete = 0;

		$curl = curl_init();
	
		curl_setopt_array($curl, array(
			CURLOPT_URL => 'https://apiservices.vdbapp.com/v2/diamonds?type=Lab_grown_Diamond&page_number=1&page_size=50',
			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 => array(
				'Authorization: Token token=4ujQnUscjOG_BWpCXwBTBqwTtYzHkQ_RUvkPtNJBGXo, api_key=_j1wfVmJTpz1noOAU_9aVlA'
			),
		));

		$responses = curl_exec($curl);
		curl_close($curl);
		$data_length = json_decode($responses, true);
		// $this->print_ex($data_length); die;

		$total_diamonds_found = floor($data_length['response']['body']['total_diamonds_found'] / 50 + 1);

		// $query = "select stock_id,vendor_id,Buy_Price,shape,weight,color,clarity,cut_grade,polish,symmetry,measurements,lab,is_fancy,Certificate from tbl_vdb_diamond limit 150000"; 
		$query = "select stock_id from tbl_vdb_diamond limit 150000"; 
		$records = DB::select($query);
		$existingStockIds = array_column($records, 'stock_id');
		// $this->print_ex($records); die;
		for ($page = 1; $page <= $total_diamonds_found; $page++) {
			// for ($page = 362; $page <= 363; $page++) {
			// die;
			$curl = curl_init();
	
			curl_setopt_array($curl, array(
				CURLOPT_URL => 'https://apiservices.vdbapp.com/v2/diamonds?type=Lab_grown_Diamond&page_number=' . $page . '&page_size=50',
				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 => array(
					'Authorization: Token token=4ujQnUscjOG_BWpCXwBTBqwTtYzHkQ_RUvkPtNJBGXo, api_key=_j1wfVmJTpz1noOAU_9aVlA'
				),
			));
	
			$response = curl_exec($curl);
			curl_close($curl);
	
			$data = json_decode($response, true);
			
			if (isset($data['response']['body']['diamonds'])) {

				$diamondRecord = $data['response']['body']['diamonds'];
				foreach ($diamondRecord as $row) {

					$vendor_id = $row['vendor_id'];
					// $vendor_name = $row['vendor_name'];
					$vendor_name = ($row['vendor_name'] != '') ? str_replace('🔹', '', $row['vendor_name']) : 'dummy';
					$stock_No = $row['stock_num'];

					$diamondData = $this->vdbDiamond($row, $vendor_id);

					if (in_array($stock_No, $existingStockIds)) {

						$existingStockIds = array_diff($existingStockIds, [$stock_No]);

						$single_query = "select * from tbl_vdb_diamond where stock_id = '$stock_No' and vendor_id = '$vendor_id' limit 1"; 
						$record = DB::select($single_query);

						// $by_price = $record[0]->Buy_Price;
				
						if($record[0]->vendor_id == $diamondData['vendor_id'] && $record[0]->shape != $diamondData['shape'] || $record[0]->Buy_Price != $diamondData['Buy_Price'] || $record[0]->weight != $diamondData['weight'] || $record[0]->color != $diamondData['color'] || $record[0]->clarity != $diamondData['clarity'] || $record[0]->cut_grade != $diamondData['cut_grade'] || $record[0]->polish != $diamondData['polish'] || $record[0]->symmetry != $diamondData['symmetry']){
							$this->updateDiamondRecord($diamondData, $stock_No, $vendor_id);
							$total_update++;
						}

					}else{

						$this->insertDiamondRecord($diamondData, $stock_No, $vendor_id, $vendor_name);
						$total_insert++;

					}
					
					$total_record++;

				}
				
			}
		}

		// Mark remaining stocks as deleted
		foreach ($existingStockIds as $stock_id) {
			$this->markDiamondAsDeleted($stock_id);
			$total_delete++;
		}

		$log_data = [
			'total_record' => $total_record,
			'total_update' => $total_update,
			'total_insert' => $total_insert,
			'total_delete' => $total_delete,
			'file' => 'VDB Diamonds',
			'log_time' => now(), // Use Laravel's helper for the current timestamp
			'type' => 'Lab Grown',
			'vendor_id' => $vendor_id,
		];
		
		// Insert the log data into the database
		DB::table('tbl_vdb_inventory_log')->insert($log_data);
	}

	private function vdbDiamond($row, $vendor_id) {
		// print_ex($row);
		$stock_id = ($row['stock_num'] != '') ? $row['stock_num'] : '';
		$cert_no = ($row['cert_num'] != '') ? $row['cert_num'] : '';
		$certificateLink = ($row['cert_url'] != '') ? $row['cert_url'] : '';
		$diamond_image = ($row["image_thumb_url"] != '') ? $row["image_thumb_url"] : '';
		$diamond_video = ($row['video_url'] != '') ? $row['video_url'] : '';
		$diamond_type = ($row['diamond_type'] != '') ? $row['diamond_type'] : '';;
		$weight = ($row['size'] != '') ? $row['size'] : '';
		$table_d = ($row['table_percent'] != '') ? $row['table_percent'] : '';
		$depth = ($row['depth_percent'] != '') ? $row['depth_percent'] : '';
		$measurements = ($row['measurement'] != '') ? $row['measurement'] : '';
		$m_length = ($row['meas_length'] != '') ? $row['meas_length'] : '';
		$m_width = ($row['meas_width'] != '') ? $row['meas_width'] : '';
		$m_height = ($row['meas_depth'] != '') ? $row['meas_depth'] : '';
		$ratio = ($row['meas_ratio'] != '') ? $row['meas_ratio'] : '';
		$country = ($row['country'] != '') ? $row['country'] : '';
		$city = ($row['city'] != '') ? $row['city'] : '';
		$state = ($row['state'] != '') ? $row['state'] : '';
		
		$availability = ($row['available'] != '') ? $row['available'] : '';
		$milky = ($row['milky'] != '') ? $row['milky'] : '';
		$shade = ($row['shade'] != '') ? $row['shade'] : '';
		$crown_angle = ($row['crown_angle'] != '') ? $row['crown_angle'] : '';
		$crown_ht = ($row['crown_height'] != '') ? $row['crown_height'] : '';
		$pavillion_angle = ($row['pavilion_angle'] != '') ? $row['pavilion_angle'] : '';
		$pavillion_depth = ($row['pavilion_depth'] != '') ? $row['pavilion_depth'] : '';
		$girdle_perct = ($row['girdle_percent'] != '') ? $row['girdle_percent'] : '';
		$girdle_con = ($row['girdle_condition'] != '') ? $row['girdle_condition'] : '';
		$culet_condition = ($row['culet_condition'] != '') ? $row['culet_condition'] : '';

		
		$girdle_thin = ($row['girdle_min'] != '') ? $row['girdle_min'] : '';
		$girdle_thick = ($row['girdle_max'] != '') ? $row['girdle_max'] : '';
		$culet_size = ($row['culet_size'] != '') ? $row['culet_size'] : '';
		$keytosymb = ($row['key_to_symbol'] != '') ? $row['key_to_symbol'] : '';
		$eye_clean = ($row['eye_clean'] != '') ? $row['eye_clean'] : '';
		$treatment = ($row['treatment'] != '') ? $row['treatment'] : '';
		$member_comment = ($row['comments'] != '') ? $row['comments'] : '';

		if(!empty($row['total_sales_price'])){
			// $main_price = $row['total_sales_price'] * 1.50;
			$total_sales_price = floatval($row['total_sales_price']);
			// $discount_percentage = 30; // Discount percentage
			// $discounted_price = $total_sales_price - ($total_sales_price * $discount_percentage / 100);
			
			$main_price = round($total_sales_price, 0);
		}else{
			$main_price = 0;
		}
		$cash_price = ($main_price != '') ? $main_price : 0;
		$Buy_Price = ($main_price != '') ? $main_price : 0;
		$shape = ($row['shape'] != '') ? ucfirst(strtolower($row['shape'])) : 'None';
		$color = ($row['color'] != '') ? $row['color'] : 'None';
		$is_fancy = ($row['is_fancy'] != '') ? $row['is_fancy'] : '0';	
		$fancy_color = ($row['fancy_color_dominant_color'] != '') ? $row['fancy_color_dominant_color'] : '';
		$fancy_color_overtone = ($row['fancy_color_overtone'] != '') ? $row['fancy_color_overtone'] : '';
		$fancy_color_intensity = ($row['fancy_color_intensity'] != '') ? $row['fancy_color_intensity'] : '';
		$clarity = ($row['clarity'] != '') ? $row['clarity'] : 'None';
		
		// $cut = ($row['cut'] != '') ? $row['cut'] : '';
		if($row['cut'] == 'Excellent'){
			$cuts = 'EX';
		}else if($row['cut'] == 'Ideal'){
			$cuts = 'ID';
		}else if($row['cut'] = 'Very Good'){
			$cuts = 'VG';
		}else if($row['cut'] == 'Good'){
			$cuts = 'GD';
		}else if($row['cut'] != ''){
			$cuts = $row['cut'];
		}else{
			$cuts = 'None';
		}
		$cut = $cuts;



		// $polish = ($row['polish'] != '') ? $row['polish'] : '';
		if($row['polish'] == 'Excellent'){
			$pol = 'EX';
		}else if($row['polish'] == 'Ideal'){
			$pol = 'ID';
		}else if($row['polish'] = 'Very Good'){
			$pol = 'VG';
		}else if($row['polish'] == 'Good'){
			$pol = 'GD';
		}else if($row['polish'] != ''){
			$pol = $row['polish'];
		}else{
			$pol = 'None';
		}
		$polish = $pol;



		// $symmetry = ($row['symmetry'] != '') ? $row['symmetry'] : '';
		if($row['symmetry'] == 'Excellent'){
			$sym = 'EX';
		}else if($row['symmetry'] == 'Ideal'){
			$sym = 'ID';
		}else if($row['symmetry'] = 'Very Good'){
			$sym = 'VG';
		}else if($row['symmetry'] == 'Good'){
			$sym = 'GD';
		}else if($row['symmetry'] != ''){
			$sym = $row['symmetry'];
		}else{
			$sym = 'None';
		}
		$symmetry = $sym;


		$fluorescence = ($row['fluor_color'] != '') ? $row['fluor_color'] : 'None';
		$fluor_intensity = ($row['fluor_intensity'] != '') ? $row['fluor_intensity'] : 'None';
		
		$lab = ($row['lab'] != '') ? $row['lab'] : 'None';
		$BGM = ($row['bgm'] != '') ? $row['bgm'] : '';
		$cert_comment = ($row['cert_comment'] != '') ? $row['cert_comment'] : '';
		$country_of_origin = ($row['country_of_origin'] != '') ? $row['country_of_origin'] : '';
		$star_length = ($row['star_length'] != '') ? $row['star_length'] : '';
		$pair_stock_num = ($row['pair_stock_num'] != '') ? $row['pair_stock_num'] : '';
		$parcel_stones = ($row['parcel_stones'] != '') ? $row['parcel_stones'] : '';
		$inclusion_center = ($row['inclusion_center'] != '') ? $row['inclusion_center'] : '';
		$inclusion_black = ($row['inclusion_black'] != '') ? $row['inclusion_black'] : '';
		$brand = ($row['brand'] != '') ? $row['brand'] : '';
		$masked_video_url = ($row['masked_video_url'] != '') ? $row['masked_video_url'] : '';
		$rapnet_price = ($row['rapnet_price'] != '') ? $row['rapnet_price'] : '';
		$short_title = ($row['short_title'] != '') ? $row['short_title'] : '';

		// $vendor_name = ($row['vendor_name'] != '') ? $row['vendor_name'] : '';
		$vendor_name = ($row['vendor_name'] != '') ? str_replace('🔹', '', $row['vendor_name']) : '';
		// $vendor_name = 'error';
		
		
		$description = '<ul>';
			$description .= ($shape != '') ? '<li><strong>SHAPE</strong> '.$shape.'</li>' : '';
			$description .= ($weight != '') ? '<li><strong>CARAT</strong> '.$weight.'ct.</li>' : '';
			$description .= ($color != '') ? '<li><strong>COLOR</strong> '.$color.'</li>' : '';
			$description .= ($clarity != '') ? '<li><strong>CLARITY</strong> '.$clarity.'</li>' : '';
			$description .= ($cut != '') ? '<li><strong>CUT</strong> '.$cut.'</li>' : '';
			
			$description .= ($lab != '') ? '<li><strong>REPORT</strong> '.$lab.'</li>' : '';
			$description .= ($cert_no != '') ? '<li><strong>CERTIFICATE NO</strong> <a target="_blank" href="'.$certificateLink.'">'.$cert_no.'</a></li>' : '';
			$description .= ($m_length != '') ? '<li><strong>LENGTH</strong> '.$m_length.' mm</li>' : '';
			$description .= ($m_width != '') ? '<li><strong>WIDTH</strong> '.$m_width.' mm</li>' : '';
			$description .= ($m_height != '') ? '<li><strong>DEPTH</strong> '.$m_height.' mm</li>' : '';

			$description .= ($table_d != '') ? '<li><strong>TABLE (%)</strong> '.$table_d.' %</li>' : '';
			$description .= ($depth != '') ? '<li><strong>DEPTH (%)</strong> '.$depth.' %</li>' : '';
			$description .= ($symmetry != '') ? '<li><strong>SYMMETRY</strong> '.$symmetry.'</li>' : '';
			$description .= ($polish != '') ? '<li><strong>POLISH</strong> '.$polish.'</li>' : '';
			$description .= ($fluorescence != '') ? '<li><strong>FLUORESCENCE</strong> '.$fluorescence.'</li>' : '';
			$description .= ($measurements != '') ? '<li><strong>MEASUREMENTS</strong> '.$measurements.'</li>' : '';
			$description .= ($ratio != '') ? '<li><strong>RATIO</strong> '.$ratio.'</li>' : '';
		$description .= '</ul>';


		$data = [

			'stock_id' => $stock_id,

			'short_title' => $short_title,

			'is_fancy' => $is_fancy,

			'm_length' => $m_length,

			'm_width' => $m_width,

			'm_depth' => $m_height,

			'availability' => $availability,

			'shape' => $shape,

			'weight' => $weight,

			'color' => $color,

			'clarity' => $clarity,

			'cut_grade' => $cut,

			'polish' => $polish,

			'symmetry' => $symmetry,

			'fluorescence_int' => $fluor_intensity,

			'fluorescence_color' => $fluorescence,

			'measurements' => $measurements,

			'lab' => $lab,

			'treatment' => $treatment,

			'fancy_color' => $fancy_color,

			'fancy_color_intensity' => $fancy_color_intensity,

			'fancy_color_overtone' => $fancy_color_overtone,

			'depth' => $depth,

			'table_d' => $table_d,

			'girdle_thin' => $girdle_thin,

			'girdle_thick' => $girdle_thick,

			'girdle_perct' => $girdle_perct,

			'girdle_con' => $girdle_con,

			'culet_size' => $culet_size,

			'culet_con' => $culet_condition,

			'crown_ht' => $crown_ht,

			'crown_angle' => $crown_angle,

			'pavillion_depth' => $pavillion_depth,

			'pavillion_angle' => $pavillion_angle,

			'cert_comments' => $cert_comment,

			'country' => $country,

			'state' => $state,

			'city' => $city,

			'origin' => $country_of_origin,

			'keytosymb' => $keytosymb,

			'shade' => $shade,

			'star_len' => $star_length,

			'report_dt' => '',

			'report_type' => '',

			'milky' => $milky,

			'eye_clean' => $eye_clean,

			'gemprint_ID' => '',

			'BGM' => $BGM,

			'ratio' => $ratio,

			'diamond_type' => $diamond_type,

			'member_comment' => $member_comment,

			'time_to_location' => '',

			'LsMatchedPairSeparable' => '',

			'pair_stock' => $pair_stock_num,

			'allow_raplink_feed' => '',

			'parcel_stones' => $parcel_stones,

			'center_inclusion' => $inclusion_center,

			'black_inclusion' => $inclusion_black,

			'lab_location' => '',

			'brand' => $brand,

			'Sarine_Name' => '',

			'Internal_Clarity_Desc_Code' => '',

			'Clarity_Description' => '',

			'Modified_Rate' => '',

			'wire_discount_price' => '',

			'diamond_image' => $diamond_image,

			'diamond_video' => $diamond_video,

			'Video_HTML' => $masked_video_url,

			'CertificateLink' => $certificateLink,

			'Rap_Price' => $rapnet_price,

			'Memo_Price' => '',

			'Memo_Discount_PER' => '',

			'Buy_Price' => $Buy_Price,

			'Buy_Price_Discount_PER' => '',

			'COD_Buy_Price' => '',

			'COD_Buy_Price_Discount_PER' => '',

			'Certificate' => $cert_no,

			'grade' => $cut,

			'cut' => $cut,

			'cash_price' => $cash_price,

			'report_filename' => '',

			'rapnet' => '',

			'created_at' => date('Y-m-d h:i'),

			'edited_at' => date('Y-m-d h:i'),

			'description' => $description,

			'vendor_id' => $vendor_id,

			'vendor_name' => $vendor_name,

			'feed_type'=> 'API'

		];
		return $data;
	}

	private function insertDiamondRecord($diamondData, $stock_No, $vendor_id, $vendor_name) {
			// Insert into the 'tbl_vdb_diamond' table
			DB::table('tbl_vdb_diamond')->insert($diamondData);
			// Insert into the 'tbl_vdb_diamond_insert_update' table
			DB::table('tbl_vdb_diamond_insert_update')->insert([
				'stock_id' => $stock_No,
				'vendor_id' => $vendor_id,
				'vendor_name' => $vendor_name,
				'feed_type' => 'API'
			]);
	}

	private function updateDiamondRecord($diamondData, $stock_No, $vendor_id) {
			// Update the 'tbl_vdb_diamond' table
			DB::table('tbl_vdb_diamond')
				->where([
					'stock_id' => $stock_No,
					'vendor_id' => $vendor_id,
					'feed_type' => 'API',
				])
				->update($diamondData);
		
			// Update the 'tbl_vdb_diamond_insert_update' table
			DB::table('tbl_vdb_diamond_insert_update')
				->where([
					'stock_id' => $stock_No,
					'vendor_id' => $vendor_id,
					'feed_type' => 'API',
				])
				->update(['is_update' => 1]);
	}
		
	private function markDiamondAsDeleted($stock_id) {
			DB::table('tbl_vdb_diamond_insert_update')
				->where([
					'stock_id' => $stock_id,
					'feed_type' => 'API',
				])
				->update(['is_delete' => 1]);
	}
		
	function print_pre($data)
	{ 
		   echo "<pre>";print_r($data);echo "</pre>";       
	}
	   
	function print_ex($data)
	{ 
		   echo "<pre>";print_r($data);echo "</pre>";exit();       
	}
		
	// https://braintreeeasysoft.com/braintree/demogetVdbDiamonds
	function demogetVdbDiamonds() {
		// die("fdf");
		$records = array();
	
		// for ($page = 1; $page <= 2; $page++) {
			// for ($page = 1; $page <= 2400; $page++) {
				$page = 1;
			$curl = curl_init();
	
			curl_setopt_array($curl, array(
				CURLOPT_URL => 'https://apiservices.vdbapp.com/v2/diamonds?type=Lab_grown_Diamond&page_number=' . $page . '&page_size=50&stock_num=NGT-09-26',
				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 => array(
					'Authorization: Token token=4ujQnUscjOG_BWpCXwBTBqwTtYzHkQ_RUvkPtNJBGXo, api_key=_j1wfVmJTpz1noOAU_9aVlA'
				),
			));
	
			$response = curl_exec($curl);
			curl_close($curl);
	
			$data = json_decode($response, true);
			
			if (isset($data['response']['body']['diamonds'])) {
				$diamonds = $data['response']['body']['diamonds'];
				$records = array_merge($records, $diamonds);	
			}
		// }
		$this->print_ex($data); die;
		// print_r($data);
		// return $records;
	}

	function bulkGetVdbDiamonds() {
		// die("fdf");
		$records = array();
	
		// for ($page = 1; $page <= 2; $page++) {
			// for ($page = 1; $page <= 2400; $page++) {
				$page = 1;
			$curl = curl_init();
	
			curl_setopt_array($curl, array(
				CURLOPT_URL => 'https://apiservices.vdbapp.com/v2/diamonds/inventory?type=Lab_grown_Diamond&upload_file_type=1',
				// CURLOPT_URL => 'https://apiservices.vdbapp.com/v2/diamonds?type=Lab_grown_Diamond&upload_file_type=1',
				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 => array(
					'Authorization: Token token=4ujQnUscjOG_BWpCXwBTBqwTtYzHkQ_RUvkPtNJBGXo, api_key=_j1wfVmJTpz1noOAU_9aVlA'
				),
			));
	
			$response = curl_exec($curl);
			curl_close($curl);
	
			$data = json_decode($response, true);
			
			// if (isset($data['response']['body']['diamonds'])) {
			// 	$diamonds = $data['response']['body']['diamonds'];
			// 	$records = array_merge($records, $diamonds);	
			// }

		// }
		$this->print_ex($data); die;
		// print_r($data);
		// return $records;
	}


}