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

class Jewelry_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');
  } 
  function details()
  {      
      $packet_no = $this->uri->segment(2);

      $item = str_replace(strrchr($packet_no, '-'), '', $packet_no);
      
      $record = $this->get_record($packet_no); 
      
      $dataImg = $dataVideo = [];

      $still[] = DNA_URL.$item.'/still.jpg';
      for ($i=1; $i <= 10; $i++) { 
          $still[] = DNA_URL.$item.'/'.$i.'.jpg';
      }   
      $dataImg = $this->urlExist($still);

      $video[] = DNA_URL.$item.'/video.mp4';      
      for ($i=1; $i <= 5; $i++) { 
          $video[] = DNA_URL.$item.'/video%20('.$i.').mp4';
      }   
      $dataVideo = $this->urlExist($video);

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

  private function checkUser() {
    if(!$this->session->userdata('isView')) {
      exit('No direct script access allowed');
    }
  }

  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.'/jewelry-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)) {
        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;
  }

  //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  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;
  }
  
}