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


class c_backend extends CI_Controller {
  function __construct(){
    parent::__construct();    
    $this->load->model('m_masters');
        $this->load->helper(array('url','html','form'));
        $this->load->library('session');
    ini_set('max_execution_time', 0);    
    ini_set('memory_limit', '20000M');
    date_default_timezone_set("Asia/Jakarta");

    $this->data = array(
      'intervalinactnotpickedup' => '3',
      'intervalinterested' => '30'
    );
  }
  
  public function distribute ()
  {
      set_time_limit(0);
    $this->m_masters->distributedata();
    echo "Distribute Success!";

  }
  
  public function importFile(){
                $path = './assets/excels/';
                require_once APPPATH . "/third_party/PHPExcel.php";
                $config['upload_path'] = $path;
                $config['allowed_types'] = 'xlsx|xls|csv';
                $config['remove_spaces'] = TRUE;
                $config['max_execution_time'] = 259200;
                $config['max_input_time'] = 259200;

                $this->load->library('upload', $config);
                $this->upload->initialize($config);            
                if (!$this->upload->do_upload('uploadFile')) 
                {
                    $error = array('error' => $this->upload->display_errors());
                } 
                else 
                {
                    $data = array('upload_data' => $this->upload->data());
                }
                if(empty($error))
                {
                  if (!empty($data['upload_data']['file_name'])) 
                    {
                      $import_xls_file = $data['upload_data']['file_name'];
                      $goupload = 1;
                  } 
                  else 
                  {
                      $import_xls_file = 0;
                      $goupload = 0;
                  }
                  $inputFileName = $path . $import_xls_file;        
                  try 
                  {
                      $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                      $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                      $objPHPExcel = $objReader->load($inputFileName);
                      $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                      $flag = true;
                      $i=0;
                      $total = "";
                      foreach ($allDataInSheet as $value) 
                        {
                          if($flag){
                            $flag =false;
                            continue;
                          }
                          
                          if (substr($data['upload_data']['file_name'],0,3) <> 'wa_')
                          {
                            $inserdata[$i]['1'] = $value['A'];
                            $inserdata[$i]['2'] = $value['B'];
                            $this->m_masters->inserting("insert into work value ('".($i+1)."','" . $inserdata[$i]['1'] ."','".$inserdata[$i]['2'] ."','','','".$data['upload_data']['file_name']."','','',now())") ;  

                          }
                          else
                          {
                            $inserdata[$i]['1'] = $value['A'];
                            $inserdata[$i]['2'] = $value['B'];
                            $inserdata[$i]['3'] = $value['C'];
                            
                            $finalstring = explode(",",$inserdata[$i]['3']);
                            $jumlahrand = count($finalstring);

                            $jackpot = rand( 0 , $jumlahrand - 1);
                            $jackpotvalue = $finalstring[$jackpot];

                            $send = $this->insertwablastsatusatu(($i+1),$inserdata[$i]['1'],$inserdata[$i]['2'],$data['upload_data']['file_name'],$jackpotvalue,$inserdata[$i]['3']);
                            // $kirim = array(
                            //   'table_name'=>'tb_nomor',
                            //   'insert_column_1'=>'priority',
                            //   'insert_value_1'=> $i+1,
                            //   'insert_column_2'=>'nomor',
                            //   'insert_value_2'=>$inserdata[$i]['1'],
                            //   'insert_column_3'=>'username',
                            //   'insert_value_3'=>$inserdata[$i]['2'],
                            //   'insert_column_4'=>'done',
                            //   'insert_value_4'=>'0',
                            //   'insert_column_5'=>'grup_data',
                            //   'insert_value_5'=>$data['upload_data']['file_name'],
                            //   'insert_column_6'=>'msgcd',
                            //   'insert_value_6'=>$jackpotvalue,
                            //   'insert_column_7'=>'msgrandom',
                            //   'insert_value_7'=>$inserdata[$i]['3']
                            // );
                            // $total = $total .  json_encode($kirim).",";
                          }
                          $i++; 
                        }   
                         // $params = "[".substr($total,0,strlen($total) - 1)."]";
                         // $send = $this->insertwablast($params);

                        $querystring = "select * from tabledatamapping where tabledata = '".$data['upload_data']['file_name']."'";
                          $jumlahrow = $this->m_masters->querying($querystring)->num_rows();
                          if ($jumlahrow == 0)
                          { 
                            if (substr($data['upload_data']['file_name'],0,3) == 'wa_')
                          { 
                            $response = $this->inserttabledatamapping($data['upload_data']['file_name']); 
                            // $querystring = "select createddate from tabledatamapping where operatorgroup = '' and tabledata = '" .$data['upload_data']['file_name']. "'";
                            // $createddate = $this->m_masters->querying($querystring)->result()[0]->createddate;

                            if(strpos(json_decode($response)->{'Info'} ,"Berhasil disimpan") > 1)
                            {
                              $querystring = "insert into tabledatamapping values ('" .$data['upload_data']['file_name']. "','','1','Admin',now())";
                                $this->m_masters->querying($querystring);
                                // $pesan = json_decode($response)->{'Info'};
                                $pesan = "Berhasil disimpan di database babi dan TMP!";
                                // $pesan = $params;
                            }
                            else
                            {
                              $pesan = "Koneksi ke babi air putus, maka file gagal diupload!";
                            }
                          }
                          else
                          {
                            $querystring = "insert into tabledatamapping values ('" .$data['upload_data']['file_name']. "','','1','Admin',now())";
                              $this->m_masters->querying($querystring);
                              $pesan = "Berhasil disimpan di local TMP!";
                          }
                          }     

                        
                      unlink("assets/excels/".$data['upload_data']['file_name']);     
              } catch (Exception $e)
              {
                     die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                              . '": ' .$e->getMessage());
              }
                // $this->session->set_flashdata('message', "Data Submission Successful!");
                $this->session->set_flashdata('message', $pesan );
                // $this->session->set_flashdata('message', $response);
                }
                else
                {
                  $this->session->set_flashdata('message',"No Excel");
                  
                    echo $error['error'];
                }
        redirect('c_modules');
        // $this->load->view('v_IC',$data);
    }


}