<?php
require_once APPPATH.'libraries/aws/vendor/autoload.php'; 
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

class Upload extends CI_Controller {

    // Columns names after parsing
    private $fields;
    // Separator used to explode each line
    private $separator = ',';
    // Enclosure used to decorate each field
    private $enclosure = '"';
    // Maximum row size to be used for decoding
    private $max_row_size = 4096;

        public function __construct()
        {
                parent::__construct();
                // $this->load->helper(array('form', 'url'));
        }

        public function index()
        {
                // $this->load->view('upload_form', array('error' => ' ' ));
        }
        public function do_upload_2()
        {
            
            // debug($_FILES,1);
            if(empty($_FILES)){
            // debug($_SESSION);
            //     debug($_POST,1);
                    // $again = self::sav_up4();
                    $param['again'] = $again;
                    $param['status'] = 1;
                    $param['txt'] = 'Success';
            }
            else
            {
                $config['upload_path'] = FCPATH . 'assets/uploads/'.$_SERVER["QUERY_STRING"];
                $config['allowed_types'] = 'csv';
                $config['file_name'] = 'import_'.$_SERVER["QUERY_STRING"].'_'.date('Y-m-d_H:i:s');
                $this->load->library('upload', $config);
                $this->upload->initialize($config);

                if ( ! $this->upload->do_upload('userfile'))
                {
                    $error = array('error' => $this->upload->display_errors());
                    $param['status'] = 0;
                    $param['txt'] = $error['error'];
                }
                else
                {
                    // $this->db->truncate('fb_product');
                    $data = array('upload_data' => $this->upload->data());
                    // $in = $_FILES['userfile']['name'];
                    $in = $config['file_name'];
                    $param['again'] = $again;
                    $param['status'] = 1;
                    $param['txt'] = 'Update in progress, please login again to view progress....';
                    $again = self::sav_up_inprog($in);
                    $param['again'] = $again;
                    $param['status'] = 1;
                    $param['txt'] = 'Success';
                    
                }
            }
                // debug($param,1);
                echo json_encode($param);
        }
        
        public function do_upload(){
            // debug($FILES,1);
//             header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
// header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// header("Cache-Control: no-store, no-cache, must-revalidate");
// header("Cache-Control: post-check=0, pre-check=0", false);
// header("Pragma: no-cache");


// Support CORS
// header("Access-Control-Allow-Origin: *");
// // other CORS headers if any...
// if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
// 	exit; // finish preflight CORS requests here
// }


// 5 minutes execution time
@set_time_limit(5 * 60);

// Uncomment this one to fake upload time
// usleep(5000);

// Settings
// $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";

$targetDir = FCPATH . 'assets/uploads/' . $_SERVER["QUERY_STRING"];
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 5 * 3600; // Temp file age in seconds

// Create target dir
if (!file_exists($targetDir)) {
	@mkdir($targetDir);
}

// Get a file name
if (isset($_REQUEST["name"])) {
	$fileName = $_REQUEST["name"];
} elseif (!empty($_FILES)) {
	$fileName = $_FILES["file"]["name"];
} else {
	$fileName = uniqid("file_");
}

// $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

// Chunking might be enabled
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;


// Remove old temp files	
if ($cleanupTargetDir) {
	if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
		die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
	}

	while (($file = readdir($dir)) !== false) {
		$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

		// If temp file is current file proceed to the next
		if ($tmpfilePath == "{$filePath}.part") {
			continue;
		}

		// Remove temp file if it is older than the max age and is not the current file
		if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
			@unlink($tmpfilePath);
		}
	}
	closedir($dir);
}	


// Open temp file
if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
	die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
}

if (!empty($_FILES)) {
	if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
		die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
	}

	// Read binary input stream and append it to temp file
	if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
		die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
	}
} else {	
	if (!$in = @fopen("php://input", "rb")) {
		die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
	}
}

while ($buff = fread($in, 4096)) {
	fwrite($out, $buff);
}
// debug($out,1);

@fclose($out);
@fclose($in);

// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
	// Strip the temp .part suffix off 
	$iii = 'import_'.$_SERVER["QUERY_STRING"].'_'.date('Y-m-d_H:i:s');
	rename("{$filePath}.part", $targetDir. DIRECTORY_SEPARATOR . $iii . '.csv');
	
// echo ('{"jsonrpc" : "2.0", "result" : ye, "id" : "id"}');

    $param['again'] = $again;
                    $param['status'] = 1;
                    $param['txt'] = 'Update in progress, please wait..';
                    $again = self::sav_up_inprog($iii);
                    $param['again'] = $again;
                    $param['status'] = 1;
                    // $param['txt'] = 'Success';
                    // echo "Admin.toastr.success()";
                // session_destroy();
                echo json_encode($param);
}

// Return Success JSON-RPC response
// echo ('{"jsonrpc" : "2.0", "result" : ye, "id" : "id"}');

// $in = $config['file_name'];
                    // $param['again'] = $again;
                    // $param['status'] = 1;
                    // $param['txt'] = 'Update in progress, please login again to view progress....';
                    // $again = self::sav_up_inprog($in);
                    // $param['again'] = $again;
                    // $param['status'] = 1;
                    // $param['txt'] = 'Success';
        }

        // public function do_upload()
        // {
            
        //     // debug($_FILES,1);
        //     if(empty($_FILES)){
        //     // debug($_SESSION);
        //     //     debug($_POST,1);
        //             // $again = self::sav_up4();
        //             $param['again'] = $again;
        //             $param['status'] = 1;
        //             $param['txt'] = 'Success';
        //     }
        //     else
        //     {
        //         $config['upload_path'] = FCPATH . 'assets/uploads/'.$_SERVER["QUERY_STRING"];
        //         $config['allowed_types'] = 'csv';
        //         $config['file_name'] = 'import_'.$_SERVER["QUERY_STRING"].'_'.date('Y-m-d_H:i:s');
        //         $this->load->library('upload', $config);
        //         $this->upload->initialize($config);

        //         if ( ! $this->upload->do_upload('userfile'))
        //         {
        //             $error = array('error' => $this->upload->display_errors());
        //             $param['status'] = 0;
        //             $param['txt'] = $error['error'];
        //         }
        //         else
        //         {
        //             // $this->db->truncate('fb_product');
        //             $data = array('upload_data' => $this->upload->data());
        //             // $in = $_FILES['userfile']['name'];
        //             $in = $config['file_name'];
        //             $param['again'] = $again;
        //             $param['status'] = 1;
        //             $param['txt'] = 'Update in progress, please login again to view progress....';
        //             $again = self::sav_up_inprog($in);
        //             $param['again'] = $again;
        //             $param['status'] = 1;
        //             $param['txt'] = 'Success';
                    
        //         }
        //     }
        //         // debug($param,1);
        //         echo json_encode($param);
        // }
        
        public function sav_up_inprog2($in)       
        {
            $in = str_replace(" ","_",$in);
            
            $fil = base_url().'assets/uploads/'.$_SERVER["QUERY_STRING"].'/'.$in.'.csv';
            // $fil = base_url().'assets/uploads/product/import_product_2022-07-25_23:02:56.csv';
            
            
            
        // Open uploaded CSV file with read-only mode
        $csvFile = fopen($fil, 'r');
        
        // Get Fields and values
        $this->fields = fgetcsv($csvFile, $this->max_row_size, $this->separator, $this->enclosure);
        // $keys_values = explode(',', $this->fields[0]);
        $keys = $this->escape_string($this->fields);
        
        // debug($keys,1);
        // Store CSV data in an array
        $csvData = array();
        $i = 0;
        while(($row = fgetcsv($csvFile, $this->max_row_size, $this->separator, $this->enclosure)) !== FALSE){
            // Skip empty lines

            if($row != NULL){
                // $values = explode(',', $row[0]);

                if(count($keys) == count($row)){
                    $arr        = array();
                    $new_values = array();
                    $new_values = $this->escape_string($row);
                    for($j = 0; $j < count($keys); $j++){
                        if($keys[$j] != ""){
                            $arr[$keys[$j]] = $new_values[$j];
                        }
                    }
                    $csvData[$i] = $arr;

                    $i++;
                    
                }
            }
        }
        // Close opened CSV file
        fclose($csvFile);
        
                // if($_SERVER["QUERY_STRING"]=="product")
                // {
                    // foreach($csvData as $key => $val):
                    //     if(!isset($csvData[$key]['product_slug']))
                    //     {
                            
                    // /*Set product name*/
                    // $csvData[$key]['product_name'] = $csvData[$key]['product_partno'].' | '.$csvData[$key]['product_name'].'-'.$csvData[$key]['product_condition'];

                    //         $csvData[$key]['product_slug'] = str_replace(array(' ','|','/','.','---','(',')','+','--'),array('-','-','-','-','-','-','-','-','-'),strtolower($csvData[$key]['product_name']));
                    // /*Set Product URL*/
                    // $csvData[$key]['product_url'] = $csvData[$key]['product_slug'];
                    //     }
                    //     else{
                    //         $csvData[$key]['product_slug'] = str_replace(array(' ','|','/','.','---','(',')','+','--'),array('-','-','-','-','-','-','-','-','-'),strtolower($csvData[$key]['product_slug']));
                    //     }
                    //     if(empty($csvData[$key]['product_sku'])){
                    //         $param001['order'] = 'product_id DESC';
                    //         $dat0 = $this->model_product->find_one($param001);
                    //         $lastid = $dat0['product_id'];
                    //         $csvData[$key]['product_sku'] = 'CRISP-'.strtotime('now');
                    //     }
                    //     // debug($csvData[$key]['product_image'],1);
                    //     $csvData[$key]['product_image_path'] = 'https://d3djghvtckqcal.cloudfront.net/';
                    // if(strpos($csvData[$key]['product_image'],'https') !== false){
                            
                    // // Remote image URL
                    // $url = $csvData[$key]['product_image'];
                    // // Image Name
                    // $imgName = strtotime('now').'.png';
                    // // Image path + Name
                    // $imgPath = 'assets/uploads/product/'.$imgName;
                    // // Save image on local server
                    // $result = file_put_contents($imgPath, file_get_contents($url));

                    // /////////// Setting csv data before upload according to the need////////
                    // /*Set image name*/
                    // $csvData[$key]['product_image'] = 'ciimages/'.$imgName;
                    // /*Set meta title if not found*/
                    // $csvData[$key]['product_meta_title'] == '' ? $csvData[$key]['product_meta_title'] = $csvData[$key]['product_name'] : $csvData[$key]['product_meta_title'] = $csvData[$key]['product_meta_title'] ;
                    // /*Set Refurb price to 20% lower than new if is highr than new price */
                    // //---------------UPLOAD IMAGE ON AWS-------------------//
                    // $s3 = new S3Client([ 
                    //     'credentials' => [ 
                    //         'key' => 'AKIATRNBES3D6KIXQOM6', 
                    //         'secret' => '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'
                    //     ], 
                    //     'version' => 'latest', 
                    //     'region' => 'us-east-1'
                    // ]); 
                    //     try{
                    //         $s3->putObject(array(
                    //                 'Bucket'=> 'crisptechllc',
                    //                 'Key' =>  'ciimages/'.$imgName,
                    //                 'Body' => file_get_contents('assets/uploads/product/'.$imgName),
                    //                 // 'ContentLength' => filesize($result),
                    //                 'StorageClass' => 'STANDARD'
                    //         ));
                    //         unlink('assets/uploads/product/'.$imgName);
                    //     }
                    //     catch(S3Exception $e)
                    //     {
                    //         echo $e->getMessage() . "\n";
                    //     }
                    // }
                    
                    // /*Adjust import category/manufacturer id*/
                    // $csvData[$key]['product_category_id'] = end(explode('|', $csvData[$key]['product_category_id'])); 
                    // $csvData[$key]['product_manufacturer_id'] = end(explode('|', $csvData[$key]['product_manufacturer_id'])); 
                    // endforeach;
                // }
                ////////////////////////Generate queue for inserting data///////////
                $param003['queue_name'] = "Update/Insert Products";
                $param003['queue_status'] = 3;
                $param003['queue_percentage'] = 0;
                $param003['queue_createdon'] = date('Y-m-d H:i:s');
                $this->model_queue->set_attributes($param003);
                $data003 = $this->model_queue->save();
                /////////////////////Queue creation ends here//////////////
                // $this->db->truncate('fb_'.$_SERVER["QUERY_STRING"]);
                // session_destroy();
                $d=array();
                foreach($csvData as $key => $val){
                    array_push($d,$val['product_sku']);
                    // $da[$key]['product_sale_price'] = $val['product_sale_price'];
                    // $da[$key]['product_price'] = $val['product_price'];
                }
                
                    $pa['where_in']['product_sku'] = $d;
                    $da = $this->model_product->find_all($pa);
                    session_destroy();
                    $acc = count($da);
                    $lim =10;

                foreach($csvData as $key => $val){
                    // $da[$key]['product_sale_price'] = $val['product_sale_price'];
                    // $da[$key]['product_price'] = $val['product_price'];
                    $dt = $this->db->query("UPDATE `fb_product` SET `product_price`=".$val['product_price'].",`product_sale_price`=".$val['product_sale_price']." WHERE `product_sku`='".$val['product_sku']."'");
                    if($dt)
                    {
                        // $param004['queue_percentage'] = ceil(($key/count($csvData))*100);
                        // $data004 = $this->model_queue->update_by_pk($data003,$param004);
                    }
                    else{
                        echo 'failed';
                        return;
                    }
                }
                // $abc = array_chunk($csvData,3);
                // debug(count($da),1);
                // debug(count($abc),1);
                // foreach($da as $key => $val){
                //     try{
                //         // $data007 = $this->model_product->update_by_pk($val['product_id'],$val);
                //         // debug($val,1);
                //         // $this->db->insert('fb_'.$_SERVER["QUERY_STRING"], $val);
                //         // $param007['product_id'] = $val['product_id'];
                //         // $data007 = $this->model_product->insert_if_not_found_or_update($val, $param007);

                //         // $dt = $this->db->query("UPDATE `fb_product` SET `product_price`=".$val['product_price'].",`product_sale_price`=".$val['product_sale_price']." WHERE `product_id`=".$val['product_id']);
                //         // debug($val['product_sku'].' => '.$dt);
                //         // $this->db->where('product_id', $val['product_id']);
                //         // $aa = $this->db->update('fb_product', $val);
                        
                // // debug($aa);
                // // debug($val,1);
                //         // $dt = $this->db->query("UPDATE `fb_product` SET `product_price`='".$val['product_price'].'",`product_sale_price`='".$val['product_sale_price']."' WHERE `product_id`='".$val['product_id'].'"");
                //         // $param004['queue_percentage'] = ceil(($key/count($csvData))*100);
                //         // $data004 = $this->model_queue->update_by_pk($data003,$param004);
                //     }
                //     catch(Exception $e)
                //     {
                //         $param1['status'] = 0;
                //         $param1['txt'] = $e->getMessage();
                //         echo json_encode($param1);
                //         exit;
                //     }
                // }
                        $param004['queue_percentage'] = 100;
                        $param004['queue_status'] = 4;
                        $data004 = $this->model_queue->update_by_pk($data003,$param004);
                // debug('done',1);
                    // $param001['group'] = 'product_partno';
                    // $param001['having'] = 'COUNT(*)>1';
                    // $param001['fields'] = 'product_partno';
                    // $data001 = $this->db->query("SELECT * FROM `fb_product` group BY `product_partno` HAVING count(*)>1")->result_array();
                    // $mid =array();
//                     if(count($data001)>0){
//                         foreach($data001 as $key => $val):
//                             array_push($mid,$val['product_partno']);
//                         endforeach;
//                             $param002['where_in']['product_partno'] = $mid;
//                             $param002['where']['product_condition'] = 'New';
//                             $param002['fields'] = 'product_id,product_partno,product_sale_price,product_condition';
//                             $param002['group_field'] = 'product_partno';
//                             $data002[] = $this->model_product->find_all($param002);

//                             $param0020['where_in']['product_partno'] = $mid;
//                             $param0020['where']['product_condition'] = 'Ref';
//                             $param0020['fields'] = 'product_id,product_partno,product_sale_price,product_condition';
//                             $param0020['group_field'] = 'product_partno';
//                             $data0020[] = $this->model_product->find_all($param0020);
// // debug(count($data002[0]));debug(count($data0020[0]),1);
//                             // if($a >= 50){
//                             // debug($data002,1);
//                         // }
//                             // debug($this->db->last_query(),1);
//                         // endforeach;
// // debug(count($data002[0]),1);   
//                         foreach($data0020[0] as $key => $val):
//                             // foreach($val as $key2 => $val2):
//                                 $compare[$key]['Ref']['product_id'] = $val['product_id'];
//                                 $compare[$key]['Ref']['product_sale_price'] = $val['product_sale_price'];

//                                 $compare[$key]['New']['product_id'] = $key;
//                                 $compare[$key]['New']['product_sale_price'] = $data002[0][$key]['product_sale_price'];
//                             endforeach;
//                             // debug($compare,1);

//                             foreach($compare as $key => $val):
//                             if($compare[$key]['Ref']['product_sale_price']>$compare[$key]['New']['product_sale_price'])
//                             {
//                                 $per = (intval($compare[$key]['New']['product_sale_price'])/100)*20;
//                                 // debug($compare[$key]);
//                                 $fin_ref = intval($compare[$key]['New']['product_sale_price']) - $per;
//                                 $compare[$key]['Ref']['product_sale_price'] = $fin_ref;
//                                 // debug($fin_ref,1);
//                                 $update001 = $this->model_product->update_by_pk($compare[$key]['Ref']['product_id'],$compare[$key]['Ref']);
//                                 // debug($update001);
//                             }
//                             $param006['queue_percentage'] = ceil(($key/count($data001))*50)+50;
//                             $data005 = $this->model_queue->update_by_pk($data003,$param006);
//                         endforeach;
                    
//                     $param006['queue_percentage'] = 100;
//                     $param006['queue_status'] = 4;
//                     $data005 = $this->model_queue->update_by_pk($data003,$param006);
//                     }
                    unlink('assets/uploads/product/'.$in.'.csv');
                return $again;
            }
            
public function update_pricing(){
                     $param001['group'] = 'product_partno';
                    $param001['having'] = 'COUNT(*)>1';
                    $param001['fields'] = 'product_partno';
                    $data001 = $this->db->query("SELECT * FROM `fb_product` group BY `product_partno` HAVING count(*)>1")->result_array();
                    $mid =array();
                    if(count($data001)>0){
                        foreach($data001 as $key => $val):
                            array_push($mid,$val['product_partno']);
                        endforeach;
                            $param002['where_in']['product_partno'] = $mid;
                            $param002['where']['product_condition'] = 'New';
                            $param002['fields'] = 'product_id,product_partno,product_sale_price,product_condition';
                            $param002['group_field'] = 'product_partno';
                            $data002[] = $this->model_product->find_all($param002);

                            $param0020['where_in']['product_partno'] = $mid;
                            $param0020['where']['product_condition'] = 'Ref';
                            $param0020['fields'] = 'product_id,product_partno,product_sale_price,product_condition';
                            $param0020['group_field'] = 'product_partno';
                            $data0020[] = $this->model_product->find_all($param0020);
// debug(count($data002[0]));debug(count($data0020[0]),1);
                        foreach($data0020[0] as $key => $val):
                            // foreach($val as $key2 => $val2):
                                $compare[$key]['Ref']['product_id'] = $val['product_id'];
                                $compare[$key]['Ref']['product_sale_price'] = $val['product_sale_price'];

                                $compare[$key]['New']['product_id'] = $data002[0][$key]['product_id'];
                                $compare[$key]['New']['product_sale_price'] = $data002[0][$key]['product_sale_price'];
                            endforeach;
                        //     // debug($compare,1);

                            foreach($compare as $key => $val):
                            if($compare[$key]['Ref']['product_sale_price'] >= $compare[$key]['New']['product_sale_price'])
                            {
                                $per = (intval($compare[$key]['Ref']['product_sale_price'])/100)*20;
                                debug('Old price: '.$compare[$key]['New']['product_sale_price']);
                                $fin_ref = intval($compare[$key]['Ref']['product_sale_price']) + $per;
                                $compare[$key]['New']['product_sale_price'] = $fin_ref;
                                $compare[$key]['New']['product_price'] = $compare[$key]['New']['product_sale_price'] + ($compare[$key]['New']['product_sale_price'] * 0.1);
                                debug('Product ID: '.$compare[$key]['New']['product_id']);
                                debug('Calculated new price: '.$compare[$key]['New']['product_price']);
                                debug('Calculated new sale price: '.$compare[$key]['New']['product_sale_price']);
                                // debug($compare[$key]['Ref']);
                                // debug($compare[$key]['New']);
                                // debug($fin_ref);
                                $update001  = $this->db->query("UPDATE `fb_product` SET `product_price`=".$compare[$key]['New']['product_price'].",`product_sale_price`=".$compare[$key]['New']['product_sale_price']." WHERE `product_id`='".$compare[$key]['New']['product_id']."'");
                    
                                // $update001 = $this->model_product->update_by_pk($compare[$key]['New']['product_id'],$compare[$key]['New']['product_sale_price']);
                                // debug($this->db->last_query(),1);
                                if($update001){
                                    debug($compare[$key]['New']['product_id'].' '.'Done');
                                }
                                else{
                                    debug('failed');
                                }
                            }
                        endforeach;
                        echo "done";
    }
    
}

        public function sav_up_inprog($in)       
        {
            $in = str_replace(" ","_",$in);
            
            $fil = base_url().'assets/uploads/'.$_SERVER["QUERY_STRING"].'/'.$in.'.csv';
            // $fil = base_url().'assets/uploads/product/import_product_2022-07-25_23:02:56.csv';
            
            // debug($in,1);
            
            
        // Open uploaded CSV file with read-only mode
        $csvFile = fopen($fil, 'r');
        
        // Get Fields and values
        $this->fields = fgetcsv($csvFile, $this->max_row_size, $this->separator, $this->enclosure);
        // $keys_values = explode(',', $this->fields[0]);
        $keys = $this->escape_string($this->fields);
        // Store CSV data in an array
        // debug($keys,1);
        $csvData = array();
        $i = 0;
        while(($row = fgetcsv($csvFile, $this->max_row_size, $this->separator, $this->enclosure)) !== FALSE){
            // Skip empty lines
            // debug($row);
            if($row != NULL){
                // $values = explode(',', $row[0]);
                // debug($keys);
                if(count($keys) == count($row)){
                    $arr        = array();
                    $new_values = array();
                    $new_values = $this->escape_string($row);
                    for($j = 0; $j < count($keys); $j++){
                        if($keys[$j] != ""){
                            $arr[$keys[$j]] = $new_values[$j];
                        }
                    }
                    $csvData[$i] = $arr;
                    // debug($arr,1);
                    $i++;
                    
                }
            }
            // if($i < 10)
            //         {
            //             debug($csvData,1);
            //         }
        }
        // Close opened CSV file
        fclose($csvFile);
        
        // debug($csvData,1);
            
            
              //////    insert finsished//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //   foreach($result[0] as $key => $val)
            //   {
            //     // $cus[] = 'product_'.$val;
            //     $cus[] = $val;
            //   }
            //   $cus[0] = ' ';
            //     $_SESSION['tot'] = count($result);
            //     $again = 0;
            //     foreach($result as $key => $val){
            //         foreach($val as $key2 => $val2){
            //             if($key2 == ' '){}
            //             else{
            //                 $param[$key][($cus[$key2])] = trim($val2);
            //             }
            //         }
            //         // debug($param,1);
            //     }
                // unset($param[0]);
                if($_SERVER["QUERY_STRING"]=="product")
                {
                    // foreach($csvData as $key => $val):
                        // if(!isset($csvData[$key]['product_slug']))
                        // {
                            
                    /*Set product name*/
                    // $csvData[$key]['product_name'] = $csvData[$key]['product_partno'].' | '.$csvData[$key]['product_name'].'-'.$csvData[$key]['product_condition'];

                            // $csvData[$key]['product_slug'] = str_replace(array(' ','|','/','.','---','(',')','+','--'),array('-','-','-','-','-','-','-','-','-'),strtolower($csvData[$key]['product_name']));
                    /*Set Product URL*/
                    // $csvData[$key]['product_url'] = $csvData[$key]['product_slug'];
                            // $csvData[$key]['product_slug'] = $csvData[$key]['product_slug'] .'-' . $csvData[$key]['product_condition'];
                            // $csvData[$key]['product_slug'] = str_replace('--','-',$csvData[$key]['product_slug']);
                            // $csvData[$key]['product_slug'] = str_replace('(','',$csvData[$key]['product_slug']);
                            // $csvData[$key]['product_slug'] = str_replace(')','',$csvData[$key]['product_slug']);
                            // debug ($csvData[$key]['product_slug'],1);
                }
                        // else{
                        //     $csvData[$key]['product_slug'] = str_replace(array(' ','|','/','.','---','(',')','+','--'),array('-','-','-','-','-','-','-','-','-'),strtolower($csvData[$key]['product_slug']));
                        //     // $csvData[$key]['product_slug'] = str_replace('--','-',$csvData[$key]['product_slug']);
                        //     // $csvData[$key]['product_slug'] = str_replace('(','',$csvData[$key]['product_slug']);
                        //     // $csvData[$key]['product_slug'] = str_replace(')','',$csvData[$key]['product_slug']);
                        // }
                        // if(empty($csvData[$key]['product_sku'])){
                        //     $param001['order'] = 'product_id DESC';
                        //     $dat0 = $this->model_product->find_one($param001);
                        //     $lastid = $dat0['product_id'];
                        //     $csvData[$key]['product_sku'] = 'CRISP-'.strtotime('now');
                        // }
                        // debug($csvData[$key]['product_image'],1);
                        // $csvData[$key]['product_image_path'] = 'https://d3djghvtckqcal.cloudfront.net/';
                    // if(strpos($csvData[$key]['product_image'],'https') !== false){
                            
                    // Remote image URL
                    // $url = $csvData[$key]['product_image'];
                    // // Image Name
                    // $imgName = strtotime('now').'.png';
                    // // Image path + Name
                    // $imgPath = 'assets/uploads/product/'.$imgName;
                    // // Save image on local server
                    // $result = file_put_contents($imgPath, file_get_contents($url));

                    /////////// Setting csv data before upload according to the need////////
                    /*Set image name*/
                    // $csvData[$key]['product_image'] = 'ciimages/'.$imgName;
                    // /*Set meta title if not found*/
                    // $csvData[$key]['product_meta_title'] == '' ? $csvData[$key]['product_meta_title'] = $csvData[$key]['product_name'] : $csvData[$key]['product_meta_title'] = $csvData[$key]['product_meta_title'] ;
                    /*Set Refurb price to 20% lower than new if is highr than new price */
                    //---------------UPLOAD IMAGE ON AWS-------------------//
                    // $s3 = new S3Client([ 
                    //     'credentials' => [ 
                    //         'key' => 'AKIATRNBES3D6KIXQOM6', 
                    //         'secret' => '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'
                    //     ], 
                    //     'version' => 'latest', 
                    //     'region' => 'us-east-1'
                    // ]); 
                    //     try{
                    //         $s3->putObject(array(
                    //                 'Bucket'=> 'crisptechllc',
                    //                 'Key' =>  'ciimages/'.$imgName,
                    //                 'Body' => file_get_contents('assets/uploads/product/'.$imgName),
                    //                 // 'ContentLength' => filesize($result),
                    //                 'StorageClass' => 'STANDARD'
                    //         ));
                    //         unlink('assets/uploads/product/'.$imgName);
                    //     }
                    //     catch(S3Exception $e)
                    //     {
                    //         echo $e->getMessage() . "\n";
                    //     }
                    // }
                    
                    /*Adjust import category/manufacturer id*/
                    // debug(explode('|', $csvData[$key]['product_category_id']));
                    // $csvData[$key]['product_category_id'] = end(explode('|', $csvData[$key]['product_category_id'])); 
                    // $csvData[$key]['product_manufacturer_id'] = end(explode('|', $csvData[$key]['product_manufacturer_id'])); 
                    // debug($csvData[$key]['product_category_id'],1);
                    // endforeach;
                // }
                ////////////////////////Generate queue for inserting data///////////
                $param003['queue_name'] = "Insert Products";
                $param003['queue_status'] = 3;
                $param003['queue_percentage'] = 0;
                $param003['queue_createdon'] = date('Y-m-d H:i:s');
                $this->model_queue->set_attributes($param003);
                $data003 = $this->model_queue->save();
                /////////////////////Queue creation ends here//////////////
                $this->db->truncate('fb_'.$_SERVER["QUERY_STRING"]);
                session_destroy();
                foreach($csvData as $key => $val){
                    try{
                        $this->db->insert('fb_'.$_SERVER["QUERY_STRING"], $val);
                        $param004['queue_percentage'] = ceil(($key/count($csvData))*100);
                        $data004 = $this->model_queue->update_by_pk($data003,$param004);
                    }
                    catch(Exception $e)
                    {
                        // $param1['again'] = $again;
                        $param1['status'] = 0;
                        $param1['txt'] = $e->getMessage();
                        echo json_encode($param1);
                        exit;
                        // break;
                    }
                }
                // $param005['queue_percentage'] = 100;
                // $param005['queue_status'] = 4;
                // $data005 = $this->model_queue->update_by_pk($data003,$param005);

                    // $param001['group'] = 'product_partno';
                    // $param001['having'] = 'COUNT(*)>1';
                    // $param001['fields'] = 'product_partno';
                    // $data001 = $this->db->query("SELECT * FROM `fb_product` group BY `product_partno` HAVING count(*)>1")->result_array();
                    // $mid =array();
                    // if(count($data001)>0){
                    //     foreach($data001 as $key => $val):
                    //         array_push($mid,$val['product_partno']);
                    //     endforeach;
                    //         $param002['where_in']['product_partno'] = $mid;
                    //         $param002['where']['product_condition'] = 'New';
                    //         $param002['fields'] = 'product_id,product_partno,product_sale_price,product_condition';
                    //         $param002['group_field'] = 'product_partno';
                    //         $data002[] = $this->model_product->find_all($param002);

                    //         $param0020['where_in']['product_partno'] = $mid;
                    //         $param0020['where']['product_condition'] = 'Ref';
                    //         $param0020['fields'] = 'product_id,product_partno,product_sale_price,product_condition';
                    //         $param0020['group_field'] = 'product_partno';
                    //         $data0020[] = $this->model_product->find_all($param0020);
                    //             debug(count($data002[0]));debug(count($data0020[0]),1);
                            // if($a >= 50){
                            // debug($data002,1);
                        // }
                            // debug($this->db->last_query(),1);
                        // endforeach;
// debug(count($data002[0]),1);   
                        // foreach($data0020[0] as $key => $val):
                        //     // foreach($val as $key2 => $val2):
                        //         $compare[$key]['Ref']['product_id'] = $val['product_id'];
                        //         $compare[$key]['Ref']['product_sale_price'] = $val['product_sale_price'];

                        //         $compare[$key]['New']['product_id'] = $key;
                        //         $compare[$key]['New']['product_sale_price'] = $data002[0][$key]['product_sale_price'];
                        //     endforeach;
                        //     // debug($compare,1);

                        //     foreach($compare as $key => $val):
                        //     if($compare[$key]['Ref']['product_sale_price']>$compare[$key]['New']['product_sale_price'])
                        //     {
                        //         $per = (intval($compare[$key]['New']['product_sale_price'])/100)*20;
                        //         // debug($compare[$key]);
                        //         $fin_ref = intval($compare[$key]['New']['product_sale_price']) - $per;
                        //         $compare[$key]['Ref']['product_sale_price'] = $fin_ref;
                        //         // debug($fin_ref,1);
                        //         $update001 = $this->model_product->update_by_pk($compare[$key]['Ref']['product_id'],$compare[$key]['Ref']);
                        //         // debug($update001);
                        //     }
                        //     // $param006['queue_percentage'] = ceil(($key/count($data001))*50)+50;
                        //     // $data005 = $this->model_queue->update_by_pk($data003,$param006);
                        // endforeach;
                    // }
                    $param006['queue_percentage'] = 100;
                    $param006['queue_status'] = 4;
                    $data005 = $this->model_queue->update_by_pk($data003,$param006);
                    
                    unlink('assets/uploads/product/'.$in.'.csv');
                // debug($param,1);
                return $again;
            }
            
        // }
            
        public function escape_string($data){
            $result = array();
            foreach($data as $row){
                $result[] = str_replace('"', '', $row);
            }
            return $result;
            }   
    
        public function sav_up5($in)       
        {
            $in = str_replace(" ","_",$in);
            
            $fil = base_url().'assets/uploads/'.$_SERVER["QUERY_STRING"].'/'.$in;
            if (($open = fopen($fil, "r")) !== FALSE) 
              {
                  $a = ' ';
                while (($data = fgetcsv($open, 1000, ",")) !== FALSE) 
                {       
                    $array[] = $data;
                }
                fclose($open);
              }
              $array[0][0] = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $array[0][0]);
              //////    insert empty value at every zero index since without doing so prodcut name is not getting inserted in db due to unknown reason
              foreach($array as $key => $val){
                    $result[] = array_merge(array_slice($val, 0, 0), array($a), array_slice($val, 0));
              }
              //////    insert finsished//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
              foreach($result[0] as $key => $val)
              {
                // $cus[] = 'product_'.$val;
                $cus[] = $val;
              }
              $cus[0] = ' ';
                $_SESSION['tot'] = count($result);
                $again = 0;
                foreach($result as $key => $val){
                    foreach($val as $key2 => $val2){
                        if($key2 == ' '){}
                        else{
                            $param[$key][($cus[$key2])] = trim($val2);
                        }
                    }
                }
                unset($param[0]);
                foreach($param as $key => $val):
                    $param[$key]['product_slug'] = str_replace(array(' ','|','/'),array('-','','-'),strtolower($param[$key]['product_name']));
                    $param[$key]['product_slug'] = str_replace('--','-',$param[$key]['product_slug']);
                endforeach;
                // debug($param,1);
                // $this->model_product->insert_batch_record($param);
                // $this->db->insert_batch('fb_product',$param);
                foreach($param as $val){
                    $this->db->truncate('fb_product');
                    // $this->db->insert('fb_product', $val);
                }
                    // unlink('assets/uploads/product/'.$in);
                // debug($param,1);
                return $again;
            }
        
        public function sav_up4()       
        {
            // debug($_SESSION['remaining']);
            // debug($_SESSION['read']);
            // debug($_SESSION['filename'],1);
            
            $fil = base_url().'assets/uploads/product/'.$_SESSION['filename'];
            // $file = new SplFileObject($fil, 'r');
            // $file->seek(PHP_INT_MAX);
            // echo $file->key() + 1;
            if (($open = fopen($fil, "r")) !== FALSE) 
              {
                  $a = ' ';
                while (($data = fgetcsv($open, 1000, ",")) !== FALSE) 
                {       
                    $array[] = $data;
                }
                fclose($open);
              }
              $array[0][0] = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $array[0][0]);
              //////    insert empty value at every zero index since without doing so prodcut name is not getting inserted in db due to unknown reason
              foreach($array as $key => $val){
                    $result[] = array_merge(array_slice($val, 0, 0), array($a), array_slice($val, 0));
              }
              //////    insert finsished//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
              
              foreach($result[0] as $key => $val)
              {
                $cus[] = 'product_'.$val;
              }
              $cus[0] = ' ';
            
                foreach($result as $key => $val){
                    foreach($val as $key2 => $val2){
                        if($key2 == ' '){
                            
                        }
                        else{
                                $param[$key][($cus[$key2])] = trim($val2);
                            }
                        }
                        
                        // unlink('assets/uploads/product/'.$in);
                }
                $c = 0;
                foreach($param as $key => $val){
                    if($c >= $_SESSION['read'])
                    {
                        if($_SESSION['remaining'] > 0)
                        {
                            if(($_SESSION['tot'] - $_SESSION['read']) > 5000)
                            {
                                $_SESSION['read'] = $_SESSION['read'] + 5000;
                                $_SESSION['remaining'] = $_SESSION['tot'] - $_SESSION['read'];
                                $again = 1;
                            }
                            else
                            {
                                if($_SESSION['read'] == $_SESSION['tot'])
                                {
                                    $again = 0;
                                    // debug($_SESSION['tot']);
                                    // debug($_SESSION['remaining']);
                                    // debug($_SESSION['read']);
                                }
                                else
                                {
                                    // $_SESSION['remaining'] = $_SESSION['remaining'];
                                    $again = 0;
                                    // debug($_SESSION['tot']);
                                    // debug($_SESSION['remaining']);
                                    // debug($_SESSION['read']);
                                }
                                unlink('assets/uploads/product/'.$in);
                            }
                            
                            break;
                        }
                        // $_SESSION['remaining'] = count($param[$key]);
                    }
                    else
                    {
                        unset($param[$key]);
                        $c++;
                    }
                }
                // unset($param[0]);
                $d = 0;
                foreach($param as $key => $val)
                {
                    $param02['product_barcode'] = $param[$key]['product_barcode'];
                    $this->model_product->insert_if_not_found_or_update($param[$key],$param02);
                    if($d < 4999)
                    {
                        $d++;
                    }
                    else{
                        break;
                    }
                }
                
                // $this->model_product->insert_batch_record($param);
                // debug($param,1);
                return $again;
            }
        
        public function sav_up3($in)       
        {
            $in = str_replace(" ","_",$in);
            
            $fil = base_url().'assets/uploads/product/'.$in;
            // $file = new SplFileObject($fil, 'r');
            // $file->seek(PHP_INT_MAX);
            // echo $file->key() + 1;
            if (($open = fopen($fil, "r")) !== FALSE) 
              {
                  $a = ' ';
                while (($data = fgetcsv($open, 1000, ",")) !== FALSE) 
                {       
                    $array[] = $data;
                }
                fclose($open);
              }
              $array[0][0] = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $array[0][0]);
              //////    insert empty value at every zero index since without doing so prodcut name is not getting inserted in db due to unknown reason
              foreach($array as $key => $val){
                    $result[] = array_merge(array_slice($val, 0, 0), array($a), array_slice($val, 0));
              }
              //////    insert finsished//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
              foreach($result[0] as $key => $val)
              {
                $cus[] = 'product_'.$val;
              }
              $cus[0] = ' ';
            //   debug($cus);
            //   debug($result,1);
            $_SESSION['tot'] = count($result);
            if(count($result)>5000)
            {
                $again = 1;
                $b = 0;
                foreach($result as $key => $val)
                {
                    foreach($val as $key2 => $val2)
                    {
                        if($key2 == '')
                            {
                                
                            }
                            else
                            {
                                $param[$key][($cus[$key2])] = trim($val2);
                            }
                    }
                    if($b>=4999)
                    {
                        $_SESSION['read'] = 5000;
                        $_SESSION['remaining'] = $_SESSION['tot'] - $_SESSION['read'];
                        $_SESSION['filename'] = $in;
                        break;
                    }
                    else
                    {
                        $b++;    
                    }
                    // unlink('assets/uploads/product/'.$in);
                }
                //   debug($param,1);
            }
            else
            {
                $again = 0;
                foreach($result as $key => $val){
                    foreach($val as $key2 => $val2){
                        if($key2 == ' '){
                            
                        }
                        else{
                                $param[$key][($cus[$key2])] = trim($val2);
                            }
                        }
                        if($key!=0)
                        {
                                // $param02['where']['product_barcode'] = $param[$key]['product_barcode'];
                                
                                // $this->model_product->update_model($param02,$param[$key]);
                                
                                // $this->model_product->insert_if_not_found_or_update($param[$key],$param02);
                        }
                }
                    unlink('assets/uploads/product/'.$in);
            }
            // debug($param,1);
                unset($param[0]);
                foreach($param as $key => $val)
                {
                    $param02['product_barcode'] = $param[$key]['product_barcode'];
                    $te[] = $this->model_product->insert_if_not_found_or_update($param[$key],$param02);
                    // debug($param);
                }
                // debug($this->db->last_query());
                // $this->model_product->insert_batch_record($param);
                // debug($param,1);
                return $again;
            }
        
        public function sav_up2($in)       
        {
            $in = str_replace(" ","_",$in);
            
            $fil = base_url().'assets/uploads/product/'.$in;
            if (($open = fopen($fil, "r")) !== FALSE) 
              {
                  $a = ' ';
                while (($data = fgetcsv($open, 1000, ",")) !== FALSE) 
                {       
                    $array[] = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $data);
                }
                fclose($open);
              }
            $array[0][0] = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $array[0][0]);
            //   debug($array,1);
              //////    insert empty value at every zero index since without doing so prodcut name is not getting inserted in db due to unknown reason
              foreach($array as $key => $val){
                    $result[] = array_merge(array_slice($val, 0, 0), array($a), array_slice($val, 0));
              }
              //////    insert finsished//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
              
                foreach($result as $key => $val){
                    foreach($val as $key2 => $val2){
                        if($key2 == ' '){
                            
                        }
                        else{
                                $param[$key][($result[0][$key2])] = trim($val2);
                            }
                        }
                        // if($key!=0)
                        // {
                        //     $param01['where']['product_barcode'] = $param[$key]['product_barcode'];
                        //     $data = $this->model_product->find_one_active($param01);
                        //     if(count($data)>0){
                                
                        //     // debug($data);
                        //     // debug($param[$key],1);
                        //         debug($data[0]['product_barcode'],1);
                        //         $param02['where']['product_barcode'] = $data['product_barcode'];
                        //         $up[] = $this->model_product->update_model($param02,$param[$key]);
                        //     }
                        //     else{
                        //         $param03['where']['product_barcode'] != $data['product_barcode'];
                        //         $this->model_product->insert_record($param[$key]);
                        //     }
                        // }
                        
                        unset($param[0]);
                        foreach($param as $key => $val)
                        {
                            $param02['product_barcode'] = $param[$key]['product_barcode'];
                            $this->model_product->insert_if_not_found_or_update($param[$key],$param02);
                        }
                        unlink('assets/uploads/product/'.$in);
                }
            //   }
            }
        
        public function sav_up($in)       
        {
            $in = str_replace(" ","_",$in);
            
            $fil = base_url().'assets/uploads/product/'.$in;
            if (($open = fopen($fil, "r")) !== FALSE) 
              {
                  $a = 0;
                while (($data = fgetcsv($open, 1000, ",")) !== FALSE) 
                {        
                  $array[] = $data;
                }
                fclose($open);
              }
              $array[0][0] = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $array[0][0]);
            //   debug($array[0][0],1);
              //////    insert empty value at every zero index since without doing so prodcut name is not getting inserted in db due to unknown reason
              foreach($array as $key => $val){
                    $result[] = array_merge(array_slice($val, 0, 0), array($a), array_slice($val, 0));
              }
              //////    insert finsished//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
             
                foreach($result as $key => $val){
                    foreach($val as $key2 => $val2){
                        if($key2 == " "){
                            
                        }
                        else{
                            $param[$key][($result[0][$key2])] = trim($val2);}
                        }
                }
                        unset($param[0]);
                        foreach($param as $key => $val)
                        {
                            $param02['product_barcode'] = $param[$key]['product_barcode'];
                            $this->model_product->insert_if_not_found_or_update($param[$key],$param02);
                        }
                        unlink('assets/uploads/product/'.$in);
                        // debug($param,1);
            }
}
?>