<?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/mail.php"; 
require_once "/home/mysamm/public_html/vendor/autoload.php"; 
ini_set('max_execution_time', 500);

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class ApiCGdata extends Connection{
	function __construct() {
		$this->mdb = new MongoConn();
		$this->db = new connection();
	}
	
	
	function generate_content($post_id, $collections){
		
		$collection_output = preg_replace("/matched\_category\_list/is", "content_output", $collections);
		
		$data = $this->db->Query("SELECT * FROM recent_post_data where id = $post_id");
		
		$spreadsheet = new Spreadsheet();
		
		$spreadsheet->getProperties()->setCreator('mySamm')
								 ->setTitle('cg')
								 ->setSubject('Content Generation');
		$sheet = $spreadsheet->getActiveSheet();
		
		$report_id = $data[0]['report_id'];
		$website_id = $data[0]['website_id'];
		$post_data = $data[0]['post_data'];
		$post_data_array = array();
		if($post_data){
			$post_data_array = json_decode($post_data, true);
		}
		
		$negative_terms_sql = "SELECT terms from negative_terms";
		$get_negative_terms = $this->db->Query($negative_terms_sql);
		$negative_term_array = array();
		foreach($get_negative_terms as $row){
			$negative_term_array[] = strtolower($row['terms']);
		}
		$this->db->execute("UPDATE content_generation_data_requsets SET process_state = 2 where id = $report_id");
			
		$cat_product_master_urls_sql = "SELECT id,website_category_name,active_in_pt,total_products,enabled from new_product_master_urls";
		$GetTotalFound = $this->db->Query($cat_product_master_urls_sql);
		$TotalFoundArray = array();
		$SubCategory = array(); 
		$ParentCategory = array();
		
		foreach($GetTotalFound as $row){
			$id = $row['id'];
			$website_category_name = $row['website_category_name'];
			$active_in_pt = $row['active_in_pt'];
			$enabled = $row['enabled'];
			if($active_in_pt == 'yes' && $enabled == 1){
				$ParentCategory[$id] = $website_category_name;
			}else{
				$SubCategory[$id] = $website_category_name;
			}
		}
		
		
		$filter = array('report_id'=>$report_id);
		$data = $this->mdb->Query($collections,$filter);
		$this->mdb->delete_document($collection_output,$filter);
		
		$log_im = "/home/mysamm/public_html/content_api/api_logs/".$report_id."_cmd_logs.txt";
		$log_ot = "/home/mysamm/public_html/content_api/api_logs/".$report_id."_out_put_logs.txt";
		
		$cols =array(0=>"A",1=>"B",2=>"C",3=>"D",4=>"E",5=>"F",6=>"G",7=>"H",8=>"I",9=>"J",10=>"K",11=>"L",12=>"M",13=>"N",14=>"O",15=>"P",16=>"Q",17=>"R",18=>"S",19=>"T",20=>"U",21=>"V",22=>"W",23=>"X",24=>"Y",25=>"Z",26=>"AA",27=>"AB",28=>"AC",29=>"AD",30=>"AE",31=>"AF",32=>"AG",33=>"AH",34=>"AI",35=>"AJ",36=>"AK",37=>"AL",38=>"AM",39=>"AN",40=>"AO",41=>"AP",42=>"AQ",43=>"AR",44=>"AS",45=>"AT",46=>"AU",47=>"AV",48=>"AW",49=>"AX",50=>"AY",51=>"AZ",52=>"BA",53=>"BB",54=>"BC",55=>"BD",56=>"BE",57=>"BF",58=>"BG",59=>"BH",60=>"BI");	
			
		
		$additional_feilds_array = array();
		foreach($data as $row){
			$rowm = (array) $row;
			
			$content_type  = trim($rowm['content_type']);
			$rowm['additional_feilds'] = preg_replace("/\\\/is","",$rowm['additional_feilds']);
			#print_r($rowm['additional_feilds']);
			if(isset($rowm['additional_feilds'])){
				 #print "Hello\n"; 
				$additional_feilds_array  = json_decode($rowm['additional_feilds'], true);
				#print_r($additional_feilds_array); die;
			}
			#print_r($rowm); die;
			#$content_type = "product_name,bullet_point";
			$email  = trim($rowm['email']);
			break;
		}		
		
		#print_r($additional_feilds_array); die;
		// foreach($data as $row){
			// $rowm = (array) $row;
			// $content_type  = trim($rowm['content_type']);
			// #$content_type = "product_name,bullet_point";
			// $email  = trim($rowm['email']);
			// break;
		// }		
		
		$rowCount = 1;
				
		$sheet->setCellValue('A'.$rowCount, 'Input');
		
		
		
	
		$header_array2 = array("SKU/Model Number","Category Name","Product Name","Product Type","Product Attribute Finish: Color/Finish","Product Attribute Dimensions");
		
		$i = 0;
		
		$rowCount = 2;
		foreach($header_array2 as $input_header){
			$cal = $cols[$i];
			$sheet->setCellValue($cal.$rowCount, $input_header);
			$sheet->getColumnDimension($cal)->setWidth(15);
			$sheet->getStyle($cal."1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('6491F8'); 
			$sheet->getStyle($cal."2")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('6491F8'); 
			$i++;
		}
		
		if(!empty($additional_feilds_array)){
			foreach($additional_feilds_array as $input_header=>$vl){
				$cal = $cols[$i];
				$sheet->setCellValue($cal.$rowCount, $input_header);
				
				$sheet->getColumnDimension($cal)->setWidth(15);
				
				$sheet->getStyle($cal."1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('6491F8'); 
				$sheet->getStyle($cal."2")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('6491F8'); 
				$i++;
			}
		}
		
		$header_array3 =  explode(",", $content_type);
		
		$j = $i+1;
		
		$sheet->setCellValue($cols[$j].'1', 'Output');
		
		foreach($header_array3 as $output_header){
			$cal = $cols[$j];
			if($output_header == "product_name"){
				$sheet->getColumnDimension($cal)->setWidth(40);
				$output_header_view = "New Product Name";
			}else if($output_header == "bullet_point"){
				$output_header_view = "New Bullet Points";
				$sheet->getColumnDimension($cal)->setWidth(45);
			}else if($output_header == "romance_copy"){
				$sheet->getColumnDimension($cal)->setWidth(70);
				$output_header_view = "New Romance Copy/Discription";
			}
			
			$sheet->getStyle($cal."1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('6491F8'); 
			$sheet->getStyle($cal."2")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('6491F8'); 
			
			$sheet->setCellValue($cal.$rowCount, $output_header_view);
			$j++;
		}
		
		
		
		$rowCount = 3;
		$products = 0;
		$completionTokens = 0;
		$promptTokens = 0;
		foreach($data as $row){
			$rowm = (array) $row;
			unset($rowm['_id']);
			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);
			#print_r($key_exist); die;			
			$input_key = "pc_rad_".$key_exist;
			if(isset($post_data_array[$input_key])){
				$cat_id = $rowm['category_id'] = $post_data_array[$input_key];
				if(isset($ParentCategory[$cat_id])){
					$cate_name = $ParentCategory[$cat_id];
					$top_100_data = file_get_contents("https://mschannellogin.com/files/TopCMCAHeader/{$cat_id}.txt");
					$top_100_data_array = json_decode($top_100_data, true);
				}else{
					$cate_name = $SubCategory[$cat_id];
					$top_100_data = file_get_contents("https://mschannellogin.com/files/TopCMCAHeaderSub/{$cat_id}.txt");
					$top_100_data_array = json_decode($top_100_data, true);
				}
			  
				$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']);
				
				$rowm['cate_name'] = $cate_name;
			    $additional_feilds_array = array();
				if(isset($rowm['additional_feilds'])){
					$rowm['additional_feilds'] = preg_replace("/\\\/is","",$rowm['additional_feilds']);
					$additional_feilds_array  = json_decode($rowm['additional_feilds'], true);
				}
			
				
		
				
				$cal = $cols[$i];
				$sheet->setCellValue($cal.$rowCount, $rowm['sku']);
				
				$i = $i+1;
				$cal = $cols[$i];			
				$sheet->setCellValue($cal.$rowCount, $cate_name);
				
				$i = $i+1;
				$cal = $cols[$i];			
				$sheet->setCellValue($cal.$rowCount, $product_name);
				
				$i = $i+1;
				$cal = $cols[$i];
				$sheet->setCellValue($cal.$rowCount, $product_type);
				
				$i = $i+1;
				$cal = $cols[$i];
				$sheet->setCellValue($cal.$rowCount, $attr_finish);
				
				$i = $i+1;
				$cal = $cols[$i];
				$sheet->setCellValue($cal.$rowCount, $attr_dimension);
				
				
				if(!empty($additional_feilds_array)){
					$i = $i+1;
					foreach($additional_feilds_array as $input_header=>$vl){
						$cal = $cols[$i];
						$sheet->setCellValue($cal.$rowCount, $vl);
						$i++;
					}
					
					$additional_data = json_encode($additional_feilds_array, true);
				}
		
				//---------Product Name Input 100------//
				$product_input_array = array();
				
				
				
				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, 10, true);
					$sample_name_term = implode(',', array_map(
						function ($v, $k) { return sprintf("%s", $k, $v); },
						$term_in_name,
						array_keys($term_in_name)
					));
				}
				//---------Bullet Point Input 100------//
				
				if(preg_match("/bullet\_point/is",$content_type)){
					
					$avg_bullet_point = $top_100_data_array['avgbullet'];
					$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, 10, 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'];
					$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";
					}
					
					$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;
				
				
				RECHECKINSTANCE:
				
				$final_cmd = "gpts output:'{$content_type}' sku:'{$sku}' product_name:'{$product_name}' product_type:'{$product_type}' attr_finish:'{$attr_finish}' attr_dimension:'{$attr_dimension}' 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}' 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}'";
				
				file_put_contents($log_im, $final_cmd.PHP_EOL, FILE_APPEND);
				
				$content_type_count = count(explode(",", $content_type));
				
				
				
				$data = shell_exec($final_cmd);
				
				//file_put_contents($log_ot, $data.PHP_EOL, FILE_APPEND);
				
				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);
					
				}
				
				#print_R($date_json_decoded); die;
				
				$j = $i+1;
				$re_hit = 1;	
				
				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)){
							$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;
						}
					} 
					
					$cal = $cols[$j];
					
					$sheet->setCellValue($cal.$rowCount, $val);
					$sheet->getStyle($cal.$rowCount)->getAlignment()->setWrapText(true); 
					$rowm[$key_ex_n] = $val;
					
					
					$j++;
						
				}
				
				if($re_hit == 2 && $recount != 1){
					$recount = 1;
					goto RECHECKINSTANCE;
				}
				
				$products++;
				
				$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'];	
				
				$this->mdb->insert_data($collection_output , $rowm);
				
				$rowCount++;
			}
		}
		
		
		//----------Create Excel------------//
		
		
		$no_of_products = $products;
		if($rowCount > 3){
			$xl_filename = "cg_out_put_file_".date("mdy_his").".xlsx";
			$writer = new Xlsx($spreadsheet);
			$writer->save("/home/mysamm/public_html/content_api/excel_files/{$xl_filename}");
			
			$to = "keshpal.pss@gmail.com";
			$cc = null;
			$mailbcc = null;
			$from = "admin@mysamm.com";
			$subject = "Your Requested Content is Generated";
			$content = "Dear Client,\n\n";
			$content .= "We have completed your Content Generation Request and your data is ready.\n";
			$content .= "Please below link to download your report\n";
			$link = "http://169.46.176.94/content_api/excel_files/".$xl_filename;
			$content .= "<a href='$link'>New Content Report</a>\n\n";
			$content .= "Thank You,\n";
			$content .= "Admin mySamm";
			$content = nl2br($content);
			$status_array = sendmail_api($email, $subject, $content, $cc, $mailbcc, $from);
			
			$this->db->execute("UPDATE content_generation_data_requsets SET process_state = 3, no_of_products = $no_of_products, completion_tokens = $completionTokens, prompt_tokens = $promptTokens, report_url='$link' where id = $report_id");
			
			$this->db->execute("DELETE FROM recent_post_data where id = $post_id");
			
			
		}
	}
	#completionTokens,totalTokens,promptTokens
	
	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;		
	}
  

}

?>