<?php defined('BASEPATH') OR exit('No direct script access allowed');

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

class Dna extends CI_Controller {

  public function __construct()
  {
      parent::__construct();    
      header('X-Robots-Tag: noindex'); 
      header('X-Content-Type-Options: nosniff');
      header('X-DNS-Prefetch-Control: off');
      header('X-Download-Options: noopen');
      header('X-Frame-Options: SAMEORIGIN');
      header('X-Permitted-Cross-Domain-Policies: none');
      header('X-XSS-Protection: 0');

      $this->load->helper('download');
      $this->load->helper('jewelry');
  }
  public function jewelry_list()
	{

    $packet_no = $this->uri->segment(2);
    // print_r($packet_no);die;
		$curl = curl_init();

		curl_setopt_array($curl, array(
		CURLOPT_URL => 'https://brainapis.com/api/oriental-gem/get-token',
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_ENCODING => '',
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_TIMEOUT => 0,
		CURLOPT_FOLLOWLOCATION => true,
		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		CURLOPT_CUSTOMREQUEST => 'POST',
		CURLOPT_POSTFIELDS => 'username=orientalGem&password=orientalGem!123!',
		CURLOPT_HTTPHEADER => array(
			'Content-Type: application/x-www-form-urlencoded'
		),
		));
	
		$response = curl_exec($curl);
	
		$err = curl_close($curl);
		// echo $response;
		if (empty($err)){
			$response = json_decode($response, true);
			$token = $response['token'];
		} 
			// ---jewelry API
			$curl = curl_init();
			curl_setopt_array($curl, array(
			CURLOPT_URL => 'https://brainapis.com/api/oriental-gem/jewelry-list',
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => '',
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 0,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => 'POST',
      CURLOPT_POSTFIELDS =>'{
				"sku": "'.$packet_no.'"
			}',
      // CURLOPT_POSTFIELDS => "Item=$packet_no",
			CURLOPT_HTTPHEADER => array(
				'Content-Type: application/json',
				'Authorization: Bearer '.$token
			),
			));
			
			$response = curl_exec($curl);
			
			  curl_close($curl);
				if (empty($err)){
					$response = json_decode($response, true);
					$records = $response['record'];
				};
        //          echo "<pre>";
        // print_r($records); die;

        $record = array();
        foreach($records as $val){
          if($val['SkuCode'] == $packet_no){
            $record[] = $val;
            continue;
          }
        }

        // echo "<pre>";
        // print_r($record);

    				// ---Bom API
            // echo $packet_no; die;
            $curl = curl_init();
            curl_setopt_array($curl, array(
              CURLOPT_URL => 'https://brainapis.com/api/oriental-gem/bom',
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => '',
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 0,
              CURLOPT_FOLLOWLOCATION => true,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => 'POST',
              CURLOPT_POSTFIELDS =>'{
                "sku": "'.$packet_no.'"
              }',
              CURLOPT_HTTPHEADER => array(
              'Content-Type: application/json',
              'Authorization: Bearer '.$token
              ),
            ));
    
            $response1 = curl_exec($curl);
        
            curl_close($curl);
            // echo $response;
            if (empty($err)){
              $response1 = json_decode($response1, true);
              $record1 = $response1['record'];
            };

            //echo "<pre>";
            // print_r($record1);
            $bom_record = array();
              foreach($record1 as $val){
                if($val['SkuCode'] == $packet_no){
                  $bom_record[] = $val;
                  continue;
                }
              }

            // similar master item start
              
              $curl = curl_init();
              curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://brainapis.com/api/oriental-gem/jewelry-list',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS =>'{
                  "item": "'.$records['0']['Item'].'"
                }',
                CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Authorization: Bearer '.$token
                ),
              ));
      
              $response2 = curl_exec($curl);
          
              curl_close($curl);
              // echo $response;
              if (empty($err)){
                $response2 = json_decode($response2, true);
                $similar = $response2['record'];
              };

            // echo "<pre>";
            // print_r($similar);
            // die;
            // similar master item end

            // $num_for = array();
            // foreach ($bom_record as $group1) {
            //    $group1['Weight'] = number_format($group1['Wt'],2)." Gram";
            //   //  $group1['Item Comp'] = $group1['ItemComp'];
            //   //  $group1['Size Comp'] = $group1['SizeComp'];
            //    $group1['Seive Size'] = $group1['SeiveSize'];

            //   $num_for[] = $group1;
            // }

            // $result = [];
            // foreach ($num_for as $group) {
            //     foreach ($group as $key=>$value) {
            //         if (!isset($result[$key]))
            //             $result[$key] = [];
                        
            //         $result[$key][] = $value;
            //     }
            // }
            
            // $newarr = array(); 
            // foreach($result as $k => $val){
            //   if($k != 'Item' && $k != 'Size' && $k != 'SkuCode' && $k != 'Amt' && $k != 'Wt' && $k != 'ItemComp' && $k != 'SizeComp' && $k != 'SeiveSize'){

            //       $newarr[$k] = $val;
            //     continue;
            //   }
            // }

            
            // echo "<pre>";
            // print_r($num_for);
            // die;

            // $bomarrr = array();
            // $bomarrr1 = array();
            // $bomarrr2 = array();
            // $bomarrr = $this->replace_key($newarr,"ItemComp","Item Comp");
            // $bomarrr1 = $this->replace_key($bomarrr,"SizeComp","Size Comp");
            // $bomarrr2 = $this->replace_key($bomarrr1,"SeiveSize","Seive Size");

            $data = [
              'jewelry_list' => $record,
              'bom' => $bom_record,
              'similar' => $similar,
              // 'bom' => $num_for,
              // 'bom' => $newarr,
            ];

            //echo "<pre>";
            // print_r($data);
		$this->load->view('diamond/dna', $data);
    
	} 

  function replace_key($arr, $oldkey, $newkey) {
    if(array_key_exists( $oldkey, $arr)) {
      $keys = array_keys($arr);
        $keys[array_search($oldkey, $keys)] = $newkey;
        return array_combine($keys, $arr);	
    }
      return $arr;    
  }

  function details()
  {      
      $packet_no = $this->uri->segment(2);

      $record = $this->get_record($packet_no); 
      $dataImg = $dataVideo = [];

      $still[] = DNA_URL.$packet_no.'.jpg';

      for ($i=2; $i <= 20; $i++) { 
          $still[] = DNA_URL.$packet_no.'_'.$i.'.jpg';
      }   
      $dataImg = $this->urlExist($still);

      $video = DNA_URL.$packet_no.'.mp4';
      if(checkLink($video) == '200') {
          $dataVideo[] = $video;
      } 

      $data = [
        'record' => $record,
        'dataImg' => $dataImg,
        'dataVideo' => $dataVideo,
        'varDetail' => getVar('varDetail'),
        'varCenterStone' => getVar('varCenterStone')
      ];
      //print_ex($data);
      $this->session->set_userdata('isView', 1);
      $this->load->view('diamond/dna',$data);
  }

  private function checkUser() {
    if(!$this->session->userdata('isView')) {
      exit('No direct script access allowed');
    }
  }
  function download(){
      $this->checkUser();
      $stock = $this->input->post('stock');
      $type = $this->input->post('type');
      if(trim($stock)=='' || trim($type)==''){
        redirect($_SERVER['HTTP_REFERER']);
      }

      if($type=='image') {
          $zip = new ZipArchive();
          $zipFile = $stock.'Image'.time().'.zip';

          if ($zip->open('uploads/'.$zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
               die ('Could not open archive');
          }
          $file_content = file_get_contents(DNA_URL.$stock.'/still.jpg');
          $zip->addFromString('still.jpg', $file_content);
          
          $dataImg = array(
            array( 'name' => 'heart', 'path' => '' ),
            array( 'name' => 'arrow', 'path' => '' ),
            array( 'name' => 'asset', 'path' => '' ),
            array( 'name' => 'white', 'path' => '' )
          );

          foreach ($dataImg as $key => $value) {
            $allUrl[] = $dataImg[$key]['path'] = DNA_URL.$value['name'].'/'.$stock.'.jpg';
          }

          $allUrlExist = $this->urlExist($allUrl);

          foreach ($dataImg as $key => $value) {
            if(in_array($value['path'], $allUrlExist)) {
              $file_content = file_get_contents($value['path']);
              $zip->addFromString($value['name'].'.jpg', $file_content);
            }
          }

          $zip->close();

          force_download('uploads/'.$zipFile, NULL);           
      }      
      else if($type=='cert') {
          $zip = new ZipArchive();
          $zipFile = $stock.'Cert'.time().'.zip';

          if ($zip->open('uploads/'.$zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
               die ('Could not open archive');
          }
          $file_content = file_get_contents(DNA_URL.'certificate_Images/'.$stock.'.pdf');
          $zip->addFromString($stock.'.pdf', $file_content);
          $zip->close();

          force_download('uploads/'.$zipFile, NULL);           
      }      
      else if($type=='video') {
          $zip = new ZipArchive();
          $zipFile = $stock.'Video'.time().'.zip';

          if ($zip->open('uploads/'.$zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
               die ('Could not open archive');
          }
          $file_content = file_get_contents(DNA_URL.$stock.'/video.mp4');
          $zip->addFromString($stock.'.mp4', $file_content);
          $zip->close();

          force_download('uploads/'.$zipFile, NULL);           
      }
      else if($type=='excel') {
        $this->export_diamond();
      }

  }

  private function export_diamond()
  {        
      $NET_RATE = $NET_VALUE = 0;
      $where = ""; 
      $stock = $this->input->post('stock');
      $type = $this->input->post('type'); 
      //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
      $records = $this->get_record($stock);    
      //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++      
    
      $spreadsheet = new Spreadsheet();
      $sheet = $spreadsheet->getActiveSheet();

      $sheet->setCellValue('A1' ,'Stock#');
      $sheet->setCellValue('B1' ,'Shape');
      $sheet->setCellValue('C1' ,'Status');
      $sheet->setCellValue('D1' ,'Cts');
      $sheet->setCellValue('E1' ,'Color');
      $sheet->setCellValue('F1' ,'Clarity');
      $sheet->setCellValue('G1' ,'Cut');
      $sheet->setCellValue('H1' ,'Pol');
      $sheet->setCellValue('I1' ,'Sym');
      $sheet->setCellValue('J1' ,'Fluor');    
      $sheet->setCellValue('K1' ,'Disc%');
      $sheet->setCellValue('L1' ,'Depth%');
      $sheet->setCellValue('M1' ,'Table%');
      $sheet->setCellValue('N1' ,'Rap.($)');
      $sheet->setCellValue('O1' ,'$/Carat');
      $sheet->setCellValue('P1' ,'Total $');
      $sheet->setCellValue('Q1' ,'Descrip');
      $sheet->setCellValue('R1' ,'Lab');
      $sheet->setCellValue('S1' ,'Pic');
      $sheet->setCellValue('T1' ,'Brand');
      $sheet->setCellValue('U1' ,'Measurements');
      $sheet->setCellValue('V1' ,'Report No');
    
      $sheet->getStyle('A1:V1')
        ->applyFromArray([
            'font' => [                    
              'color' => ['argb' => 'ffffff'],
              'size'  => 11,
              'name' => 'Calibri'
            ],
          'fill' =>[ 
              'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
              'color' => ['argb' => '17375d']
            ]
        ]);
      $i=2;       
      foreach($records as $row) 
      {   
          $sheet->setCellValue('A' . $i, $row->PACKET_NO);
          $sheet->setCellValue('B' . $i, $row->SHAPE_SEQ);         
          $sheet->setCellValue('C' . $i, $row->MemoStatus);         
          $sheet->setCellValue('D' . $i, number_format($row->CTS,2));
          $sheet->setCellValue('E' . $i, $row->COLOR_SEQ);
          $sheet->setCellValue('F' . $i, $row->PURITY_SEQ);
          $sheet->setCellValue('G' . $i, $row->CUT_SEQ);
          $sheet->setCellValue('H' . $i, $row->POLISH_SEQ);
          $sheet->setCellValue('I' . $i, $row->SYMM_SEQ);
          $sheet->setCellValue('J' . $i, $row->FLS_SEQ);        
          $sheet->setCellValue('K' . $i, number_format($row->DISC_PER));
          $sheet->setCellValue('L' . $i, number_format($row->DEPTH_PER,1));
          $sheet->setCellValue('M' . $i, (int)$row->TABLE_PER);
          $sheet->setCellValue('N' . $i, round($row->RATE));        
          $sheet->setCellValue('O' . $i, round($row->NET_RATE));        
          $sheet->setCellValue('P' . $i, round($row->NET_VALUE));        
          $sheet->setCellValue('Q' . $i, $row->DESCRIPTION);       
          $sheet->setCellValue('R' . $i, $row->LAB_SEQ);       
          $sheet->setCellValue('S' . $i, 'DNA');       
          $sheet->setCellValue('T' . $i, $row->HA);       
          $sheet->setCellValue('U' . $i, $row->LWD);       
          $sheet->setCellValue('V' . $i, $row->REPORT_NO); 

          $link = "https://dnalinks.in/certificate_Images/".$row->REPORT_NO.".pdf"; 
          $sheet->getCell('R' . $i)->getHyperlink()->setUrl($link);

          $link = "https://dna.dnalinks.in/d/".$row->PACKET_NO;
          $sheet->getCell('S' . $i)->getHyperlink()->setUrl($link);

          $sheet->getStyle('R'.$i.':S'.$i)
            ->applyFromArray(
                [
                    'font' => [                    
                        'color' => ['argb' => '0000FF'],
                        'size'  => 11,
                        'name' => 'Calibri',
                        'underline' => 'single'
                    ]
                ]
            );

          $NET_RATE += round($row->NET_RATE);
          $NET_VALUE += round($row->NET_VALUE);
          $i++;
      }

      $sheet->setCellValue('A' . $i, count($records));
      $sheet->setCellValue('P' . $i, $NET_VALUE);

      $sheet->getStyle('A'.$i.':V'.$i)
        ->applyFromArray(
          [
              'font' => [                    
                  'color' => ['argb' => '000000'],
                  'size'  => 11,
                  'name' => 'Calibri'
              ],
              'fill' => [
                  'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                  'color' => ['argb' => 'd3d3d3']
              ]
          ]
      );
       
      $filename='Stock_'.date('m_d_Y_h_i_s_A').'.xlsx'; 
      $writer = new Xlsx($spreadsheet);               
      $writer->save('uploads/'.$filename);
    
      header('Content-Type: application/vnd.ms-excel'); 
      header('Content-Disposition: attachment;filename="'.$filename.'"'); 
      header('Cache-Control: max-age=0');
      readfile("uploads/".$filename);

      unlink("uploads/".$filename);
  }

  private function get_token() 
  {   
    $token = $this->session->tempdata('dna_token');
    if(empty($token)) 
    {
      $curl = curl_init();
      curl_setopt_array($curl, array(
      CURLOPT_URL => APIURL."/get-token",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => "username=".APIUSER."&password=".APIPASSWORD."",
      CURLOPT_HTTPHEADER => array(
          "Accept: */*",
          "Content-Type: application/x-www-form-urlencoded",
        ),
      ));
      $response = curl_exec($curl);
      $err = curl_error($curl);
      curl_close($curl);
      if (empty($err)){
        $response = json_decode($response, true);
        $token = $response['token'];
        $this->session->set_tempdata('dna_token',$token,3000);
      } 
    } 

    return $token;
  }

  private function get_record($stock) 
  {   
      $record = array();
      //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
      $token = $this->get_token();
      /*$record = $this->check_record($stock);
      if(!empty($record)) {
          return $record;
      }*/
      //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
      $curl = curl_init();
      curl_setopt_array($curl, array(
        CURLOPT_URL => APIURL.'/dna/',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "item=$stock",
        CURLOPT_HTTPHEADER => array(
          "Accept: */*",
          "Authorization: Bearer ".$token         
        ),
      ));
      $response = curl_exec($curl);
      $err = curl_error($curl);
      curl_close($curl);
      if (empty($err)){
        $responseArr = json_decode($response);
        $record = $responseArr->record;

        /*if(!empty($record)) {
          $this->save_record($record[0]->Item, $record[0]->Item, $response);           
        }*/
      }
      
      return $record;
  }

  private function save_record($packet_no, $report_no, $response) {
    $data = array(
            'packet_no' => $packet_no,
            'report_no'  => $report_no,
            'data'  => $response,
            'added_at'  => date('Y-m-d H:i')
    );

    $this->db->replace('tbl_diamond', $data);
  }
  private function check_record($packet_no) {    
    $record = [];

    $result = $this->db->query("SELECT * FROM tbl_diamond WHERE packet_no = '$packet_no'")->result();

    if(!empty($result)) {
        if(date('Y-m-d') == date('Y-m-d', strtotime($result[0]->added_at))) {
            $responseArr = json_decode($result[0]->data);       
            $record = $responseArr->record;
        }
    }
    return $record;
  }
  //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  function del_file() {
    $this->load->database();
    $this->db->truncate('ci_sessions');
    $this->db->delete('curl_buying_report', array('added_at <' => date("Y-m-d", strtotime("- 5 day"))));
    $this->db->delete('tbl_diamond', array('added_at <' => date("Y-m-d")));

    $this->load->helper('file');
    delete_files('./uploads/', FALSE, TRUE);
  }
  //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  private function urlExist($urls) {
    $requests = array();
    $returnArray = array();

    $mh = curl_multi_init();

    foreach ($urls as $k => $url) {
        $requests[$k] = array();
        $requests[$k]['url'] = $url;
        $requests[$k]['curl_handle'] = curl_init($url);
        
        curl_setopt($requests[$k]['curl_handle'], CURLOPT_RETURNTRANSFER, true);
        curl_setopt($requests[$k]['curl_handle'], CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($requests[$k]['curl_handle'], CURLOPT_TIMEOUT, 10);
        curl_setopt($requests[$k]['curl_handle'], CURLOPT_NOBODY, true);
        curl_setopt($requests[$k]['curl_handle'], CURLOPT_HEADER, true);

        curl_multi_add_handle($mh, $requests[$k]['curl_handle']);
    }

    $stillRunning = false;
    do {
        curl_multi_exec($mh, $stillRunning);
    } while ($stillRunning);

    foreach ($requests as $k => $request) {
        curl_multi_remove_handle($mh, $request['curl_handle']);        
        $http_code = curl_getinfo($request['curl_handle'], CURLINFO_HTTP_CODE);
        $requests[$k]['http_code'] = curl_getinfo($request['curl_handle'], CURLINFO_HTTP_CODE);
        if ($requests[$k]['http_code'] == 200) {
          $returnArray[] = $request['url'];
        }
        curl_close($requests[$k]['curl_handle']);
    }
    curl_multi_close($mh);
    return $returnArray;
  }
  
}