<?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($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");
		
		$report_id = $data[0]['report_id'];
		$user_id = $data[0]['user_id'];
		$website_id = $data[0]['website_id'];
		$post_data = $data[0]['post_data'];
		$not_include_item = $data[0]['include_item'];
		$not_include_brand = $data[0]['include_brand'];
		$white_labeled = $data[0]['white_labeled'];
		
		$user_rules = $this->db->Query("SELECT product_name_rules, bullet_point_rules, romance_copy_rules FROM user_website_configurations where user_id = $user_id and website_id = $website_id");
		
		
		
		$product_name_rules = $user_rules[0]['product_name_rules'];
		$bullet_point_rules = $user_rules[0]['bullet_point_rules'];
		$romance_copy_rules = $user_rules[0]['romance_copy_rules'];
		
		
		
		$api_key = "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";
		 
		$remove_punctuation = 0;
		if($website_id == 22){
			$remove_punctuation = 1;
		}
		$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->dbPT->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";
		if(file_exists($log_im)){
			unlink($log_im);
		}
		
		$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");

		$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", 61 => "BJ", 62 => "BK", 63 => "BL", 64 => "BM", 65 => "BN", 66 => "BO", 67 => "BP", 68 => "BQ", 69 => "BR", 70 => "BS", 71 => "BT", 72 => "BU", 73 => "BV", 74 => "BW", 75 => "BX", 76 => "BY", 77 => "BZ", 78 => "CA", 79 => "CB", 80 => "CC", 81 => "CD", 82 => "CE", 83 => "CF", 84 => "CG", 85 => "CH", 86 => "CI", 87 => "CJ", 88 => "CK", 89 => "CL", 90 => "CM", 91 => "CN", 92 => "CO", 93 => "CP", 94 => "CQ", 95 => "CR", 96 => "CS", 97 => "CT", 98 => "CU", 99 => "CV", 100 => "CW", 101 => "CX", 102 => "CY", 103 => "CZ");

			
		
		$additional_feilds_array = array();
		$additional_feilds_array_header = array();
		foreach($data as $row){
			$rowm = (array) $row;
			$content_type  = trim($rowm['content_type']);
			if(isset($rowm['additional_feilds'])){
				$additional_feilds_array  = json_decode($rowm['additional_feilds'], true);
				$additional_feilds_array_header = $additional_feilds_array;
			}
			$email  = trim($rowm['email']);
			break;
		}
		
		$header_array3 =  explode(",", $content_type);
		
		
		$rowCount = 3;
		$products = 0;
		$completionTokens = 0;
		$promptTokens = 0;
		$bbcount = 0;
		$bbmax_count = 0;
		$rcount  = 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);
				
			$input_key = "pc_rad_".$key_exist;
			if(isset($post_data_array[$input_key])){
				
				$cat_id = $rowm['category_id'] = $post_data_array[$input_key];
				$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);
				
				if(empty($top_100_data_array)){
					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);
					}
				}else{
					if(isset($ParentCategory[$cat_id])){
						$cate_name = $ParentCategory[$cat_id];
					}else{
						$cate_name = $SubCategory[$cat_id];
					}
				}
			  
				$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();
				if(isset($rowm['additional_feilds'])){
					//$rowm['additional_feilds'] = preg_replace("/\\\/is","",$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;
				//$content_type = "product_name,bullet_point,romance_copy";
				
				$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}'"; 
				
				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 == 1){ 
					$re_hit = 2;
					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++;
				
				$this->mdb->insert_data($collection_output , $rowm);
			}
		}
		
		
		//----------Create Excel------------//
		
		$spreadsheet = new Spreadsheet();
		
		$spreadsheet->getProperties()->setCreator('mySamm')
								 ->setTitle('cg')
								 ->setSubject('Content Generation');
								 
		//--------Create Sheet 1-----------//
		$sheet1 = $spreadsheet->getActiveSheet();
		$sheet1->setTitle('Sheet1');
		$sheet1->getColumnDimension("A")->setWidth(100);
		
		$richText = new RichText();
		$part1 = $richText->createTextRun('Important: Please Review the Generated Content Before Submitting to Retail Partners');
		$font1 = $part1->getFont();  // Get the font of the first text part
		$font1->setBold(true);  // Set bold font
		$font1->setColor(new Color(Color::COLOR_RED));  // Set red font color


		$part2 = $richText->createText("\nThis content was generated with the assistance of AI. Users should review and edit AI generated content to ensure accuracy, alignment with your brand’s voice, and any specific requirements your eCommerce partners may have. While AI can help streamline content creation, your final approval is crucial to ensure everything meets your standards. it’s important to note that AI output is not always perfect. In some cases, errors may occur due to the complexity of the system or data.");
		
		$part3 = $richText->createTextRun("Please note mySamm disclaims any and all liability for any errors or omission in the content produced  by our AI Content generator tool."); 
		$font2 = $part3->getFont();  // Get the font of the first text part
		$font2->setBold(true);  // Set bold font
		
		$sheet1->setCellValue('A1', $richText);
		$sheet1->getStyle('A1')->getAlignment()->setVertical(Alignment::VERTICAL_TOP);
		$sheet1->getStyle("A1")->getAlignment()->setWrapText(true);
		$sheet1->setCellValue("A2","Thank you for taking the time to thoroughly review this content before proceeding!");
		
		$sheet1->setCellValue('A4', 'Please click here to review your content!');
		$sheet1->getCell('A4')->getHyperlink()->setUrl('#Content!A1'); 
		$sheet1->getStyle('A4')->getFont()->setUnderline(true)->setColor(new \PhpOffice\PhpSpreadsheet\Style\Color(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_BLUE));
		
		$sheet1->getStyle('A1:Z1000')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('FFFFFF');
		
		#if($user_id == 371){
			$para_heading = "The following custom rules where provided to the AI engine when generating your content:";
			$sheet1->setCellValue('A9', $para_heading);
			$sheet1->getStyle('A9')->getFont()->setBold(true);
			
			$sheet1->setCellValue('A10', "Product Name");
			$product_name_rules_array = json_decode($product_name_rules, true);
			$row = 11;
			foreach($product_name_rules_array as $rules){
				$sheet1->setCellValue('A'.$row, $rules);
				$row++;
			}
			
			$row = $row+1;
			$sheet1->setCellValue('A'.$row, "Bullet Point");
			$bullet_point_rules_array = json_decode($bullet_point_rules, true);
			$row++;
			foreach($bullet_point_rules_array as $rules){
				$sheet1->setCellValue('A'.$row, $rules);
				$row++;
			}
			
			$row = $row+1;
			$sheet1->setCellValue('A'.$row, "Romance Copy");
			$romance_copy_rules_array = json_decode($romance_copy_rules, true);
			$row++;
			foreach($romance_copy_rules_array as $rules){
				$sheet1->setCellValue('A'.$row, $rules);
				$row++;
			}
		#}
		
		
		$sheet = $spreadsheet->createSheet();
		$sheet->setTitle('Content');
		#$sheet = $spreadsheet->getActiveSheet();
		
		
		$rowCount = 1;
				
		$sheet->setCellValue('A'.$rowCount, 'Input');
		
		
		
	
		$header_array2 = array("SKU/Model Number","Product Name","Product Type","Product Attribute Finish: Color/Finish","Product Attribute Dimensions", "Brand/White Label Value");
		 
		$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_header)){
			foreach($additional_feilds_array_header 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;
		
		$cal = $cols[$j];
		
		$sheet->setCellValue($cols[$j].'1', 'Output');
		
		
		
		$output_header_view = "Category Name";
		$sheet->setCellValue($cal.$rowCount, $output_header_view);
		$sheet->getColumnDimension($cal)->setWidth(35);
		$sheet->getStyle($cal.$rowCount)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('6491F8'); 
			
		$sheet->getStyle($cal."1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('6491F8'); 
		
		
		
		$j = $i+2; 
		
		$p = $bl = $r = 0;
		foreach($header_array3 as $output_header){ 
			
			$cal = $cols[$j];
			if($output_header == "product_name"){
				$p = 1;
				$sheet->getColumnDimension($cal)->setWidth(40);
				$output_header_view = "New Product Name";
				$sheet->setCellValue($cal.$rowCount, $output_header_view);
				
				$sheet->getStyle($cal.$rowCount)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('6491F8'); 
					
				$sheet->getStyle($cal."1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('6491F8'); 

				$j++;
			}else if($output_header == "bullet_point"){
				$bl = 1;
				for($b = 1; $b <= $bbmax_count; $b++){
					$output_header_view = "Bullet Point $b";
					$cal = $cols[$j];
					$sheet->setCellValue($cal.$rowCount, $output_header_view);
					$sheet->getStyle($cal.$rowCount)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('6491F8'); 
					
					$sheet->getStyle($cal."1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('6491F8'); 
					$sheet->getColumnDimension($cal)->setWidth(30);
					$j++;
				}
				$output_header_view = "New Bullet Points";
				
			}else if($output_header == "romance_copy"){
				$r = 1;
				$sheet->getColumnDimension($cal)->setWidth(70);
				$output_header_view = "New Romance Copy/Description";
				
				$sheet->getStyle($cal.$rowCount)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('6491F8'); 
					
				$sheet->getStyle($cal."1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('6491F8'); 
				
				$sheet->setCellValue($cal.$rowCount, $output_header_view);
				$j++;
			}
		}
		
		
		$filter = array('report_id'=>$report_id);
		$data = $this->mdb->Query($collection_output,$filter);
		$additional_feilds_array = array();
		
		$rowCount = 3;
		
		foreach($data as $row){
			
			$i = 0;
			$rowm = (array) $row;
			
			$rowm['sku'] = str_replace('\\', '',$rowm['sku']);
			$rowm['product_name'] = str_replace('\\', '',$rowm['product_name']);
			$rowm['product_type'] = str_replace('\\', '',$rowm['product_type']);
			$rowm['attr_finish'] = str_replace('\\', '',$rowm['attr_finish']);
			$rowm['attr_dimension'] = str_replace('\\', '',$rowm['attr_dimension']);
			$rowm['brand'] = str_replace('\\', '',$rowm['brand']);
			
			$cal = $cols[$i];
			$sheet->setCellValue($cal.$rowCount, $rowm['sku']);
			
			$i = $i+1;
			$cal = $cols[$i];			
			
			$sheet->setCellValue($cal.$rowCount, $rowm['product_name']);
			
			$i = $i+1;
			$cal = $cols[$i];
			$sheet->setCellValue($cal.$rowCount, $rowm['product_type']);
			
			$i = $i+1;
			$cal = $cols[$i];
			$sheet->setCellValue($cal.$rowCount, $rowm['attr_finish']);
			
			$i = $i+1;
			$cal = $cols[$i];
			$sheet->setCellValue($cal.$rowCount, $rowm['attr_dimension']);
			
			$i = $i+1;
			$cal = $cols[$i];
			$sheet->setCellValue($cal.$rowCount, $rowm['brand']);
			
			$additional_feilds = $rowm['additional_feilds']; 
			
			$avg_bullet_point = $rowm['avg_bullet_point'];
			
			$additional_feilds_array = json_decode($additional_feilds, true);
			if(!empty($additional_feilds_array_header)){
				$i = $i+1;
				foreach($additional_feilds_array_header as $input_header=>$vll){
					$cal = $cols[$i];
					$vl = "";
					if(isset($additional_feilds_array[$input_header])){
						$vl = $additional_feilds_array[$input_header];
					}
					$vl = str_replace('\\', '',$vl);
					$sheet->setCellValue($cal.$rowCount, $vl);
					$i++;
				}
				
				$additional_data = json_encode($additional_feilds_array, true); 
			}else{
				$i = $i+1;
			}
			
			
			$i = $i+1;
			$cal = $cols[$i];	
			if($bl == 1){
				$category_name_string = $rowm['cate_name']. " - Avg $avg_bullet_point Bullet Points";  
			}else{
				$category_name_string = $rowm['cate_name'];  
			}			
			
			$sheet->setCellValue($cal.$rowCount, $category_name_string);
			
			
			if($p == 1){
				$i = $i+1;
				$cal = $cols[$i];
				$sheet->setCellValue($cal.$rowCount, $rowm['product_name_new']);
			}
			
			if($bl == 1){
				$i = $i+1;
				$bullet_points_array = explode("\n", $rowm['bullets_points_new']);
				$k = 0;
				for($b = 1; $b <= $bbmax_count; $b++){
					$cal = $cols[$i];
					$sheet->setCellValue($cal.$rowCount, $bullet_points_array[$k]);
					$i++;
					$k++;
				}
			}
			
			if($r == 1){
				$i = $i;
				if($bl != 1){
					$i = $i+1; 
				}
				
				$cal = $cols[$i];
				$sheet->setCellValue($cal.$rowCount, $rowm['product_description_new']);  
			}
			$rowCount++;
		}
		
		$no_of_products = $products;
		if($rowCount > 2){ 
			$spreadsheet->setActiveSheetIndex(0);
			$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 = "keshpal.pss@gmail.com";
			$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 = "https://msurlcenter.com/content_api/excel_files/".$xl_filename;
			$content .= "<a href='$link'>New Content Report</a>\n";
			$content .= "<p style='color:red;'><b>Important: Please Review the Generated Content Before Submitting to Retail Partners</b></p>";

			$content .= "<p>This content was generated with the assistance of AI. Users should review and edit AI generated content to ensure accuracy, alignment with your brand’s voice, and any specific requirements your eCommerce partners may have. While AI can help streamline content creation, your final approval is crucial to ensure everything meets your standards.  it’s important to note that AI output is not always perfect. In some cases, errors may occur due to the complexity of the system or data.<b> Please note mySamm disclaims any and all liability for any errors or omission in the content produced by our AI Content generator tool. </b></p>";

			$content .= "<p>Thank you for taking the time to thoroughly check this content before proceeding!</p>";
			
			$content .= "Thank You,\n";
			$content .= "mySamm Team";
			$content = nl2br($content);
			$status_array = sendmail_api($email, $subject, $content, $cc, $mailbcc, $from);
			
			$input = 0.150/1000000;
			$output = 0.600/1000000;
			
			$input = 0.00003;
			$output = 0.00006;
			$est_input_cost	= $promptTokens * $input;
			$out_est_cost = $completionTokens * $output;
			$est_total_cost	 = $est_input_cost+$out_est_cost;
			
			$est_input_cost = round($est_input_cost, 8);
			$out_est_cost = round($out_est_cost, 8);
			$est_total_cost = round($est_total_cost, 8);
			
			$this->db->execute("UPDATE content_generation_data_requsets SET `process_state` = 3, `no_of_products` = '$no_of_products', `completion_tokens` = '$completionTokens', `prompt_tokens` = '$promptTokens', `est_input_cost` = '$est_input_cost', `out_est_cost` = '$out_est_cost', `est_total_cost` = '$est_total_cost' , `report_url`='$link' where id = $report_id");
			
			
			$this->db->Query("UPDATE user_website_configurations SET product_name_rules = '', bullet_point_rules ='', romance_copy_rules='' where user_id = $user_id and website_id = $website_id AND rule_saved=0");
			
			#$this->db->execute("DELETE FROM recent_post_data where id = $post_id"); 
			
			
		}
	}
	
	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;		
	}
  

}

?>