<?php
// ini_set("memory_limit", "-1");
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);

require_once "/home/mysamm/Lib/MysqlDB/connection.php"; 
require_once "/home/mysamm/Lib/MongoDB/mongo_connect.php";
require_once "/home/mysamm/Lib/MysqlDB/connection_pt_server.php"; 
require_once "/home/mysamm/Lib/mail.php"; 
require_once "/home/mysamm/public_html/vendor/autoload.php"; 
ini_set('max_execution_time', 3500);

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Alignment;

class ApiCGdata extends Connection{
	function __construct() {
		$this->mdb = new MongoConn();
		$this->db = new Connection();
		#print_r($this->db); die;
		#$this->dbMaster = new ConnectionMaster();
		$this->dbPT = new ConnectionPT();
	}
	
	
	function generate_content($data_string){
		
		$data = array();
		if(!empty($data_string)){
			$data = json_decode($data_string, true);
		}
		
		$report_id = $data['report_id'];
		$user_id = $data['user_id'];
		$website_id = $data['website_id'];
		$content_type = $data['content_type'];
		$not_include_item = $data['include_item'];
		$not_include_brand = $data['include_brand'];
		$white_labeled = $data['white_labeled'];
		$api_key = $data['api_key'];
		$product_name_rules = $data['product_name_rules'];
		$bullet_point_rules = $data['bullet_point_rules'];
		$romance_copy_rules = $data['romance_copy_rules'];
		$remove_punctuation = $data['remove_punctuation'];
		$collection_output = $data['collection_output'];
				 
		$log_im = "/home/mysamm/public_html/content_api/api_logs/".$report_id."_".$website_id."_cmd_logs.txt";
		
		$negative_term_array = array();
		
		$additional_feilds_array = array();
		$additional_feilds_array_header = array();
		
		$content_type  = trim($data['content_type']);
		if(isset($data['additional_feilds'])){
			$additional_feilds_array  = json_decode($data['additional_feilds'], true);
			$additional_feilds_array_header = $additional_feilds_array;
		}
		
		$header_array3 =  explode(",", $content_type);
		
		
		$rowCount = 3;
		$products = 0;
		$completionTokens = 0;
		$promptTokens = 0;
		$bbcount = 0;
		$bbmax_count = 0;
		$rcount  = 0;
		
		$rowm = $data;

		unset($rowm['_id']);

		$category_info = array();

		$cat_id = $rowm['is_prime'];

		if($rowm['category_info']){
		$cat_id = $rowm['is_prime'];
		$category_info = json_decode($rowm['category_info'], true);
		$cate_name = $category_info[$cat_id];
		}
		#print_r($cate_name); die;
		unset($rowm['category_info']);
		$i = 0;
		$key_exist = $rowm['sku']."**".$rowm['product_type']."**".$rowm['product_name'];
		$key_exist = trim($key_exist);
		$key_exist = preg_replace("/\W+/is","-", $key_exist);
		$key_exist = strtolower($key_exist);





		$top_100_data = "http://169.46.176.94/content_api/api_tct_header_data.php?cid=$cat_id"; 
		$cont = file_get_contents($top_100_data); 
		$top_100_data_array = json_decode($cont, true);

		#print_r($top_100_data_array); die;

		$sku = $content_type = $product_name = $product_type = $attr_finish = $attr_dimension = 0;
		$name_avg_char = $sample_name_term = $avg_bullet_point = $max_word_bullet = $sample_bullet_term = $min_word_romance_copy = $max_word_romance_copy = $min_char_romance_copy  = $max_char_romance_copy = 0;

		$sku  = trim($rowm['sku']);

		$content_type  = trim($rowm['content_type']);
		$product_name  = trim($rowm['product_name']);
		$product_type  = trim($rowm['product_type']);
		$attr_finish  = trim($rowm['attr_finish']);
		$attr_dimension  = trim($rowm['attr_dimension']);
		$brand  = trim($rowm['brand']);

		$rowm['cate_name'] = $cate_name;

		$additional_feilds_array = array();
		$additional_data = "";
		if(isset($rowm['additional_feilds'])){
			$additional_feilds_array  = json_decode($rowm['additional_feilds'], true); 
		}
	
		if(!empty($additional_feilds_array)){
			$additional_data = json_encode($additional_feilds_array, true);
		}

		//---------Product Name Input 100------//
		$product_input_array = array();


		$is_include_size = 0;
		$is_include_sku = 0;
		$name_max_word_limit = 0;

		$rowm['content_type'] = $content_type;

		if(preg_match("/product\_name/is",$content_type)){

		$word_sweetspots = $top_100_data_array['word_sweetspots'];
		$word_sweetspots_r = explode("-", $word_sweetspots);
		$name_max_word_limit = trim($word_sweetspots_r[1]);

		$name_avg_char = $top_100_data_array['avgchar'];
		$term_in_name_arrays = $top_100_data_array['term_in_name'];
		$term_in_name_array = array();
		foreach($term_in_name_arrays as $term=>$vl){
			if(!in_array($term, $negative_term_array)){
				$term_in_name_array[$term] = $vl;
			}
		}
		$term_in_name = array_slice($term_in_name_array, 0, 20, true);
		$sample_name_term = implode(',', array_map(
			function ($v, $k) { return sprintf("%s", $k, $v); },
			$term_in_name,
			array_keys($term_in_name)
		));

		if(preg_match("/Size\s+Present/is", $sample_name_term)){
			$is_include_size = 1;
		}

		if(preg_match("/Sku\s+Present/is", $sample_name_term)){
			$is_include_sku = 1; 
		}
		$not_include_brand = 1;
		if($white_labeled != 1){
			if(preg_match("/Brand\s+Present/is", $sample_name_term)){
				$white_labeled = 0;  
				$not_include_brand = 0; 
			}
		}
		}
		//---------Bullet Point Input 100------//
		$avg_bullet_point_as_opt = 0;
		if(preg_match("/bullet\_point/is",$content_type)){

		$avg_bullet_point = $top_100_data_array['avgbullet'];

		if(is_numeric($avg_bullet_point)){
			if($avg_bullet_point < 5){
				$avg_bullet_point = 5;
			}
		}else{
			$avg_bullet_point = 5; 
		}
		$avg_bullet_point_as_opt = $avg_bullet_point+3;

		$max_word_bullets = $top_100_data_array['bullete_word_sweetspot'];
		$max_word_bullets_r = explode("-", $max_word_bullets);
		$max_word_bullet = trim($max_word_bullets_r[1]);
		if($max_word_bullet > 30){
			$max_word_bullet = 30; 
		}
		$term_in_bullet_array = array();
		$term_in_bullet_arrays = $top_100_data_array['term_in_bullet'];

		foreach($term_in_bullet_arrays as $term=>$vl){
			if(!in_array($term, $negative_term_array)){
				$term_in_bullet_array[$term] = $vl;
			}
		}

		$term_in_bullet = array_slice($term_in_bullet_array, 0, 20, true);

		$sample_bullet_term = implode(',', array_map(
			function ($v, $k) { return sprintf("%s", $k, $v); },
			$term_in_bullet,
			array_keys($term_in_bullet)
		));
		}

		if(preg_match("/romance\_copy/is",$content_type)){
		$average_word_romace_copy = $top_100_data_array['avgromancew'];
		if($top_100_data_array['romace_sweetspots'] == "N/A"){
			$min_word_romance_copy = $average_word_romace_copy-5;
			$max_word_romance_copy = $average_word_romace_copy+5;
		}else{
			$romace_sweetspots	= $top_100_data_array['romace_sweetspots'];
			$romace_sweetspots_r = explode("-", $romace_sweetspots);
			$min_word_romance_copy = trim($romace_sweetspots_r[0]);
			$max_word_romance_copy = trim($romace_sweetspots_r[1]);
		}

		if($min_word_romance_copy == '0' || $min_word_romance_copy == 'N/A' || $min_word_romance_copy == ''){
			$min_word_romance_copy = "50";
		}

		if($max_word_romance_copy == '0' || $max_word_romance_copy == 'N/A' || $max_word_romance_copy == ''){
			$max_word_romance_copy = "100";
		}

		if($top_100_data_array['romace_sweetspots'] == "N/A"){
			$min_char_romance_copy = 1000;
			$max_char_romance_copy = 2500;
		}else{
			$romance_char_sweetspot	= $top_100_data_array['romance_char_sweetspot'];
			$romance_char_sweetspot_r = explode("-", $romance_char_sweetspot);
			$min_char_romance_copy = trim($romance_char_sweetspot_r[0]);
			$max_char_romance_copy = trim($romance_char_sweetspot_r[1]);
		}
		} 

		$recount = 0;

		if($additional_data == ""){
			$additional_data = "{}";
		}

		if($not_include_item == 1){

		}else{
		if($is_include_sku == 1){
			$not_include_item = 0;
		}else{
			$not_include_item = 1;
		}
		}
		$product_name_cmd = preg_replace("/\'/is", "", $product_name);
		$product_type_cmd = preg_replace("/\'/is", "", $product_type);
		$attr_finish_cmd = preg_replace("/\'/is", "", $attr_finish);
		$attr_dimension_cmd = preg_replace("/\'/is", "", $attr_dimension);
		$brand_cmd = preg_replace("/\'/is", "", $brand);

		$re_hit = 1;	

		RECHECKINSTANCE:

		$final_cmd = "gptsparam output:'{$content_type}' sku:'{$sku}' product_name:'{$product_name_cmd}' product_type:'{$product_type_cmd}' attr_finish:'{$attr_finish_cmd}' attr_dimension:'{$attr_dimension_cmd}' brand:'{$brand_cmd}' name_max_word_limit:'{$name_max_word_limit}' name_avg_char:'{$name_avg_char}' sample_name_term:'{$sample_name_term}' avg_bullet_point:'{$avg_bullet_point_as_opt}' max_word_bullet:'{$max_word_bullet}' sample_bullet_term:'{$sample_bullet_term}', min_word_romance_copy:'{$min_word_romance_copy}' max_word_romance_copy:'{$max_word_romance_copy}' additional_feilds:'{$additional_data}' do_not_include_item_number:'{$not_include_item}' do_not_include_brand:'{$not_include_brand}' is_white_labeled:'{$white_labeled}' is_include_size:'{$is_include_size}' remove_punctuation:'{$remove_punctuation}' apikey:'{$api_key}' additional_product_name_rule:'{$product_name_rules}' additional_bullet_point_rule:'{$bullet_point_rules}' additional_romance_copy_rules:'{$romance_copy_rules}'"; 
		#print "$final_cmd\n"; exit;
		file_put_contents($log_im, $final_cmd.PHP_EOL, FILE_APPEND);

		$content_type_count = count(explode(",", $content_type));



		$data = shell_exec($final_cmd);

		$date_json_decoded = array();
		if($content_type_count == 1){
			$data_Arr = explode("####", $data);
			$json1 = trim($data_Arr[0]);
			$date_json_decoded = json_decode($json1, true);
		}else if($content_type_count == 2){
			$data_Arr = explode("####", $data);
			$json1 = trim($data_Arr[0]);
			$json2 = trim($data_Arr[1]);
			$date_json_decoded1 = json_decode($json1, true);
			$date_json_decoded2 = json_decode($json2, true);
			$date_json_decoded = $this->mergeArrays($date_json_decoded1,$date_json_decoded2);
		}else{
			$date_json_decoded = json_decode($data, true); 
		}

		if(empty($date_json_decoded) && $re_hit < 5){ 
			$re_hit++;
			goto RECHECKINSTANCE; 
		} 

		foreach($header_array3 as $k=>$hkey){
			$val = "";	
			if($hkey == "product_name"){
				$key_ex = "product_name";
				$key_ex_n = "product_name_new";
				$val = $date_json_decoded['data'][$key_ex];
				
				if($val == ""){
					$re_hit = 2;
				}
			}else if($hkey == "bullet_point"){
				$key_ex = "bullets_points";
				$key_ex_n = "bullets_points_new";
				$bull_val = $date_json_decoded['data'][$key_ex];
				
				if(is_array($bull_val)){
					$bbcount = count($bull_val);
					if($bbcount > $bbmax_count){
						$bbmax_count = $bbcount;
					}
					$val = implode("\n",$bull_val);
				}
				if($val == ""){
					$re_hit = 2;
				}
			}else if($hkey == "romance_copy"){
				$key_ex = "product_description";
				$key_ex_n = "product_description_new";
				$val = $date_json_decoded['data'][$key_ex];
				
				if($val == ""){
					$re_hit = 2;
				}
			} 
			$val = preg_replace_callback('/(\d+)\s*(Feet|ft|Inches|Inch|-inch|in\.|in)/is', function($matches) {
				$unit = strtolower($matches[2]);
				if ($unit == 'feet' || $unit == 'ft') {
					return $matches[1] . "'"; 
				}else if ($unit == 'in.' || $unit == 'in' || $unit == 'inches' || $unit == 'inch' || $unit == '-inch') {
					return $matches[1] . '"'; 
				} 
				return $matches[0];
			}, $val); 

			$rowm[$key_ex_n] = $val;
		} 

		$products++;

		$rowm['avg_bullet_point'] = $avg_bullet_point;
		$rowm['completionTokens'] = $date_json_decoded['data']['completionTokens'];
		$rowm['promptTokens'] = $date_json_decoded['data']['promptTokens'];
		$rowm['totalTokens'] = $date_json_decoded['data']['totalTokens'];


		$completionTokens = $completionTokens + $rowm['completionTokens'];	
		$promptTokens = $promptTokens + $rowm['promptTokens'];	
		$rcount++;
		unset($rowm['product_name_rules']);
		unset($rowm['bullet_point_rules']);
		unset($rowm['romance_copy_rules']);
		unset($rowm['include_item']);
		unset($rowm['include_brand']);
		unset($rowm['white_labeled']);
		unset($rowm['api_key']);
		
		#print_r($rowm); die;
		$this->mdb->insert_data($collection_output , $rowm);
		
		unset($rowm);		
		
	}
	
	function mergeArrays($array1, $array2) {
		
		$result = array();
		if(is_array($array1) && is_array($array2)){
			
			foreach (array_keys($array1 + $array2) as $key) {
				if ($key === 'data') {
					$result['data'] = array_merge($array1['data'], $array2['data']);
					// Summing up completionTokens, promptTokens, and totalTokens if they exist in both arrays
					foreach (['completionTokens', 'promptTokens', 'totalTokens'] as $tokenKey) {
						if (isset($array1['data'][$tokenKey]) && isset($array2['data'][$tokenKey])) {
							$result['data'][$tokenKey] = $array1['data'][$tokenKey] + $array2['data'][$tokenKey];
						} elseif (isset($array1['data'][$tokenKey])) {
							$result['data'][$tokenKey] = $array1['data'][$tokenKey];
						} elseif (isset($array2['data'][$tokenKey])) {
							$result['data'][$tokenKey] = $array2['data'][$tokenKey];
						}
					}
				} elseif (isset($array1[$key])) {
					$result[$key] = $array1[$key];
				} elseif (isset($array2[$key])) {
					$result[$key] = $array2[$key];
				}
			}
		}else if(is_array($array1)){
			$result = $array1;
		}else if(is_array($array2)){
			$result = $array2;
		}
		
		return $result; 
	}
	
	
	function compareDates($date1, $date2){
      if (strtotime($date1) < strtotime($date2))
         return 1;
      else if (strtotime($date1) > strtotime($date2))
         return -1;
      else
         return 0;
	}
	
	
	function match_string($string_1, $string_2){
		
		
		$string_1 = strtolower($string_1);
		$string_1 = trim($string_1);
		$string_1 = preg_replace("/\W+/is", "", $string_1);
		
		
		$string_2 = strtolower($string_2);
		$string_2 = trim($string_2);
		$string_2 = preg_replace("/\W+/is", "", $string_2);
		
		if($string_1 == $string_2){
			return 1;
		}else{
			return 2;
		}
	}
	
	public function encodeJson($responseData) {
		$jsonResponse = json_encode($responseData, JSON_INVALID_UTF8_IGNORE);
		return $jsonResponse;		
	}
  

}

?>