<?php
function validateDate($date, $format = 'Y-m-d')
{
    $d = DateTime::createFromFormat($format, $date);
    // The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
    return $d && $d->format($format) === $date;
}

function validateDateTime($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    // The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
    return $d && $d->format($format) === $date;
}
/**
 * return indonesian date format 
 * @param  text $date date text 2019-07-02
 * @return text       indonesian format 2 januari 2019
 */
function tgl_indo($date) { // fungsi atau method untuk mengubah tanggal ke format indonesia
  if (validateDate($date)) {
       // variabel BulanIndo merupakan variabel array yang menyimpan nama-nama bulan
      $BulanIndo = array("Januari", "Februari", "Maret",
                 "April", "Mei", "Juni",
                 "Juli", "Agustus", "September",
                 "Oktober", "November", "Desember");
    
      $tahun = substr($date, 0, 4); // memisahkan format tahun menggunakan substring
      $bulan = substr($date, 5, 2); // memisahkan format bulan menggunakan substring
      $tgl   = substr($date, 8, 2); // memisahkan format tanggal menggunakan substring
      
      $result = $tgl . " " . $BulanIndo[(int)$bulan-1] . " ". $tahun;
      return($result);
  } else {
    return '';
  }

}

function dec_data($data) {
  $replace_encode = substr_replace($data, '', 3 , 3);
  $decode = base64_decode($replace_encode);
  $json_sys = json_decode($decode);
  return $json_sys;
}

function tgl_english($date) {
  if ($date!='') {
      $tahun = substr($date, -4); // memisahkan format tahun menggunakan substring
      $bulan = substr($date, 3, 2); // memisahkan format bulan menggunakan substring
      $tgl   = substr($date, 0, 2); // memisahkan format tanggal menggunakan substring
      
      $result = $tahun. "-" .$bulan. "-". $tgl;
      return($result);
  } else {
    return '';
  }
}



function tgl_indo_angka($date) { // fungsi atau method untuk mengubah tanggal ke format indonesia
  if (validateDate($date)) {
      $tahun = substr($date, 0, 4); // memisahkan format tahun menggunakan substring
      $bulan = substr($date, 5, 2); // memisahkan format bulan menggunakan substring
      $tgl   = substr($date, 8, 2); // memisahkan format tanggal menggunakan substring
      
      $result = $tgl . "-" . $bulan . "-". $tahun;
      return($result);
  } else {
    return '';
  }

}
  function run($data,$url, $type = 'json')
  {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_POST, 1); 

    $headers = array();

    if ($type == 'xml')
      $headers[] = 'Content-Type: application/xml';
    else
      $headers[] = 'Content-Type: application/json';

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    if ($data) {
      if ($type == 'xml') {
        $data = stringXML($data);
      } else {
        $data = json_encode($data);
      }
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    //curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
  }

  function get_data_service($data) {
    $token = get_token();
      $data_dic = [
        'act' => $data['act'],
        'token' => $token,
        'filter' => $data['filter'],
        'order' => "",
        'limit' => 1,
        'offset' => 0

      ];

      $hasil = service_request($data_dic);
      if ($hasil->data) {
          foreach ($hasil->data as $dt) {
              
          }
          return $dt;
      } else {
        return false;
          //echo $hasil->error_desc;
      }

  }

function service_request($data, $url = '', $timeout = 25) {
    if ($url == '') {
        $url = get_service_url('rest');
    }

    /*if (!isset($data['token'])) {
        $data['token'] = get_token();
    }*/

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_POST, 1);

    $headers = array();
    $headers[] = 'Content-Type: application/json';

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    $data = json_encode($data);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    //curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_ENCODING, '');
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); // Set the timeout in seconds
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($ch);

    if ($result === false) {
        // Check if the request exceeded the specified timeout
        $curlError = curl_error($ch);
        $curlErrorCode = curl_errno($ch);
        if ($curlErrorCode == 28) { // 28 is CURLE_OPERATION_TIMEDOUT
            return json_decode('{"error": "PASTIKAN NEO FEEDER AKTIF, Atau Coba Masuk Ke menu Master Data, Config Akun Feeder, Pastikan status Connected"}');
        }
    }

    //dump($data);

    //print_r($data);
    curl_close($ch);

    return json_decode($result);
}

  function get_token_native() {
          $config = get_config_user();

          $url = 'http://'.$config->url.':'.$config->port.'/ws/user/login';
          //iser user
          $sems = file_get_contents('http://'.$config->url.':'.$config->port.'/ws/user/filter');

          $decode = json_decode($sems);

          //dump($decode);
          $get_one_sem = $decode[0][0]->id_smt;

          $data = array(
            'username' => dec_data($config->username),
            'password' => dec_data($config->password),
            'semester' => array('id_smt' => $get_one_sem)
          );
          $token = service_request($data,$url);
          return $token;

  }

  function service_native($data,$url,$type='POST') {
      $ch = curl_init();

      curl_setopt($ch, CURLOPT_POST, 1); 

      $headers = array();
      $headers[] = 'Authorization: Bearer '.get_token();
      $headers[] = 'Content-Type: application/json';

      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
      $data = json_encode($data);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      //curl_setopt($ch, CURLOPT_HEADER, 1);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_ENCODING, '');
      curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
      curl_setopt($ch, CURLOPT_TIMEOUT, 0);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

      curl_setopt($ch, CURLOPT_VERBOSE, true);


      curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

      $result = curl_exec($ch);
      curl_close($ch);

      return json_decode($result);
  }

    function get_data_services($act,$filter,$order='',$limit='',$offset='') {
    $token = get_token();
      $data_dic = [
        'act' => $act,
        'token' => $token,
        'filter' => $filter,
        'order' => $order,
        'limit' => $limit,
        'offset' => $offset
      ];

      $hasil = service_request($data_dic);
      if ($hasil->data) {
          return $hasil->data;
      } else {
        return false;
          //echo $hasil->error_desc;
      }


  }



  function check_token() {
    $config = get_config_user();

      $data = array(
        'act' => 'GetToken',
        'username' => dec_data($config->username),
        'password' => dec_data($config->password)
      );
      $result = service_request($data);
      if (isset($result->error)) {
        echo $result->error;
        exit();
      }
      if ($result->data) {
         $token = $result->data->token;
         $array_return = array(
          'status' => 1,'error' => '','token' => $token);
         return $array_return;

      } else {
        if ($result->error_desc=='username/password salah') {
          echo "Ada Kesalahan Akun, Silakan Masuk ke Menu Master Data -> Config Akun Feeder. Edit. Pastikan Status Connected";
          exit();
        } else {
          $array_return = array(
          'status' => 0,'error' => $result->error_desc,'token' => '');
          return $array_return;
         //exit();
        }
        
      }
     

  }

  function get_token() {
    if (check_token()['status']=='1') {
      return check_token()['token'];
    } else {
      echo check_token()['error'];
      //exit();
    }
  }


  function get_service_url($type='rest') {

      global $db;
      $config = get_config_user();
      if ($config->live=='Y') {
        $url = $config->protokol.'://'.$config->url.':'.$config->port.'/ws/live2.php';
      } else {
        $url = $config->protokol.'://'.$config->url.':'.$config->port.'/ws/sandbox2.php';
      }

      return $url;
  }

  function get_config_user() {
    global $db;
    $config = $db->fetch_single_row('config_user','id',1);
    return $config;
  }

/**
 * updateMulti mapper array
 * @param  array $update_value      array recordset 
 * @param  array $primary_key_value primary key value recordset
 * @return array                    array recordset
 */
  function mapper($update_value,$primary_key_value) {
  $index=0;
  foreach ($update_value as $value) {
  $primary_value = $primary_key_value[$index];
  $append[] = array_map(function ($str) use($primary_value) { return "WHEN '".$primary_value."' THEN '$str'"; }, $value);
  $index++;
  }
  return $append;
}
/**
 * [updateMulti update bulk sql]
 * @param  [string] $table_name    table name
 * @param  array $update_value        array recordset with key value column_name and value of record
 * @param  string $primary_key_name   primary key column_name
 * @param  array $primary_key_value primary key value (single array )
 * @return boolean update query
 */
function updateMulti($table_name,$update_value,$primary_key_name,$primary_key_value) {
    global $db;
    $data_mapper_update = mapper($update_value,$primary_key_value);
    $data_mapper = array_keys($data_mapper_update[0]);
      $collection = [];
    foreach ($data_mapper as $key) {
      $collection[] = "$key = (CASE $primary_key_name ".implode(' ', array_unique(
          // `array_column` will give you all values under `$key`
          array_column($data_mapper_update, $key)
      ))." END)";
    }
    $primary_key_quote = sprintf("'%s'", implode("','", $primary_key_value ) );
    $query = "UPDATE $table_name SET ".implode(",", $collection)." WHERE $primary_key_name IN ($primary_key_quote)";
     $db->fetch_custom($query);
}

function write_data($filename,$data_record) {
  $json_data = json_encode($data_record);
  $json_data = trim($json_data, '[]');
  // read the file if present
  $handle = @fopen($filename, 'r+');

  // create the file if needed
  if ($handle === false)
  {
      $handle = fopen($filename, 'w+');
  }

  if ($handle)
  {
      // seek to the end
      fseek($handle, 0, SEEK_END);

      // file suda ada isi
      if (ftell($handle) > 0)
      {
          // move back a byte
          fseek($handle, -1, SEEK_END);

          // add the trailing comma
          fwrite($handle, ',', 1);

          // add the new json string
          fwrite($handle, $json_data.']');
      }
      else
      {
          // write the first event inside an array
          fwrite($handle, '['.$json_data.']');
          //fwrite($handle, $json_data);
      }

          // close the handle on the file
          fclose($handle);
  }
}

function write_push($filename,$data_record) {
  $json_data = json_encode($data_record);
  // read the file if present
  $handle = @fopen($filename, 'r+');

  // create the file if needed
  if ($handle === false)
  {
      $handle = fopen($filename, 'w+');
  }

    fwrite($handle, $json_data);
    fclose($handle);
}

function convert_ascii($string) 
{ 
  // Replace Single Curly Quotes
  $search[]  = chr(226).chr(128).chr(152);
  $replace[] = "'";
  $search[]  = chr(226).chr(128).chr(153);
  $replace[] = "'";
  // Replace Smart Double Curly Quotes
  $search[]  = chr(226).chr(128).chr(156);
  $replace[] = '"';
  $search[]  = chr(226).chr(128).chr(157);
  $replace[] = '"';
  // Replace En Dash
  $search[]  = chr(226).chr(128).chr(147);
  $replace[] = '--';
  // Replace Em Dash
  $search[]  = chr(226).chr(128).chr(148);
  $replace[] = '---';
  // Replace Bullet
  $search[]  = chr(226).chr(128).chr(162);
  $replace[] = '*';
  // Replace Middle Dot
  $search[]  = chr(194).chr(183);
  $replace[] = '*';
  // Replace Ellipsis with three consecutive dots
  $search[]  = chr(226).chr(128).chr(166);
  $replace[] = '...';
  // Apply Replacements
  $string = str_replace($search, $replace, $string);
  // Remove any non-ASCII Characters
  $string = preg_replace("/[^\x01-\x7F]/","", $string);
  $string = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $string);

  $string = preg_replace( '/[^[:print:]]/', '',$string);
  $string = trim($string);
  return $string; 
}

function dump($data) {
    echo "<pre>";
    print_r($data);
    echo "</pre>";
}
function action_response($error_message,$custom_response=array()) {
    $json_response = array();
    if ($error_message=='') {
        $status['status'] = "good";
        if (!empty($custom_response)) {
       foreach ($custom_response as $key => $value) {
          $status[$key] = $value;
       }

      }

     } else {
        $status['status'] = "error";
        $status['error_message'] = $error_message;
     }
    array_push($json_response, $status);
    echo json_encode($json_response);
    exit();
}