<?php

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/MysqlDB/connection_master_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();
		
		$this->dbMaster = new ConnectionMaster();
		$this->dbPT = new ConnectionPT();
		
	}
	
	
	
	function generate_content($post_id, $collections, $website_id, $watch_dog = 0){
		
		$collection_output = preg_replace("/matched\_category\_list/is", "content_output", $collections);
		
		
		
		$data = $this->db->Query("SELECT * FROM recent_post_data_dev where id = $post_id");
		$report_id = $data[0]['report_id'];
		$user_id = $data[0]['user_id'];
		$include_item = $data[0]['include_item'];
		$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_dev 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'];
		
		
		$user_info = $this->dbMaster->Query("SELECT username,open_ai_key FROM users where id = $user_id");
		$api_key = $user_info[0]['open_ai_key'];
		if($api_key == ""){
			$api_key = "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";
		}
		
		
		$remove_punctuation = 0;
		if($website_id == 22){
			$remove_punctuation = 1;
		}
		
		$this->db->execute("UPDATE content_generation_reports_dev SET process_state = 2 where id = $report_id and user_id = $user_id");
		
		$this->db->execute("UPDATE content_generation_data_requsets_dev SET process_state = 2 where report_id = $report_id and website_id=$website_id");
		
		$existing_data = array();
		
		$filter = array('report_id'=>$report_id,'website_id'=>$website_id);
		$data = $this->mdb->Query($collections,$filter);
		
		if($watch_dog != 1){
			$this->mdb->delete_document($collection_output,$filter);
		}else{
			
			$filter = array('report_id'=>$report_id,'website_id'=>$website_id);
			$datass = $this->mdb->Query($collection_output,$filter);
			foreach($datass as $rowss){
				$rowmmm = (array) $rowss;
				$sku_key  = trim($rowmmm['sku']);
				$sku_key = strtolower($sku_key);
				$existing_data[$sku_key] = 1;
			}
		}
		
		$log_im = "/home/mysamm/public_html/content_api/api_logs/".$report_id."_".$website_id."_cmd_logs.txt";
		if(file_exists($log_im)){
			unlink($log_im);
		}
		
		$log_ot = "/home/mysamm/public_html/content_api/api_logs/".$report_id."_".$website_id."_out_put_logs.txt";
		
		$all_instances = array();
		$instance = 0;
		foreach($data as $row){
			$rowm = (array) $row;
			unset($rowm['_id']);
			$sku_key  = trim($rowm['sku']);
			$sku_key = strtolower($sku_key);
			if(!isset($existing_data[$sku_key])){	
				$user_id = $rowm['user_id'];
				$rowm['product_name_rules'] = $product_name_rules;
				$rowm['bullet_point_rules'] = $bullet_point_rules;
				$rowm['romance_copy_rules'] = $romance_copy_rules;
				$rowm['include_item'] = $include_item;
				$rowm['include_brand'] = $include_brand;
				$rowm['white_labeled'] = $white_labeled;
				$rowm['api_key'] = $api_key;
				$rowm['remove_punctuation'] = $remove_punctuation;
				$rowm['collection_output'] = $collection_output; 
				
				$data_array_sting = $this->encodeJson($rowm, true);
				$cmd = "nohup php /home/mysamm/public_html/content_api/generate_single_sku_data.php '{$report_id}' '{$website_id}' '{$data_array_sting}' >/dev/null 2>&1 & "; 
				$all_instances[$instance]= $cmd;
				$instance++;
			}
		}
		$this->run_instances(50, $all_instances, 'generate_single_sku_data.php');
	}
	
	
    

	function run_instances($instance = 10, $all_instance=array(), $check_running_instance = null){
		
		RECHECKINSTANCE:
		$running_instnances = exec("ps aux|grep '$check_running_instance' | grep -v 'grep' |wc -l");
		$count = 0;
		$loop = $instance - $running_instnances;
		$cmd = '';
		foreach($all_instance as $keys=>$command){
			if($running_instnances < $instance){
				shell_exec($command);
				$running_instnances++;
				unset($all_instance[$keys]);
			}
			$count++;
			if($loop==$count){
				break;
			}
		}
		if(count($all_instance) > 0){
			sleep(5);
			goto RECHECKINSTANCE;
		}
		
		return 1;
	} 

	
	public function encodeJson($responseData) {
		$jsonResponse = json_encode($responseData, JSON_INVALID_UTF8_IGNORE);
		return $jsonResponse;		
	}
  

}

?>