<?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();    
      $this->load->helper('download');
      $this->load->helper('diamond');

      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');
  } 
  
  function diamond_details()
  {
      $PACKET_NO = $this->uri->segment(2);  
      //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++      
      $record = $this->get_record($PACKET_NO); 
      //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
      $baseAsset = 'https://diamondmedia.s3.us-east-1.amazonaws.com/';
      $data_cert = '';
      $data_still = '';
      $data_still_2 = '';      
      $data_video360 = '';
      $data_video_2 = '';
      $isB2b = 0;

      $dataImg = $dataVideo = [];          

      $dataB2B = array(
        array( 'name' => 'Heart_Black_BG.jpg', 'image' => 'Heart_Black_BG.jpg', 'id' => 'b2b_Heart_Black', 'path' => '', 'isAvail' => 0, 'title' => 'Heart', 'tooltip' => 'Heart Black'),
        array( 'name' => 'Arrow_Black_BG.jpg', 'image' => 'Arrow_Black_BG.jpg', 'id' => 'b2b_Arrow_Black', 'path' => '', 'isAvail' => 0, 'title' => 'Arrow', 'tooltip' => 'Arrow Black'),
        array( 'name' => 'ASET_Black_BG.jpg', 'image' => 'ASET_Black_BG.jpg', 'id' => 'b2b_ASET_Black', 'path' => '', 'isAvail' => 0, 'title' => 'Aset', 'tooltip' => 'Aset Black'),
        array( 'name' => 'ASET_White_BG.jpg', 'image' => 'ASET_White_BG.jpg', 'id' => 'b2b_ASET_White', 'path' => '', 'isAvail' => 0, 'title' => 'Aset', 'tooltip' => 'Aset White'),
        array( 'name' => 'IDEAL_White_BG.jpg', 'image' => 'IDEAL_White_BG.jpg', 'id' => 'b2b_Ideal_White', 'path' => '', 'isAvail' => 0, 'title' => 'Ideal', 'tooltip' => 'Ideal White'),
        array( 'name' => 'Dark_Field_White_BG.jpg', 'image' => 'Dark_Field_White_BG.jpg', 'id' => 'b2b_Dark_Field', 'path' => '', 'isAvail' => 0, 'title' => 'Dark Field', 'tooltip' => 'Dark Field White'),
        array( 'name' => 'Office_Light_Black_BG.jpg', 'image' => 'Office_Light_Black_BG.jpg', 'id' => 'b2b_Office_Light', 'path' => '', 'isAvail' => 0, 'title' => 'Office Light', 'tooltip' => 'Office Light Black'),
        array( 'name' => 'fluorescence.jpg', 'image' => 'fluorescence.jpg', 'id' => 'b2b_fluor', 'path' => '', 'isAvail' => 0, 'title' => 'Fluorescence', 'tooltip' => 'Fluorescence'),
      );

      $allUrl = [];

      if(!empty($record)) {
          $PACKET_NO = $record['0']->PACKET_NO;
          $FL_IMAGE = $record['0']->FL_IMAGE;
          $FL_VIDEO = $record['0']->FL_VIDEO;

          $cert = $baseAsset.'CERTPDF/'.$record['0']->REPORT_NO.'.pdf';
          $data_cert = (checkLink($cert) == '200') ? $cert : '';
      } 

      $still = $baseAsset.'B2C/imaged/'.$PACKET_NO.'/still.jpg';
      $still_2 = $baseAsset.'B2B/imaged/'.$PACKET_NO.'/still.jpg';

      $data_still = (checkLink($still) == '200') ? $still : '';
      $data_still_2 = (checkLink($still_2) == '200') ? $still_2 : '';
                  
      $data_video360 = (checkLink($this->videoB2c($PACKET_NO, 0)) == '200') ? $this->videoB2c($PACKET_NO) : '';
      $data_video_2 = (checkLink($this->videoB2b($PACKET_NO, 0)) == '200') ? $this->videoB2b($PACKET_NO) : '';

      if(str_ends_with($PACKET_NO, 'A') || str_ends_with($PACKET_NO, 'B')
          || str_ends_with($PACKET_NO, 'F') || str_ends_with($PACKET_NO, 'HK')) {

          $PACKET_NO = rtrim($PACKET_NO,'ABFHK');

          if(empty($data_video360)) { 
              $data_video360 = (checkLink($this->videoB2c($PACKET_NO, 0)) == '200') ? $this->videoB2c($PACKET_NO) : '';
          }
          if(empty($data_video_2)) {
              $data_video_2 = (checkLink($this->videoB2b($PACKET_NO, 0)) == '200') ? $this->videoB2b($PACKET_NO) : '';
          }

          $still = $baseAsset.'B2C/imaged/'.$PACKET_NO.'/still.jpg';
          $still_2 = $baseAsset.'B2B/imaged/'.$PACKET_NO.'/still.jpg';

          if(empty($data_still)) { 
              $data_still = (checkLink($still) == '200') ? $still : '';
          }
          if(empty($data_still_2)) {
               $data_still_2 = (checkLink($still_2) == '200') ? $still_2 : '';
          }
      }

      $journey = $baseAsset.'JOURNEY/'.$PACKET_NO.'.mp4';
      $data_journey = (checkLink($journey) == '200') ? $journey : '';

      foreach ($dataB2B as $key => $value) {
        $allUrl[] = $dataB2B[$key]['path'] = $baseAsset.'B2B/imaged/'.$PACKET_NO.'/'.$value['name'];
      }
      $allUrlExist = $this->urlExist($allUrl);

      foreach ($dataB2B as $key => $value) {
        if(in_array($value['path'], $allUrlExist)) {
          $dataB2B[$key]['isAvail'] = 1;
          $isB2b = 1;
        }
      }
      
      $data = array(
        'record' => $record,
        'data_video360' => $data_video360,
        'data_video_2' => $data_video_2,
        'data_cert' => $data_cert,
        'data_still' => $data_still,
        'data_still_2' => $data_still_2,        
        'dataImg' => $dataImg,
        'dataVideo' => $dataVideo,
        'isB2b' => $isB2b,
        'dataB2B' => $dataB2B,
        'data_journey' => $data_journey,
      );
      $data['varDiamondDetail'] = diaVar('varDiamondDetail');
      $data['varDiamondMeas'] = diaVar('varDiamondMeas');
      $data['varDiamondInclusion'] = diaVar('varDiamondInclusion');
      //print_ex($data);
      $this->session->set_userdata('isView', 1);
      $this->load->view('diamond/dna',$data);      

  }

  function bb_video()
  {
      $data_cert = '';
      $data_video_2 = '';
      $PACKET_NO = $this->uri->segment(2);     
      $segment_3 = $this->uri->segment(3);     
      $baseAsset = 'https://diamondmedia.s3.us-east-1.amazonaws.com/';

      $record = $this->get_record($PACKET_NO); 
      
      if(!empty($record)) {
          $PACKET_NO = $record['0']->PACKET_NO;

          $cert = $baseAsset.'CERTPDF/'.$record['0']->REPORT_NO.'.pdf';
          $data_cert = (checkLink($cert) == '200') ? $cert : '';
      } 
      $video360_b2b = $this->videoB2b($PACKET_NO);                  

      if($segment_3 == 'vision360.html') { 
        if(checkLink($this->videoB2b($PACKET_NO, 0)) != '200') {
          $video360_b2b = $this->videoB2c($PACKET_NO);
        }
      } 
      else {
        $video360_b2b = (checkLink($this->videoB2b($PACKET_NO, 0)) == '200') ? $this->videoB2b($PACKET_NO) : '';

        if(str_ends_with($PACKET_NO, 'A') || str_ends_with($PACKET_NO, 'B')
             || str_ends_with($PACKET_NO, 'F') || str_ends_with($PACKET_NO, 'HK')) {

            $PACKET_NO = rtrim($PACKET_NO,'ABFHK');
            if(empty($video360_b2b)) {
                $video360_b2b = (checkLink($this->videoB2b($PACKET_NO, 0)) == '200') ? $this->videoB2b($PACKET_NO) : '';
            }
        }
      }
      
      $data = array(
        'record' => $record,
        'data_video_2' => $video360_b2b,
        'data_cert' => $data_cert,
      );
      //print_ex($data);
      $this->session->set_userdata('isView', 1);
      $this->load->view('diamond/bb_video',$data); 
  }

  function image_video()
  {      
      $type = $this->uri->segment(1);     
      $PACKET_NO = $this->uri->segment(2);     
      $baseAsset = 'https://diamondmedia.s3.us-east-1.amazonaws.com/';

      /*$record = $this->get_record($PACKET_NO); 
      if(!empty($record)) {
          $PACKET_NO = $record['0']->PACKET_NO;
      }*/      
      $data_video360 = $data_video_2 = $data_still = $data_still_2 = '';

      if($type == 'vid') {            
          $data_video360 = (checkLink($this->videoB2c($PACKET_NO, 0)) == '200') ? $this->videoB2c($PACKET_NO) : '';
          $data_video_2 = (checkLink($this->videoB2b($PACKET_NO, 0)) == '200') ? $this->videoB2b($PACKET_NO) : '';

          if(str_ends_with($PACKET_NO, 'A') || str_ends_with($PACKET_NO, 'B')
              || str_ends_with($PACKET_NO, 'F') || str_ends_with($PACKET_NO, 'HK')) {

              $PACKET_NO = rtrim($PACKET_NO,'ABFHK');

              if(empty($data_video360)) { 
                  $data_video360 = (checkLink($this->videoB2c($PACKET_NO, 0)) == '200') ? $this->videoB2c($PACKET_NO) : '';
              }
              if(empty($data_video_2)) {
                  $data_video_2 = (checkLink($this->videoB2b($PACKET_NO, 0)) == '200') ? $this->videoB2b($PACKET_NO) : '';
              }

          }
      }

      $still = $baseAsset.'B2C/imaged/'.$PACKET_NO.'/still.jpg';
      $still_2 = $baseAsset.'B2B/imaged/'.$PACKET_NO.'/still.jpg';
      if($type == 'img') {
          $data_still = (checkLink($still) == '200') ? $still : '';
          $data_still_2 = (checkLink($still_2) == '200') ? $still_2 : '';

          if(str_ends_with($PACKET_NO, 'A') || str_ends_with($PACKET_NO, 'B')
            || str_ends_with($PACKET_NO, 'F') || str_ends_with($PACKET_NO, 'HK')) {

              $PACKET_NO = rtrim($PACKET_NO,'ABFHK');
            
              $still = $baseAsset.'B2C/imaged/'.$PACKET_NO.'/still.jpg';
              $still_2 = $baseAsset.'B2B/imaged/'.$PACKET_NO.'/still.jpg';

              if(empty($data_still)) { 
                  $data_still = (checkLink($still) == '200') ? $still : '';
              }
              if(empty($data_still_2)) {
                   $data_still_2 = (checkLink($still_2) == '200') ? $still_2 : '';
              }
          }
      }
      
      $data = array(        
        'type' => $type,
        'data_video360' => $data_video360,
        'data_video_2' => $data_video_2,
        'data_still' => $data_still,
        'data_still_2' => $data_still_2,
      );
      //print_ex($data);
      $this->session->set_userdata('isView', 1);
      $this->load->view('diamond/image_video',$data); 
  }

  private function videoB2c($PACKET_NO, $isCompress = 1) {
    $baseAsset = 'https://diamondmedia.s3.us-east-1.amazonaws.com/';
    $file = '';
    if($isCompress) {      
      $file = $baseAsset.'B2C/Vision360.html?d='.$PACKET_NO.'&sr=10&s=20';
    } 
    else if(!$isCompress) {
      $file = $baseAsset.'B2C/imaged/'.$PACKET_NO.'/0.json?version=1';      
    }
    return $file;

  }
  private function videoB2b($PACKET_NO, $isCompress = 1) {
    $baseAsset = 'https://diamondmedia.s3.us-east-1.amazonaws.com/';
    $file = '';
    if($isCompress) {      
      $file = $baseAsset.'B2B/Vision360.html?d='.$PACKET_NO.'&sr=10&s=20';
    } 
    else if(!$isCompress) {
      $file = $baseAsset.'B2B/imaged/'.$PACKET_NO.'/0.json?version=1';      
    }
    return $file;
  }
  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']);
      }
      $baseAsset = 'https://diamondmedia.s3.us-east-1.amazonaws.com/';
      $allUrl = [];

      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($baseAsset.'B2C/imaged/'.$stock.'/still.jpg');
          $zip->addFromString('still.jpg', $file_content);

          $dataB2B = array(
            array( 'name' => 'still.jpg', 'path' => '' ),
            array( 'name' => 'Arrow_Black_BG.jpg', 'path' => '' ),
            array( 'name' => 'ASET_Black_BG.jpg', 'path' => '' ),
            array( 'name' => 'ASET_White_BG.jpg', 'path' => '' ),
            array( 'name' => 'Dark_Field_White_BG.jpg', 'path' => '' ),
            array( 'name' => 'fluorescence.jpg', 'path' => '' ),
            array( 'name' => 'Heart_Black_BG.jpg', 'path' => '' ),
            array( 'name' => 'IDEAL_White_BG.jpg', 'path' => '' ),
            array( 'name' => 'Office_Light_Black_BG.jpg', 'path' => '' )
          );
          
          foreach ($dataB2B as $key => $value) {
            $allUrl[] = $dataB2B[$key]['path'] = $baseAsset.'B2B/imaged/'.$stock.'/'.$value['name'];
          }

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

          foreach ($dataB2B as $key => $value) {
            if(in_array($value['path'], $allUrlExist)) {
              $file_content = file_get_contents($value['path']);
              $zip->addFromString('B2B_'.$value['name'], $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($baseAsset.'CERTPDF/'.$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($baseAsset.'B2C/imaged/'.$stock.'/video.mp4');
          $zip->addFromString($stock.'.mp4', $file_content);

          $b2bVideo = $baseAsset.'B2B/imaged/'.$stock.'/video.mp4';
          if(checkLink($b2bVideo)=='200') {
            $file_content = file_get_contents($b2bVideo);
            $zip->addFromString('B2B_'.$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'); 

      $baseAsset = 'https://diamondmedia.s3.us-east-1.amazonaws.com/';
      //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
      $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, number_format($row->NET_RATE,2));        
          $sheet->setCellValue('P' . $i, number_format($row->NET_VALUE,2));        
          $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 = $this->getCertUrl($row->REPORT_NO);
          $sheet->getCell('R' . $i)->getHyperlink()->setUrl($link);

          $link = "https://dna.dnalink.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 += $row->NET_RATE;
          $NET_VALUE += $row->NET_VALUE;
          $i++;
      }
      $sheet->setCellValue('A' . $i, count($records));
      $sheet->setCellValue('O' . $i, $NET_RATE);
      $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."/diamond-dna/".$stock,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        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]->PACKET_NO, $record[0]->REPORT_NO, $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)) {
        $responseArr = json_decode($result[0]->data);       
        $record = $responseArr->record;
        // if(date('Y-m-d') == date('Y-m-d', strtotime($result[0]->added_at))) {}
    }
    return $record;
  }
  //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  function del_file() {
    $this->load->database();
    $this->db->truncate('ci_sessions');
    $this->db->delete('tbl_diamond', [ 'added_at <' => date("Y-m-d", strtotime("- 10 day")) ]);

    $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;
  }

  private function getCertUrl($report) {
    if(!$report) { return ''; }
    return 'https://diamondmedia.s3.us-east-1.amazonaws.com/CERTPDF/'.$report.'.pdf';
  }
  
}
