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

class c_modules 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'
    );

     // if(empty($this->session->userdata("username")))
   //       {
   //         redirect(base_url(),'refresh');
   //       }
  }
  public function index()
  {
    if (empty($this->session->userdata('username')))
    { 
      redirect('c_login');
    }
    else
    {
      $data['title'] = "Main Modules";


      $querystring = "select b.response, coalesce(a.jumlah,'0') jumlah from responses b left join (select response, count(1) as jumlah from work group by response) a on a.response = b.response order by b.response";
      $data['dashboard'] = $this->m_masters->querying($querystring);
      $data['dashboardarr'] = $data['dashboard']->result();


      $querystring = "select count(1) as allcalls from work";
      $data['allcalls'] = $this->m_masters->querying($querystring)->result();
      $this->load->view('v_modules',$data); 
    }
  }

  public function SignOut()
  { 
    // $querystring = "delete from login where operator = '". $this->session->userdata('username')."'";
    // $this->m_masters->querying($querystring);
    session_unset();
    session_destroy();


    redirect('c_login/index');

  }
  public function saveusername()
    {
        $Username = $this->input->post('Username');
        $PhoneNo = $this->input->post('PhoneNo');
        $OperatorGroup = $this->input->post("OperatorGroup");
        $querystring = "update work set Username ='" . $Username ."' where PhoneNo = '".$PhoneNo . "' and OperatorGroup = '". $OperatorGroup ."'" ;
        $this->m_masters->updating($querystring);
    }
   
    public function insertwablast($insertthis)
    {
      // $kirim = array(
      //  'OG' => $phoneno,
      //  'GSecret' => $username,
      //  'Creator' => $runningno,
      //  'CreatedDate' => 'bebas'
      // );

      // $kirim = array(
      //  'nomor' => $phoneno,
      //  'username' => $username,
      //  'done'=>"0",
       //  'grup_data'=>"TEST_LAGI2",
       //  'priority'=>$runningno,
       //  'remarks'=> "Blaster"
      // );

    // $kirim = array(
    //     'table_name'=>'tb_nomor',
    //     'insert_column_1'=>'priority',
    //     'insert_value_1'=> $runningno,
    //     'insert_column_2'=>'nomor',
    //     'insert_value_2'=>$phoneno,
    //     'insert_column_3'=>'username',
    //     'insert_value_3'=>$username,
    //     'insert_column_4'=>'done',
    //     'insert_value_4'=>'0',
    //     'insert_column_5'=>'grup_data',
    //     'insert_value_5'=>$grup,
    //     'insert_column_6'=>'msgcd',
    //     'insert_value_6'=>$msg,
    //     'insert_column_7'=>'msgrandom',
    //     'insert_value_7'=>$msgrand
    //   );

  //     $params = "[" . json_encode($kirim) . "]";

        // $ch = curl_init('http://localhost/skypeadv/C_api');

       $ch = curl_init('https://katon.babiair.com/Apitmpl2RpsYoaPusDmlLdhOhRmUPbUt9Eb9da40rvLCH/katon_insert_7');
           curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
           curl_setopt($ch, CURLOPT_POSTFIELDS, $insertthis);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
           curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
               'Content-Type: application/json',                                                                                
               'Content-Length: ' . strlen($insertthis))                                                                      
           );
           curl_exec($ch);
       return $ch;
    }
    public function insertwablastsatusatu($runningno,$phoneno,$username,$grup,$msg,$msgrand)
    {
      $kirim = array(
        'table_name'=>'tb_nomor',
        'insert_column_1'=>'priority',
        'insert_value_1'=> $runningno,
        'insert_column_2'=>'nomor',
        'insert_value_2'=>$phoneno,
        'insert_column_3'=>'username',
        'insert_value_3'=>$username,
        'insert_column_4'=>'done',
        'insert_value_4'=>'0',
        'insert_column_5'=>'grup_data',
        'insert_value_5'=>$grup,
        'insert_column_6'=>'msgcd',
        'insert_value_6'=>$msg,
        'insert_column_7'=>'msgrandom',
        'insert_value_7'=>$msgrand
      );

      $params = "[" . json_encode($kirim) . "]";

      $ch = curl_init('https://katon.babiair.com/Apitmpl2RpsYoaPusDmlLdhOhRmUPbUt9Eb9da40rvLCH/katon_insert_7');
           curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
           curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
           curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
               'Content-Type: application/json',                                                                                
               'Content-Length: ' . strlen($params))                                                                      
           );
           curl_exec($ch);
       return $ch;
    }

    public function inserttabledatamapping($grup)
    {
      $createddate = date("Y-m-d H:i:s");
      $kirim = array(
        'table_name'=>'tabledatamapping',
        'insert_column_1'=>'Tabledata',
        'insert_value_1'=> $grup,
        'insert_column_2'=>'OperatorGroup',
        'insert_value_2'=>'',
        'insert_column_3'=>'ID',
        'insert_value_3'=>'1',
        'insert_column_4'=>'Creator',
        'insert_value_4'=>$this->session->userdata("username"),
        'insert_column_5'=>'CreatedDate',
        'insert_value_5'=>$createddate
      );

       $params = "[" . json_encode($kirim) . "]";
        // $ch = curl_init('http://localhost/skypeadv/C_api');
       $ch = curl_init('https://katon.babiair.com/Apitmpl2RpsYoaPusDmlLdhOhRmUPbUt9Eb9da40rvLCH/katon_insert_5');
           curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
           curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
           curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
               'Content-Type: application/json',                                                                                
               'Content-Length: ' . strlen($params))                                                                      
           );
           $ch = curl_exec($ch);
       return $ch;
    }

    public function warenametabledata($newtabledata,$tabledata)
    {
    $kirim = array(
        'table_name'=>'tabledatamapping',
        'update_column_1'=>'Tabledata',
        'update_value_1'=> $newtabledata,
        'where_column_1'=>'Tabledata',
        'where_value_1'=>$tabledata
      );

       $params =  json_encode($kirim) ;
        // $ch = curl_init('http://localhost/skypeadv/C_api');
       $ch = curl_init('https://katon.babiair.com/Apitmpl2RpsYoaPusDmlLdhOhRmUPbUt9Eb9da40rvLCH/katon_update_1_1');
           curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
           curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
           curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
               'Content-Type: application/json',                                                                                
               'Content-Length: ' . strlen($params))                                                                      
           );
           $response = curl_exec($ch);
       return $response;
    }
    public function warenamework($newtabledata,$tabledata)
    {
    $kirim = array(
        'table_name'=>'tb_nomor',
        'update_column_1'=>'grup_data',
        'update_value_1'=> $newtabledata,
        'where_column_1'=>'grup_data',
        'where_value_1'=>$tabledata
      );

       $params =  json_encode($kirim);
        // $ch = curl_init('http://localhost/skypeadv/C_api');
       $ch = curl_init('https://katon.babiair.com/Apitmpl2RpsYoaPusDmlLdhOhRmUPbUt9Eb9da40rvLCH/katon_update_1_1');
           curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
           curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
           curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
               'Content-Type: application/json',                                                                                
               'Content-Length: ' . strlen($params))                                                                      
           );
           curl_exec($ch);
       $response = curl_exec($ch);
       return $response;
    }

    public function wasubmittabledata($tabledata,$grup,$id)
    {
      $createddate = date("Y-m-d H:i:s");
    $kirim = array(
        'table_name'=>'tabledatamapping',
        'insert_column_1'=>'Tabledata',
        'insert_value_1'=> $tabledata,
        'insert_column_2'=>'OperatorGroup',
        'insert_value_2'=>$grup,
        'insert_column_3'=>'ID',
        'insert_value_3'=>$id,
        'insert_column_4'=>'Creator',
        'insert_value_4'=>$this->session->userdata("username"),
        'insert_column_5'=>'CreatedDate',
        'insert_value_5'=>$createddate
      );

       $params =  "[" . json_encode($kirim) . "]";
        // $ch = curl_init('http://localhost/skypeadv/C_api');
       $ch = curl_init('https://katon.babiair.com/Apitmpl2RpsYoaPusDmlLdhOhRmUPbUt9Eb9da40rvLCH/katon_insert_5');
           curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
           curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
           curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
               'Content-Type: application/json',                                                                                
               'Content-Length: ' . strlen($params))                                                                      
           );
           $response = curl_exec($ch);
       return $response;
    }

    public function waupdatetabledata($tabledata,$grup,$id)
    {
    $kirim = array(
        'table_name'=>'tabledatamapping',
        'update_column_1'=>'ID',
        'update_value_1'=> $id,
        'where_column_1'=>'Tabledata',
        'where_value_1'=>$tabledata,
        'where_column_2'=>'OperatorGroup',
        'where_value_2'=>$grup
      );

       $params =  json_encode($kirim) ;
        // $ch = curl_init('http://localhost/skypeadv/C_api');
       $ch = curl_init('https://katon.babiair.com/Apitmpl2RpsYoaPusDmlLdhOhRmUPbUt9Eb9da40rvLCH/katon_update_1_2');
           curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
           curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
           curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
               'Content-Type: application/json',                                                                                
               'Content-Length: ' . strlen($params))                                                                      
           );
          $response = curl_exec($ch);
       return $response;
    }

    public function wainsertmessage($cdselector,$message)
    {
      $createddate = date("Y-m-d H:i:s");
    $kirim = array(
        'table_name'=>'messages',
        'insert_column_1'=>'MsgCd',
        'insert_value_1'=> $cdselector,
        'insert_column_2'=>'Message',
        'insert_value_2'=>$message,
        'insert_column_3'=>'Creator',
        'insert_value_3'=>$this->session->userdata("username"),
        'insert_column_4'=>'CreatedDate',
        'insert_value_4'=>$createddate,
      );

       $params =  "[" . json_encode($kirim) . "]";
        // $ch = curl_init('http://localhost/skypeadv/C_api');
       $ch = curl_init('https://katon.babiair.com/Apitmpl2RpsYoaPusDmlLdhOhRmUPbUt9Eb9da40rvLCH/katon_insert_4');
           curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
           curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
           curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
               'Content-Type: application/json',                                                                                
               'Content-Length: ' . strlen($params))                                                                      
           );
           curl_exec($ch);
       return $params;
    }

    public function apicheckavail($username)
    {
      $kirim = array(
        'OG'=>$this->session->userdata('privilege'),
        'Username'=>$username
      );

       $params =  json_encode($kirim) ;
        // $ch = curl_init('http://localhost/skypeadv/C_api');
       $ch = curl_init('http://localhost/moonmoney/C_api/checkname');
       // $ch = curl_init('https://moneymoon.club/C_api/checkname');
           curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
           curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
           curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
               'Content-Type: application/json',                                                                                
               'Content-Length: ' . strlen($params))                                                                      
           );
           $response = curl_exec($ch);
       return $response;
    }

    public function apicheckavailnorek($norek)
    {
      $kirim = array(
        'OG'=>$this->session->userdata('privilege'),
        'Norek'=>$norek
      );

       $params =  json_encode($kirim) ;
        // $ch = curl_init('http://localhost/skypeadv/C_api');
       $ch = curl_init('http://localhost/moonmoney/C_api/checkrek');
       // $ch = curl_init('https://moneymoon.club/C_api/checkrek');
           curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
           curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
           curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
               'Content-Type: application/json',                                                                                
               'Content-Length: ' . strlen($params))                                                                      
           );
           $response = curl_exec($ch);
       return $response;
    }
    public function wablastberapa($datefrom,$dateto)
    {
    $kirim = array(
        'tanggal_done_from'=>$datefrom,
        'tanggal_done_to'=>$dateto
      );

       $params =  json_encode($kirim) ;
        // $ch = curl_init('http://localhost/skypeadv/C_api');
       $ch = curl_init('https://katon.babiair.com/Apitmpl2RpsYoaPusDmlLdhOhRmUPbUt9Eb9da40rvLCH/katon_get');
           curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
           curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
           curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
               'Content-Type: application/json',                                                                                
               'Content-Length: ' . strlen($params))                                                                      
           );
           $response = curl_exec($ch);
       return $response;
    }


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

  public function testing()
  {
    $data['modulecode'] = $this->input->post('modulecode');
    $this->load->view("v_testing" ,$data);      
  }

  public function uploads()
  {
    $data['modulecode'] = $this->input->post('modulecode');
    $this->load->view("v_upload",$data);
  }

  public function deleterequest()
  {
    $errmsg = "";
    $phoneno=$this->input->post("phoneno");
    $tabledata=$this->input->post("tabledata");
        $creator=$this->input->post("creator");
        $creatoroperatorgroup=$this->input->post("creatoroperatorgroup");
        $querystring = "delete from players where phoneno = '" . $phoneno . "' and tabledata = '" . $tabledata ."' and operator = '".$creator ."' and operatorgroup = '" . $creatoroperatorgroup ."'";
        $this->m_masters->querying($querystring);
        $errmsg = '<div class="alert alert-success alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <h5><i class="icon fas fa-check"></i>Success</h5>
                    Delete Successful !
                    </div>';
        echo $errmsg;
  }

  public function getcallhistory()
  {
    $errmsg = "";
    $show = "";
    $phoneno=$this->input->post("phoneno");
    $tabledata=$this->input->post("tabledata");
    $operator=$this->input->post("operator");
    $operatorgroup=$this->input->post("operatorgroup");
    $querystring = "select uploaddate, keterangan from work where phoneno = '".$phoneno."' and tabledata = '".$tabledata ."' and creator = '".$operator ."' and creatoroperatorgroup = '".$operatorgroup. "' order by uploaddate desc";
    $hist = $this->m_masters->querying($querystring)->result();
    if (count($hist)<0)
    {
      $show = '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              No Chat History Found
                            </div>';
    }
    else
    {
      for($i = 0; $i < count($hist) ; $i++)
      {
        $show = $show ."Called at : " .$hist[$i]->uploaddate;
        $show = $show . "\nKeterangan : ".$hist[$i]->keterangan."\n\n";
      }
    }
        
    echo $show;
    // echo count($hist). " ".$hist[]
    // echo "ads";
  }
  public function requesttocs()
  {
    $errmsg = "";
    $phoneno=$this->input->post("phoneno");
    $username=$this->input->post("username");
    $password = $this->input->post("password");
    $no=$this->input->post("no");
    $name=$this->input->post("name");
    $bank=$this->input->post("bank");
    $website=$this->input->post("website");
    $wa=$this->input->post("wa");
    $referral=$this->input->post("referral");
    $tabledata=$this->input->post("tabledata");
    $creator=$this->input->post("creator");
    $creatoroperatorgroup=$this->input->post("creatoroperatorgroup");
    $note = $this->input->post("note");


    $querycheck = "select * from players where phoneno = '" . $phoneno ."' and tabledata = '".$tabledata. "' and operator = '".$creator ."' and operatorgroup = '" .$creatoroperatorgroup . "'";
    $exist = $this->m_masters->querying($querycheck)->num_rows();
    if($exist > 0)
    {
      $querystring = "update players set username = '" .$username.  "',password = '" .$password.  "', nomorrekening = '".$no . "', namarekening = '".$name . "', bankrekening = '".$bank ."', website = '" .$website ."', wano = '".$wa ."', referral = '".$referral ."',createddate=now(), keterangan = '".$note ."', status = 'Open' where phoneno = '".$phoneno ."' and tabledata = '".$tabledata ."' and operator = '".$creator ."' and operatorgroup = '".$creatoroperatorgroup ."'"  ;
      $errmsg = '<div class="alert alert-success alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <h5><i class="icon fas fa-check"></i>Success</h5>
                    Data Updated Successfully!
                  </div>';
    }
    else
    {
      $querystring = "insert into players values('".$phoneno . "','".$username . "','".$password."','" .$no ."','".$name ."','".$bank."','".$website."','".$wa."','".$referral."','".$tabledata."','".$creator."','".$creatoroperatorgroup. "',now(),'Open','".$note ."')";
      $errmsg ='<div class="alert alert-success alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <h5><i class="icon fas fa-check"></i>Success</h5>
                    Data Inserted Successfully!
                  </div>';
    }

    // echo $querystring;
    $this->m_masters->querying($querystring);
    echo $errmsg;
  }

  public function createplayer()
  {
    $errmsg = "";
    $phoneno=$this->input->post("phoneno");
    $tabledata=$this->input->post("tabledata");
    $creator=$this->input->post("creator");
    $creatoroperatorgroup=$this->input->post("creatoroperatorgroup");
    $note = $this->input->post("note");
    $password = $this->input->post("password");


    $querystring = "update players set createddate=now(),password='".$password."', keterangan = '".$note ."', status = 'Created' where phoneno = '".$phoneno ."' and tabledata = '".$tabledata ."' and operator = '".$creator ."' and operatorgroup = '".$creatoroperatorgroup ."'"  ;
    $this->m_masters->querying($querystring);



    $querystring = "insert into work values ('Callback','".$phoneno."','','User Created','','".$tabledata."','".$creatoroperatorgroup."','".$creator."',now())";
    $this->m_masters->querying($querystring);
    $errmsg = '<div class="alert alert-success alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <h5><i class="icon fas fa-check"></i>Success</h5>
                    Data Saved as Created!
                  </div>';
    echo $errmsg;
  }

  public function reviseplayer()
  {
    $errmsg = "";
    $phoneno=$this->input->post("phoneno");
    $tabledata=$this->input->post("tabledata");
    $creator=$this->input->post("creator");
    $creatoroperatorgroup=$this->input->post("creatoroperatorgroup");
    $note = $this->input->post("note");


    $querystring = "update players set createddate=now(), keterangan = '".$note ."', status = 'Reopen' where phoneno = '".$phoneno ."' and tabledata = '".$tabledata ."' and operator = '".$creator ."' and operatorgroup = '".$creatoroperatorgroup ."'"  ;
    $this->m_masters->querying($querystring);
    $errmsg = '<div class="alert alert-success alert-dismissible">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                  <h5><i class="icon fas fa-check"></i>Success</h5>
                  Data is passed back to Tele!
                </div>'; 
    echo $errmsg;
  }

  public function rejectplayer()
  {
    $errmsg = "";
    $phoneno=$this->input->post("phoneno");
    $tabledata=$this->input->post("tabledata");
    $creator=$this->input->post("creator");
    $creatoroperatorgroup=$this->input->post("creatoroperatorgroup");
    $note = $this->input->post("note");


    $querystring = "update players set createddate=now(), keterangan = '".$note ."', status = 'Reject' where phoneno = '".$phoneno ."' and tabledata = '".$tabledata ."' and operator = '".$creator ."' and operatorgroup = '".$creatoroperatorgroup ."'"  ;
    $this->m_masters->querying($querystring);
    $querystring = "insert into work values ('Callback','".$phoneno."','','User Created','','".$tabledata."','".$creatoroperatorgroup."','".$creator."',now())";
    $this->m_masters->querying($querystring);
    $errmsg = '<div class="alert alert-success alert-dismissible">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                  <h5><i class="icon fas fa-check"></i>Success</h5>
                  Data Saved as Rejected!
                </div>';

    
    echo $errmsg;
  }



  public function playerrequest()
  {
    $phoneno = $this->input->post("phoneno");

    $querystring = "select * from players where phoneno like '%".$phoneno."' and status = 'open' and website = '". $this->session->userdata('privilege')."' order by createddate";
    

    $data['listuserarr'] = $this->m_masters->querying($querystring);
    $data['listuser'] = $data['listuserarr']->result();
    // echo $querystring;
    $this->load->view("v_PR_dg",$data);
  }


  public function requestplayer()
  {
    $errmsg = "";
    $request = $this->input->post("request");
    $phoneno = $this->input->post("phoneno");
    $username = $this->input->post("username");
    $bankno = $this->input->post("bankno");
    $bankname = $this->input->post("bankname");
    $bank = $this->input->post("bank");
    $website = $this->input->post("website");
    $tabledata = $this->input->post("tabledata");

    if($username == 'blank')
    {
      $username = '';
    }
    if($bank == 'blank')
    {
      $bank = '';
    }
    if($website == 'blank')
    {
      $website = '';
    }
    if($tabledata == 'blank')
    {
      $tabledata = '';
    }


    $querystring = "select website from websites";
      $data['listwebsite'] = $this->m_masters->querying($querystring)->result();

      $querystring = "select bank from bankmaster";
      $data['listbank'] = $this->m_masters->querying($querystring)->result();
      if($request == "missing")
      {
      $querystring = "select * from (select asdf.phoneno,asdf.response, asdf.tabledata, asdf.creatoroperatorgroup, asdf.creator, asdf.lastresponsedate, asdf.workketerangan, e.username, e.password,e.nomorrekening, e.namarekening, e.bankrekening, e.website, e.wano, e.referral,e.status,e.keterangan from (
        select d.lastresponsedate,a.phoneno,a.username,a.response,a.keterangan as workketerangan,a.tabledata,a.creatoroperatorgroup,a.creator from work a 
        inner join 
        (
        select phoneno, creator,creatoroperatorgroup,tabledata ,max(uploadDate) As lastresponsedate from work where response <> ''
        group by phoneno,creator,creatoroperatorgroup,tabledata
        )d
        on a.PhoneNo = d.PhoneNo
        and a.Creator = d.Creator
        and a.Creatoroperatorgroup = d.Creatoroperatorgroup
        and a.tabledata = d.tabledata
        and a.Uploaddate = d.lastresponsedate
        and a.response in ('interested','User Created') and a.creator = '".$this->session->userdata("username").
        "' and d.CreatorOperatorGroup = '" . $this->session->userdata("privilege").
        "' and a.phoneno like '%" . $phoneno ."%'
        order by a.uploaddate
              ) asdf
              left join
               players e 
              on asdf.PhoneNo = e.PhoneNo
        and asdf.Creator = e.Operator
        and asdf.Creatoroperatorgroup = e.OperatorGroup
        and asdf.tabledata = e.tabledata) s where s.status is null order by lastresponsedate limit 5";
    }
    else
    {
      $querystring = "select * from (select asdf.phoneno,asdf.response, asdf.tabledata, asdf.creatoroperatorgroup, asdf.creator, asdf.lastresponsedate, asdf.workketerangan,
        e.username , e.password,e.nomorrekening, e.namarekening, e.bankrekening, e.website, e.wano, e.referral,e.status,e.keterangan from (
        select d.lastresponsedate,a.phoneno,a.username,a.response, a.keterangan as workketerangan, a.tabledata,a.creatoroperatorgroup,a.creator from work a
        inner join 
        (
        select phoneno, creator,creatoroperatorgroup,tabledata ,max(uploadDate) As lastresponsedate from work where response <> ''
        group by phoneno,creator,creatoroperatorgroup,tabledata
        )d
        on a.PhoneNo = d.PhoneNo
        and a.Creator = d.Creator
        and a.Creatoroperatorgroup = d.Creatoroperatorgroup
        and a.tabledata = d.tabledata
        and a.Uploaddate = d.lastresponsedate
        and a.response in ('interested','user created') and a.creator = '".$this->session->userdata("username").
        "' and d.CreatorOperatorGroup = '" . $this->session->userdata("privilege").
        "'
        and a.phoneno like '%" . $phoneno ."%'
        order by a.uploaddate
              ) asdf
              left join
              players e 
              on asdf.PhoneNo = e.PhoneNo
        and asdf.Creator = e.Operator
        and asdf.Creatoroperatorgroup = e.OperatorGroup
        and asdf.tabledata = e.tabledata
              where e.website like '%" .$website ."'
              and e.username like '%".$username . "'
        and e.nomorrekening like '%" . $bankno ."%'
        and e.namarekening like '%" . $bankname ."%'
        and e.bankrekening like '".$bank . "%'
              and e.tabledata like '" .$tabledata ."%')s where s.username is not null and s.status = 'reopen' order by lastresponsedate limit 5";
    }
    $data['listuserarr'] = $this->m_masters->querying($querystring);
    $data['listuser'] = $data['listuserarr']->result();
    // echo $querystring;
    $this->load->view("v_PM_dg",$data);
  }


  public function main()
  {
    if(empty($this->session->userdata('username')))
    {
      echo "0";
    }
    else
    {
      $data['modulecode'] = $this->input->post('modulecode');
      $modulecode = $this->input->post('modulecode');

      if($modulecode == "IO"||$modulecode == "PNS" || $modulecode == "ILK" || $modulecode == "TDM" || $modulecode == "reports")  
      {
        $data['listoperatorgroups'] = $this->m_masters->getOperatorGroups()->result();
      }
      if($modulecode == "PNS" ) 
      {
        $data['listoperators'] = $this->m_masters->getOperators()->result();
      }
      if($modulecode == "ILK") 
      {
        $querystring = "select priority from priority";
        $data['listpriority'] = $this->m_masters->querying($querystring)->result();
      }
      if($modulecode == "TDM" ) 
      {
        $querystring = "select * from tabledatamapping";
        $data['listtabledatamapping'] = $this->m_masters->querying($querystring)->result();
      }
      if($modulecode == "TDM" || $modulecode == "RTD" || $modulecode == "reports") 
      {
        $querystring = "select distinct tabledata from tabledatamapping";
        $data['listtabledata'] = $this->m_masters->querying($querystring)->result();
      }
      // if($modulecode == "PM")
      // {
      //  $querystring = "select website from websites";
      //  $data['listwebsite'] = $this->m_masters->querying($querystring)->result(); 
      // }
      // if($modulecode == "PM")
      // {
      //  $querystring = "select bank from bankmaster";
      //  $data['listbank'] = $this->m_masters->querying($querystring)->result(); 
      // }

      if($modulecode == "CPT")
      {
        $querystring = "select operator from operators where operatorgroup = '" . $this->session->userdata("privilege") . "'";
        $data['listoperators'] = $this->m_masters->querying($querystring)->result();
      }

      // if($modulecode == "PM")
      // {
      //  $querystring = "select e.username from (
    //      select d.lastresponsedate,a.phoneno,a.username,a.response,a.tabledata,a.creatoroperatorgroup,a.creator from work a
      //  inner join tabledatamapping b on a.Tabledata = b.Tabledata 
      //  inner join 
      //  (
      //  select phoneno, creator,creatoroperatorgroup,tabledata ,max(uploadDate) As lastresponsedate from work where response <> ''
      //  group by phoneno,creator,creatoroperatorgroup,tabledata
      //  )d
      //  on a.PhoneNo = d.PhoneNo
      //  and a.Creator = d.Creator
      //  and a.Creatoroperatorgroup = d.Creatoroperatorgroup
      //  and a.tabledata = d.tabledata
      //  and a.Uploaddate = d.lastresponsedate
      //  and a.response in ('interested','user created') and a.creator = '".$this->session->userdata("username").
      //  "' and b.OperatorGroup = '" . $this->session->userdata("privilege").
      //  "' and b.ID <> '0' and b.ID <> 'inactive' 
      //  order by a.uploaddate
    //           ) asdf
    //           left join
    //            players e 
    //           on asdf.PhoneNo = e.PhoneNo
      //  and asdf.Creator = e.Operator
      //  and asdf.Creatoroperatorgroup = e.OperatorGroup
      //  and asdf.tabledata = e.tabledata
    //           where e.username is not null";
    //           $data['listusername'] = $this->m_masters->querying($querystring)->result();
      // }
      if($modulecode == "dashboard")
      {
        $querystring = "select b.response, coalesce(a.jumlah,'0') jumlah from responses b left join (select response, count(1) as jumlah from work group by response) a on a.response = b.response order by b.response";
        $data['dashboard'] = $this->m_masters->querying($querystring);
        $data['dashboardarr'] = $data['dashboard']->result();
        $querystring = "select count(1) as allcalls from work";
        $data['allcalls'] = $this->m_masters->querying($querystring)->result();
        
        // $querystring = "select now() as skrg";
        // $data['allcalls'] = $this->m_masters->querying($querystring)->result();
        // echo $data['allcalls'][0]->skrg;
        // $beforerand = "1,2,3";
        // $finalstring = explode(",",$beforerand);
        // $jumlahrand = count($finalstring);

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

        // echo $beforerand;
        // echo $jumlahrand;
        // echo $jackpot;
        // echo $jackpotvalue;

      }

      // datagrid
      if($modulecode == 'IOG')
      {
      $data['datatable'] = $this->m_masters->querying("select operatorgroup, creator, createddate from operatorgroups order by createddate")->result();
      }

      if($modulecode == 'IO')
      {
       $data['datatable'] = $this->m_masters->querying("select operator, operatorgroup, creator, createddate from operators ")->result();
      }
      $this->load->view("v_".$modulecode,$data);
    }
  
  }
  public function preview()
  {
    $errmsg = "";
      
      $datefrom = $this->input->post("datefrom");
      $dateto = $this->input->post("dateto");
      $reporttype = $this->input->post("reporttype");
      $ogselector = $this->input->post("ogselector");
      $outstanding = $this->input->post("outstanding");

      if($datefrom == "" && $reporttype <> "sisadata" && $reporttype <> "cbos" && $reporttype <> "requestplayer")
      {
        $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill date from!
                            </div>';
      }
      if($dateto == "" && $reporttype <> "sisadata" && $reporttype <> "cbos" && $reporttype <> "requestplayer")
      {
        $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill date to!
                            </div>';
      }
      if ($reporttype == "blank")
      {
        $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill Report Type!
                            </div>';
      }
      if ($errmsg == "")
      {
        $datefrom = date('Y-m-d', strtotime($datefrom));
        $dateto = date('Y-m-d', strtotime($dateto));
        
        // echo $reporttype;
        if($reporttype == "blastberapa")
        { 
          $datefrom = $datefrom . " 00:00:00";
          $dateto = $dateto . " 23:59:59";
          $response = $this->wablastberapa($datefrom,$dateto);
          $data['listblast'] = json_decode($response); 
          // echo json_decode($response)[3]->{'tanggal'};
          // echo $response;
          // echo $listblast[3]->operatorgroup;
          // echo count($listblast);
          // echo $datefrom . $dateto;
          if(count($data['listblast']) == 0)
          {
            echo '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              No Records Found!
                            </div>';
          }
          else
          {
            $this->load->view("v_blastberapa_dg",$data);
            }

        }
        if($reporttype == "rawreport")
          {
            $data['workarr'] = $this->m_masters->reportrawreport($datefrom,$dateto);
          $data['work'] = $data['workarr']->result();
          if($data['workarr']->num_rows() < 1)
          {
            echo '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              No Records Found!
                            </div>';
          }
          else{
            $this->load->view("v_rawreport_dg",$data);
            }
          }
          if($reporttype == "calloperator")
          {
            // echo $this->session->userdata('privileges') . "datefrom: ".$datefrom ."dateto: ". $dateto ."ogselector: ". $ogselector;
            if ($this->session->userdata('privileges') == 'Admin')
            {
              if ($ogselector == 'blank')
              {
                $data['workarr'] = $this->m_masters->reportcalloperator($datefrom,$dateto);
                // echo 'kosong';
            }
            else
            {
              $data['workarr'] = $this->m_masters->reportcalloperator_og($datefrom,$dateto,$ogselector);
              // echo $ogselector;
            }
          }
          else
          {
            $data['workarr'] = $this->m_masters->reportcalloperator_og($datefrom,$dateto,$this->session->userdata('privilege'));
          }
          $data['work'] = $data['workarr']->result();
          if($data['workarr']->num_rows() < 1)
          {
            echo '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              No Records Found!
                            </div>';
          }
          else
          {
              $this->load->view("v_calloperator_dg",$data);
            }
          // echo $data['workarr']->num_rows();
          }
          if($reporttype == "requestplayer")
          {
            if($outstanding == 'goal')
            {
              $status = "s.status in ('Created','Reject') ";
            }
            else
            {
              $status = "s.status in ('Open','Reopen') or s.status is null ";
            }

            if ($this->session->userdata('privileges') == 'Admin')
            {
              if ($ogselector == 'blank')
              {
                $querystring = "select * from (select asdf.phoneno,asdf.response, asdf.tabledata, asdf.creatoroperatorgroup, asdf.creator, asdf.lastresponsedate, asdf.workketerangan, e.username, e.password,e.nomorrekening, e.namarekening, e.bankrekening, e.website, e.wano, e.referral,e.status,e.keterangan from (
        select d.lastresponsedate,a.phoneno,a.username,a.response,a.keterangan as workketerangan,a.tabledata,a.creatoroperatorgroup,a.creator from work a
        inner join 
        (
        select phoneno, creator,creatoroperatorgroup,tabledata ,max(uploadDate) As lastresponsedate from work where response <> ''
        group by phoneno,creator,creatoroperatorgroup,tabledata
        )d
        on a.PhoneNo = d.PhoneNo
        and a.Creator = d.Creator
        and a.Creatoroperatorgroup = d.Creatoroperatorgroup
        and a.tabledata = d.tabledata
        and a.Uploaddate = d.lastresponsedate
        and a.response in ('interested','User Created') and d.CreatorOperatorGroup = '" . $this->session->userdata("privilege").
        "'
              ) asdf
              left join
               players e 
              on asdf.PhoneNo = e.PhoneNo
        and asdf.Creator = e.Operator
        and asdf.Creatoroperatorgroup = e.OperatorGroup
        and asdf.tabledata = e.tabledata) s where ".$status ." order by lastresponsedate" ;
               }
              else
              {
                $querystring = "select * from (select asdf.phoneno,asdf.response, asdf.tabledata, asdf.creatoroperatorgroup, asdf.creator, asdf.lastresponsedate, asdf.workketerangan, e.username, e.password,e.nomorrekening, e.namarekening, e.bankrekening, e.website, e.wano, e.referral,e.status,e.keterangan from (
        select d.lastresponsedate,a.phoneno,a.username,a.response,a.keterangan as workketerangan,a.tabledata,a.creatoroperatorgroup,a.creator from work a
        inner join 
        (
        select phoneno, creator,creatoroperatorgroup,tabledata ,max(uploadDate) As lastresponsedate from work where response <> ''
        group by phoneno,creator,creatoroperatorgroup,tabledata
        )d
        on a.PhoneNo = d.PhoneNo
        and a.Creator = d.Creator
        and a.Creatoroperatorgroup = d.Creatoroperatorgroup
        and a.tabledata = d.tabledata
        and a.Uploaddate = d.lastresponsedate
        and a.response in ('interested','User Created') and d.CreatorOperatorGroup = '" . $ogselector.
        "'
              ) asdf
              left join
               players e 
              on asdf.PhoneNo = e.PhoneNo
        and asdf.Creator = e.Operator
        and asdf.Creatoroperatorgroup = e.OperatorGroup
        and asdf.tabledata = e.tabledata) s where ".$status  ." order by lastresponsedate" ;
              }
            }
            else if ($this->session->userdata('privileges') == 'Supervisor')
            {
              $querystring = "select * from (select asdf.phoneno,asdf.response, asdf.tabledata, asdf.creatoroperatorgroup, asdf.creator, asdf.lastresponsedate, asdf.workketerangan, e.username, e.password,e.nomorrekening, e.namarekening, e.bankrekening, e.website, e.wano, e.referral,e.status,e.keterangan from (
        select d.lastresponsedate,a.phoneno,a.username,a.response,a.keterangan as workketerangan,a.tabledata,a.creatoroperatorgroup,a.creator from work a
        inner join 
        (
        select phoneno, creator,creatoroperatorgroup,tabledata ,max(uploadDate) As lastresponsedate from work where response <> ''
        group by phoneno,creator,creatoroperatorgroup,tabledata
        )d
        on a.PhoneNo = d.PhoneNo
        and a.Creator = d.Creator
        and a.Creatoroperatorgroup = d.Creatoroperatorgroup
        and a.tabledata = d.tabledata
        and a.Uploaddate = d.lastresponsedate
        and a.response in ('interested','User Created') and d.CreatorOperatorGroup = '" . $this->session->userdata("privilege").
        "'
              ) asdf
              left join
               players e 
              on asdf.PhoneNo = e.PhoneNo
        and asdf.Creator = e.Operator
        and asdf.Creatoroperatorgroup = e.OperatorGroup
        and asdf.tabledata = e.tabledata) s where ".$status  ." order by lastresponsedate" ;
            }
            else
            {
               $querystring = "select * from (select asdf.phoneno,asdf.response, asdf.tabledata, asdf.creatoroperatorgroup, asdf.creator, asdf.lastresponsedate, asdf.workketerangan, e.username, e.password,e.nomorrekening, e.namarekening, e.bankrekening, e.website, e.wano, e.referral,e.status,e.keterangan from (
        select d.lastresponsedate,a.phoneno,a.username,a.response,a.keterangan as workketerangan,a.tabledata,a.creatoroperatorgroup,a.creator from work a
        inner join 
        (
        select phoneno, creator,creatoroperatorgroup,tabledata ,max(uploadDate) As lastresponsedate from work where response <> ''
        group by phoneno,creator,creatoroperatorgroup,tabledata
        )d
        on a.PhoneNo = d.PhoneNo
        and a.Creator = d.Creator
        and a.Creatoroperatorgroup = d.Creatoroperatorgroup
        and a.tabledata = d.tabledata
        and a.Uploaddate = d.lastresponsedate
        and a.response in ('interested','User Created') and d.CreatorOperatorGroup = '" . $this->session->userdata("privilege").
        "' and d.CreatorOperatorGroup = '" . $this->session->userdata("privilege").
        "'
              ) asdf
              left join
               players e 
              on asdf.PhoneNo = e.PhoneNo
        and asdf.Creator = e.Operator
        and asdf.Creatoroperatorgroup = e.OperatorGroup
        and asdf.tabledata = e.tabledata) s where ".$status  ." order by lastresponsedate" ;

              
            }
            $data['workarr'] = $this->m_masters->querying($querystring);
            $data['work'] = $data['workarr']->result();
            if($data['workarr']->num_rows() < 1)
            {
              echo '<div class="alert alert-danger alert-dismissible">
                                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                                <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                                No Records Found!
                              </div>';
            }
            else{
                $this->load->view("v_requestplayer_dg",$data);
              }
            // echo $querystring;
          }
          if($reporttype == "cbos")
          {
            if ($this->session->userdata('privileges') == 'Admin')
            {
              if ($ogselector == 'blank')
              {
                $querystring = "select * from (
            select a.phoneno, b.username as username,a.creator, a.creatoroperatorgroup, 
            a.tabledata, a.lastresponsedate, b.response as response, b.keterangan as keterangan from 
            ( 
              select phoneno, creator,creatoroperatorgroup,tabledata, max(uploadDate) As lastresponsedate from work 
              where creatoroperatorgroup = '". $this->session->userdata('privilege') . "' 
              group by phoneno,creator,creatoroperatorgroup,tabledata 
            )a 
            inner join 
            ( 
              select * from work where creatoroperatorgroup = '". $this->session->userdata('privilege') . "'
               and response in( 
                select response from responses where callbackf = 1 ) 
            ) b on a.Phoneno = b.phoneno and a.creatoroperatorgroup = b.creatoroperatorgroup 
            and a.creator = b.creator and a.tabledata = b.tabledata and a.lastresponsedate = b.uploaddate
            ) total order by lastresponsedate";

         //       $querystring = "select terpilih.*, getresponse.response,getresponse.username,getresponse.keterangan from (
      //   select phoneno,tabledata,creator,creatoroperatorgroup, max(uploaddate) as lastresponsedate from (
      //     select phoneno, tabledata, creator, creatoroperatorgroup,response, uploaddate from work where
      //         (
      //       (
      //         response = 'interested' and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinterested'] . " DAY) as char), ' 00:00:00')  
      //       )
      //       or
      //       (
      //         response in ( 'not active','not picked up') and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinactnotpickedup'] . " DAY) as char), ' 00:00:00')  
      //       )
      //     )
      //     and creatoroperatorgroup = '". $this->session->userdata('privilege') . "'
      //   ) filterinterval
      //   where
      //     (
      //     (
      //       response = 'interested' and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinterested'] . " DAY) as char), ' 00:00:00')  
      //     )
      //     or
      //     (
      //       response in ( 'not active','not picked up') and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinactnotpickedup'] . " DAY) as char), ' 00:00:00')  
      //     )
      //     )
      //   and  creatoroperatorgroup = '". $this->session->userdata('privilege') . "'
      //   group by phoneno, tabledata,creator,creatoroperatorgroup
      // ) terpilih
      // left join work getresponse on getresponse.phoneno = terpilih.phoneno and getresponse.tabledata = terpilih.tabledata and 
      // getresponse.creator = terpilih.creator and getresponse.creatoroperatorgroup = terpilih.creatoroperatorgroup  and terpilih.lastresponsedate = getresponse.uploaddate
      // order by terpilih.lastresponsedate desc";
          }
          else
          {
            $querystring = "select * from (
            select a.phoneno, b.username as username,a.creator, a.creatoroperatorgroup, 
            a.tabledata, a.lastresponsedate, b.response as response, b.keterangan as keterangan from 
            ( 
              select phoneno, creator,creatoroperatorgroup,tabledata, max(uploadDate) As lastresponsedate from work 
              where  creatoroperatorgroup = '". $ogselector . "' 
              group by phoneno,creator,creatoroperatorgroup,tabledata 
            )a 
            inner join 
            ( 
              select * from work where  creatoroperatorgroup = '". $ogselector . "'
               and response in( 
                select response from responses where callbackf = 1 ) 
            ) b on a.Phoneno = b.phoneno and a.creatoroperatorgroup = b.creatoroperatorgroup 
            and a.creator = b.creator and a.tabledata = b.tabledata and a.lastresponsedate = b.uploaddate
            ) total order by lastresponsedate";
            // $querystring = "select terpilih.*, getresponse.response,getresponse.username,getresponse.keterangan from (
      //   select phoneno,tabledata,creator,creatoroperatorgroup, max(uploaddate) as lastresponsedate from (
      //     select phoneno, tabledata, creator, creatoroperatorgroup,response, uploaddate from work where
      //         (
      //       (
      //         response = 'interested' and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinterested'] . " DAY) as char), ' 00:00:00')  
      //       )
      //       or
      //       (
      //         response in ( 'not active','not picked up') and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinactnotpickedup'] . " DAY) as char), ' 00:00:00')  
      //       )
      //     )
      //     and creatoroperatorgroup = '". $ogselector . "'
      //   ) filterinterval
      //   where
      //     (
      //     (
      //       response = 'interested' and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinterested'] . " DAY) as char), ' 00:00:00')  
      //     )
      //     or
      //     (
      //       response in ( 'not active','not picked up') and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinactnotpickedup'] . " DAY) as char), ' 00:00:00')  
      //     )
      //     )
      //   and  creatoroperatorgroup = '". $ogselector . "'
      //   group by phoneno, tabledata,creator,creatoroperatorgroup
      // ) terpilih
      // left join work getresponse on getresponse.phoneno = terpilih.phoneno and getresponse.tabledata = terpilih.tabledata and 
      // getresponse.creator = terpilih.creator and getresponse.creatoroperatorgroup = terpilih.creatoroperatorgroup  and terpilih.lastresponsedate = getresponse.uploaddate
      // order by terpilih.lastresponsedate desc";
          }
        }
        else
        {
          $querystring = "select * from (
            select a.phoneno, b.username as username,a.creator, a.creatoroperatorgroup, 
            a.tabledata, a.lastresponsedate, b.response as response, b.keterangan as keterangan from 
            ( 
              select phoneno, creator,creatoroperatorgroup,tabledata, max(uploadDate) As lastresponsedate from work 
              where creatoroperatorgroup = '". $this->session->userdata('privilege') . "' 
              group by phoneno,creator,creatoroperatorgroup,tabledata 
            )a 
            inner join 
            ( 
              select * from work where creatoroperatorgroup = '". $this->session->userdata('privilege') . "'
               and response in( 
                select response from responses where callbackf = 1 ) 
            ) b on a.Phoneno = b.phoneno and a.creatoroperatorgroup = b.creatoroperatorgroup 
            and a.creator = b.creator and a.tabledata = b.tabledata and a.lastresponsedate = b.uploaddate
            ) total order by lastresponsedate";
          // $querystring = "select terpilih.*, getresponse.response,getresponse.username,getresponse.keterangan from (
     //    select phoneno,tabledata,creator,creatoroperatorgroup, max(uploaddate) as lastresponsedate from (
     //      select phoneno, tabledata, creator, creatoroperatorgroup,response, uploaddate from work where
     //          (
     //        (
     //          response = 'interested' and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinterested'] . " DAY) as char), ' 00:00:00')  
     //        )
     //        or
     //        (
     //          response in ( 'not active','not picked up') and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinactnotpickedup'] . " DAY) as char), ' 00:00:00')  
     //        )
     //      )
     //      and creatoroperatorgroup = '". $this->session->userdata('privilege') . "'
     //    ) filterinterval
     //    where
     //      (
     //      (
     //        response = 'interested' and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinterested'] . " DAY) as char), ' 00:00:00')  
     //      )
     //      or
     //      (
     //        response in ( 'not active','not picked up') and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinactnotpickedup'] . " DAY) as char), ' 00:00:00')  
     //      )
     //      )
     //    and  creatoroperatorgroup = '". $this->session->userdata('privilege') . "'
     //    group by phoneno, tabledata,creator,creatoroperatorgroup
     //  ) terpilih
     //  left join work getresponse on getresponse.phoneno = terpilih.phoneno and getresponse.tabledata = terpilih.tabledata and 
     //  getresponse.creator = terpilih.creator and getresponse.creatoroperatorgroup = terpilih.creatoroperatorgroup  and terpilih.lastresponsedate = getresponse.uploaddate
     //  order by terpilih.lastresponsedate desc";
        }

        $data['workarr'] = $this->m_masters->querying($querystring);
          $data['work'] = $data['workarr']->result();
          if($data['workarr']->num_rows() < 1)
          {
            echo '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              No Records Found!
                            </div>';
          }
          else
          {
              $this->load->view("v_cbos_dg",$data);
          }
            // echo $querystring;

          }
          if($reporttype == "sisadata")
          {
            $querystring = "select a.createddate as uploaddate, a.tabledata, c.totaldata, b.donedata, 
          round(b.donedata * 100 / c.totaldata,1) as donepercentage, 
          c.totaldata - b.donedata as avail,
          round((c.totaldata - b.donedata) * 100 / c.totaldata,1) as availpercentage
          from tabledatamapping a
          inner join
          (
            select tabledata, count(response) as donedata from work where response <> '' and runningno <> 'Callback'
              group by tabledata
          ) b on a.tabledata = b.tabledata
          inner join 
          (
            select tabledata, count(response) as totaldata from work where runningno <> 'Callback'
              group by tabledata
          )c on a.tabledata = c.tabledata
          and a.operatorgroup = '' order by a.createddate desc";
            $data['workarr'] = $this->m_masters->querying($querystring);
          $data['work'] = $data['workarr']->result();
          if($data['workarr']->num_rows() < 1)
          {
            echo '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              No Records Found!
                            </div>';
          }
          else{
              $this->load->view("v_sisadata_dg",$data);
            }
          }
      }
      else
      {
        echo $errmsg;
      }
  }

  public function reportsisadata()
  {
    $errmsg = "";
      
      $tabledata = $this->input->post("modaltabledatainv");

      // $table_columns = array("Table Data", "Response","Count");
      $table_columns = array("No", "PhoneNo","Username","Response","Keterangan","Data", "Tele", "Group");
      $column = 0;
      $querystring = "select runningno, phoneno, username, response, keterangan, tabledata,creator, creatoroperatorgroup  from work
      where tabledata = '". $tabledata . "'";

      // $querystring = "select 1 as tabledata,2 as response,3 as count union all select 2,3,4";
    $work = $this->m_masters->querying($querystring)->result();

    require_once APPPATH . "/third_party/PHPExcel.php";
        $object= new PHPExcel();
        $object->setActiveSheetIndex(0);
        $object->getDefaultStyle()->getNumberFormat()->setFormatCode(
        PHPExcel_Style_NumberFormat::FORMAT_TEXT
    );
       foreach($table_columns as $field){

          $object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);

          $column++;
      }
        $excel_row = 2;
        foreach($work as $row){
        // $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$row->tabledata);
       //  $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $row->response);
       //  $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $row->count);

        $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$row->runningno);
        $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $row->phoneno);
        $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $row->username);
        $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $row->response);
        $object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $row->keterangan);
        $object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $row->tabledata);
        $object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row, $row->creator);
        $object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row, $row->creatoroperatorgroup);


        $excel_row++;
        
    }
    $object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel5');
      header('Content-Type: application/vnd.ms-excel');
      $excelname = $tabledata . date("Y_m_d_h_i_sa").".xls";
      header('Content-Disposition: attachment;filename="'.$excelname.'"');
      $object_writer->save('php://output');
  }

  public function reports()
  {
    $errmsg = "";
      
      $datefrom = $this->input->post("datefromselector");
      $dateto = $this->input->post("datetoselector");
      $reporttype = $this->input->post("reporttypeselector");
      $ogselector = $this->input->post("ogselector");
      $tdselector = $this->input->post("tdselector");
      $outstanding = $this->input->post("outstanding");


      if($datefrom == "" && $reporttype <> "sisadata" && $reporttype <> "cbos" && $reporttype <> "requestplayer")
      {
        $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill date from!
                            </div>';
      }
      if($dateto == "" && $reporttype <> "sisadata" && $reporttype <> "cbos" && $reporttype <> "requestplayer")
      {
        $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill date to!
                            </div>';
      }
      if ($reporttype == "blank")
      {
        $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill Report Type!
                            </div>';
      }
      if($ogselector == "" && $tdselector == "" && $reporttype == "sisadata")
      {
        $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill operator group or table data for sisadata report
                            </div>';
      }

      if ($errmsg == "")
      {
        $datefrom = date('Y-m-d', strtotime($datefrom));
        $dateto = date('Y-m-d', strtotime($dateto));


        if($reporttype == "blastberapa")
        { 
          $datefrom = $datefrom . " 00:00:00";
          $dateto = $dateto . " 23:59:59";
          $response = $this->wablastberapa($datefrom,$dateto);
          $data['listblast'] = json_decode($response); 
          // echo json_decode($response)[3]->{'tanggal'};
          // echo $response;
          // echo $listblast[3]->operatorgroup;
          // echo count($listblast);
          // echo $datefrom . $dateto;
          if(count($data['listblast']) == 0)
          {
            echo '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              No Records Found!
                            </div>';
          }
          else
          {
            $table_columns = array("Tanggal", "Group","Jumlah Blast");
              $column = 0;
              $querystring = "select  tabledata,response, count(1) as count from work group by response, tabledata order by tabledata, response";
            $work = $data['listblast'];

            require_once APPPATH . "/third_party/PHPExcel.php";
              $object= new PHPExcel();
              $object->setActiveSheetIndex(0);
              $object->getDefaultStyle()->getNumberFormat()->setFormatCode(
              PHPExcel_Style_NumberFormat::FORMAT_TEXT
            );
             foreach($table_columns as $field){

                $object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);

                $column++;
            }
              $excel_row = 2;
              foreach($work as $row){

              $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$row->tanggal);
              $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $row->operatorgroup);
              $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $row->jumlah_blast);
              $excel_row++;
              }
            }

        }

        if($reporttype == "requestplayer")
        {
            $table_columns = array("Status", "Phone No","Username","Password","Response","Keterangan","Nomor Rekening","Nama Rekening","Bank Rekening","Website","WA No","Referral","Creator","Creator Operator Group","Table Data","Last Response Date");
            $column = 0;

            if($outstanding == 'goal')
            {
              $status = "s.status in ('Created','Reject') ";
            }
            else
            {
              $status = "s.status in ('Open','Reopen') or s.status is null ";
            }
            if ($this->session->userdata('privileges') == 'Admin')
            {
              if ($ogselector == 'blank')
              {
                  $querystring = "select * from (select asdf.phoneno,asdf.response, asdf.tabledata, asdf.creatoroperatorgroup, asdf.creator, asdf.lastresponsedate, asdf.workketerangan, e.username, e.password,e.nomorrekening, e.namarekening, e.bankrekening, e.website, e.wano, e.referral,e.status,e.keterangan from (
        select d.lastresponsedate,a.phoneno,a.username,a.response,a.keterangan as workketerangan,a.tabledata,a.creatoroperatorgroup,a.creator from work a
        inner join 
        (
        select phoneno, creator,creatoroperatorgroup,tabledata ,max(uploadDate) As lastresponsedate from work where response <> ''
        group by phoneno,creator,creatoroperatorgroup,tabledata
        )d
        on a.PhoneNo = d.PhoneNo
        and a.Creator = d.Creator
        and a.Creatoroperatorgroup = d.Creatoroperatorgroup
        and a.tabledata = d.tabledata
        and a.Uploaddate = d.lastresponsedate
        and a.response in ('interested','User Created') and d.CreatorOperatorGroup = '" . $this->session->userdata("privilege").
        "'
              ) asdf
              left join
               players e 
              on asdf.PhoneNo = e.PhoneNo
        and asdf.Creator = e.Operator
        and asdf.Creatoroperatorgroup = e.OperatorGroup
        and asdf.tabledata = e.tabledata) s where ".$status  ;
              }
              else
              {
                $querystring = "select * from (select asdf.phoneno,asdf.response, asdf.tabledata, asdf.creatoroperatorgroup, asdf.creator, asdf.lastresponsedate, asdf.workketerangan, e.username, e.password,e.nomorrekening, e.namarekening, e.bankrekening, e.website, e.wano, e.referral,e.status,e.keterangan from (
        select d.lastresponsedate,a.phoneno,a.username,a.response,a.keterangan as workketerangan,a.tabledata,a.creatoroperatorgroup,a.creator from work a
        inner join 
        (
        select phoneno, creator,creatoroperatorgroup,tabledata ,max(uploadDate) As lastresponsedate from work where response <> ''
        group by phoneno,creator,creatoroperatorgroup,tabledata
        )d
        on a.PhoneNo = d.PhoneNo
        and a.Creator = d.Creator
        and a.Creatoroperatorgroup = d.Creatoroperatorgroup
        and a.tabledata = d.tabledata
        and a.Uploaddate = d.lastresponsedate
        and a.response in ('interested','User Created') and d.CreatorOperatorGroup = '" . $this->session->userdata("privilege").
        "'
              ) asdf
              left join
               players e 
              on asdf.PhoneNo = e.PhoneNo
        and asdf.Creator = e.Operator
        and asdf.Creatoroperatorgroup = e.OperatorGroup
        and asdf.tabledata = e.tabledata) s where ".$status  ;
              }
            }
          $work = $this->m_masters->querying($querystring)->result();

          require_once APPPATH . "/third_party/PHPExcel.php";
            $object= new PHPExcel();
            $object->setActiveSheetIndex(0);
            $object->getDefaultStyle()->getNumberFormat()->setFormatCode(
            PHPExcel_Style_NumberFormat::FORMAT_TEXT
          );
           foreach($table_columns as $field){

              $object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);

              $column++;
          }
            $excel_row = 2;
            foreach($work as $row){

            $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$row->status);
            $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $row->phoneno);            
            $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row,$row->username);
            $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $row->password);
            $object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $row->response);
            $object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $row->workketerangan);
            $object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row,$row->nomorrekening);
            $object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row,$row->namarekening);
            $object->getActiveSheet()->setCellValueByColumnAndRow(8, $excel_row,$row->bankrekening);
            $object->getActiveSheet()->setCellValueByColumnAndRow(9, $excel_row,$row->website);
            $object->getActiveSheet()->setCellValueByColumnAndRow(10, $excel_row,$row->wano);
            $object->getActiveSheet()->setCellValueByColumnAndRow(11, $excel_row,$row->referral);
            $object->getActiveSheet()->setCellValueByColumnAndRow(12, $excel_row,$row->creator);
            $object->getActiveSheet()->setCellValueByColumnAndRow(13, $excel_row,$row->creatoroperatorgroup);
            $object->getActiveSheet()->setCellValueByColumnAndRow(14, $excel_row,$row->tabledata);
            $object->getActiveSheet()->setCellValueByColumnAndRow(15, $excel_row,$row->lastresponsedate);
            $excel_row++;
            }
          }


        if($reporttype == "cbos")
          {
            $table_columns = array("PhoneNo", "Username","Last Call","Prev Response", "Prev Note", "Data","Tele","Group");
            $column = 0;

            if ($this->session->userdata('privileges') == 'Supervisor')
            {
              $querystring = "select * from (
            select a.phoneno, b.username as username,a.creator, a.creatoroperatorgroup, 
            a.tabledata, a.lastresponsedate, b.response as response, b.keterangan as keterangan from 
            ( 
              select phoneno, creator,creatoroperatorgroup,tabledata, max(uploadDate) As lastresponsedate from work 
              where uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['interval'] . " DAY) as char), ' 00:00:00')  
              and creatoroperatorgroup = '". $this->session->userdata('privilege') . "' 
              group by phoneno,creator,creatoroperatorgroup,tabledata 
            )a 
            inner join 
            ( 
              select * from work where uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['interval'] . " DAY) as char), ' 00:00:00') and creatoroperatorgroup = '". $this->session->userdata('privilege') . "'
               and response in( 
                select response from responses where callbackf = 1 ) 
            ) b on a.Phoneno = b.phoneno and a.creatoroperatorgroup = b.creatoroperatorgroup 
            and a.creator = b.creator and a.tabledata = b.tabledata and a.lastresponsedate = b.uploaddate
          ) total";
          }

        else
        {
          if ($ogselector == 'blank')
              {
                $querystring = "select * from (
            select a.phoneno, b.username as username,a.creator, a.creatoroperatorgroup, 
            a.tabledata, a.lastresponsedate, b.response as response, b.keterangan as keterangan from 
            ( 
              select phoneno, creator,creatoroperatorgroup,tabledata, max(uploadDate) As lastresponsedate from work 
              where creator = '". $this->session->userdata('username') . "' and creatoroperatorgroup = '". $this->session->userdata('privilege') . "' 
              group by phoneno,creator,creatoroperatorgroup,tabledata 
            )a 
            inner join 
            ( 
              select * from work where creator = '". $this->session->userdata('username') . "' and creatoroperatorgroup = '". $this->session->userdata('privilege') . "'
               and response in( 
                select response from responses where callbackf = 1 ) 
            ) b on a.Phoneno = b.phoneno and a.creatoroperatorgroup = b.creatoroperatorgroup 
            and a.creator = b.creator and a.tabledata = b.tabledata and a.lastresponsedate = b.uploaddate
            ) total";
            // $querystring = "select terpilih.*, getresponse.response,getresponse.username,getresponse.keterangan from (
      //   select phoneno,tabledata,creator,creatoroperatorgroup, max(uploaddate) as lastresponsedate from (
      //     select phoneno, tabledata, creator, creatoroperatorgroup,response, uploaddate from work where
      //         (
      //       (
      //         response = 'interested' and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinterested'] . " DAY) as char), ' 00:00:00')  
      //       )
      //       or
      //       (
      //         response in ( 'not active','not picked up') and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinactnotpickedup'] . " DAY) as char), ' 00:00:00')  
      //       )
      //     )
      //     and creatoroperatorgroup = '". $this->session->userdata('privilege') . "'
      //   ) filterinterval
      //   where
      //     (
      //     (
      //       response = 'interested' and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinterested'] . " DAY) as char), ' 00:00:00')  
      //     )
      //     or
      //     (
      //       response in ( 'not active','not picked up') and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinactnotpickedup'] . " DAY) as char), ' 00:00:00')  
      //     )
      //     )
      //   and  creatoroperatorgroup = '". $this->session->userdata('privilege') . "'
      //   group by phoneno, tabledata,creator,creatoroperatorgroup
      // ) terpilih
      // left join work getresponse on getresponse.phoneno = terpilih.phoneno and getresponse.tabledata = terpilih.tabledata and 
      // getresponse.creator = terpilih.creator and getresponse.creatoroperatorgroup = terpilih.creatoroperatorgroup  and terpilih.lastresponsedate = getresponse.uploaddate
      // order by terpilih.lastresponsedate desc";
          }
          else
          {
            $querystring = "select * from (
            select a.phoneno, b.username as username,a.creator, a.creatoroperatorgroup, 
            a.tabledata, a.lastresponsedate, b.response as response, b.keterangan as keterangan from 
            ( 
              select phoneno, creator,creatoroperatorgroup,tabledata, max(uploadDate) As lastresponsedate from work 
              where creator = '". $this->session->userdata('username') . "' and creatoroperatorgroup = '". $ogselector . "' 
              group by phoneno,creator,creatoroperatorgroup,tabledata 
            )a 
            inner join 
            ( 
              select * from work where creator = '". $this->session->userdata('username') . "' and creatoroperatorgroup = '". $ogselector . "'
               and response in( 
                select response from responses where callbackf = 1 ) 
            ) b on a.Phoneno = b.phoneno and a.creatoroperatorgroup = b.creatoroperatorgroup 
            and a.creator = b.creator and a.tabledata = b.tabledata and a.lastresponsedate = b.uploaddate
            ) total";
            // $querystring = "select terpilih.*, getresponse.response,getresponse.username,getresponse.keterangan from (
      //   select phoneno,tabledata,creator,creatoroperatorgroup, max(uploaddate) as lastresponsedate from (
      //     select phoneno, tabledata, creator, creatoroperatorgroup,response, uploaddate from work where
      //         (
      //       (
      //         response = 'interested' and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinterested'] . " DAY) as char), ' 00:00:00')  
      //       )
      //       or
      //       (
      //         response in ( 'not active','not picked up') and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinactnotpickedup'] . " DAY) as char), ' 00:00:00')  
      //       )
      //     )
      //     and creatoroperatorgroup = '". $ogselector . "'
      //   ) filterinterval
      //   where
      //     (
      //     (
      //       response = 'interested' and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinterested'] . " DAY) as char), ' 00:00:00')  
      //     )
      //     or
      //     (
      //       response in ( 'not active','not picked up') and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinactnotpickedup'] . " DAY) as char), ' 00:00:00')  
      //     )
      //     )
      //   and  creatoroperatorgroup = '". $ogselector . "'
      //   group by phoneno, tabledata,creator,creatoroperatorgroup
      // ) terpilih
      // left join work getresponse on getresponse.phoneno = terpilih.phoneno and getresponse.tabledata = terpilih.tabledata and 
      // getresponse.creator = terpilih.creator and getresponse.creatoroperatorgroup = terpilih.creatoroperatorgroup  and terpilih.lastresponsedate = getresponse.uploaddate
      // order by terpilih.lastresponsedate desc";
          }
        }
          $work = $this->m_masters->querying($querystring)->result();

          require_once APPPATH . "/third_party/PHPExcel.php";
            $object= new PHPExcel();
            $object->setActiveSheetIndex(0);
            $object->getDefaultStyle()->getNumberFormat()->setFormatCode(
            PHPExcel_Style_NumberFormat::FORMAT_TEXT
          );
           foreach($table_columns as $field){

              $object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);

              $column++;
          }
            $excel_row = 2;
            foreach($work as $row){

            $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$row->phoneno);
            $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $row->username);
            $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $row->lastresponsedate);
            $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row,$row->response);
            $object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $row->keterangan);
            $object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $row->tabledata);
            $object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row,$row->creator);
            $object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row,$row->creatoroperatorgroup);
            $excel_row++;
            }
          }

        if($reporttype == "sisadata")
          {
            if($ogselector <> "blank")
            {
              $table_columns = array("Data", "Priority","Total","NotCalledyet","Interested","User Created","Not Active","Not Pickedup","Not Interested","Invalid Number");
              // $work = $this->m_masters->reportsisadata_ogr($ogselector)->result();
              $querystring = "
                            select uni.tabledata, prio.ID, uni.response,coalesce(uni.hitung,0) as count from 
              (
                select cros.tabledata, cros.response, satu.hitung from 
                (
                  select acc.tabledata, acc.response, acc.hitung from 
                  (
                    select  tabledata, response ,count(1) as hitung from (
                      select a.*, b.response from (
                      select phoneno, tabledata,  max(uploaddate) as maxdate
                      from work where tabledata in (select tabledata from tabledatamapping where operatorgroup = '".$ogselector ."')
                      group by phoneno, tabledata
                      ) a
                      inner join
                      work b
                      on a.phoneno = b.phoneno  and a.tabledata = b.tabledata and
                      a.maxdate = b.uploaddate 
                      where b.tabledata in (select tabledata from tabledatamapping where operatorgroup = '".$ogselector ."')
                    ) total group by tabledata,response
                  ) acc 
                )satu 
                right join 
                ( 
                  select tdm.tabledata, rsp.response from 
                  (
                    select tabledata from tabledatamapping where operatorgroup = '".$ogselector ."'  
                  ) tdm
                  cross join
                  (
                    select response from responses
                  ) rsp
                )cros
                on satu.response = cros.response and satu.tabledata = cros.tabledata
              ) uni
              inner join tabledatamapping prio on
              uni.tabledata = prio.tabledata where prio.operatorgroup = '".$ogselector ."' 
              order by CAST(prio.ID As Unsigned), uni.response
              ";
              $work = $this->m_masters->querying($querystring)->result();
            }
            else
            {
              $table_columns = array("Data", "Total","NotCalledyet","Interested","User Created","Not Active","Not Pickedup","Not Interested","Invalid Number");
              $querystring = "
              select uni.tabledata,  uni.response,coalesce(uni.hitung,0) as count from 
              (
                select cros.tabledata, cros.response, satu.hitung from 
                (
                  select acc.tabledata, acc.response, acc.hitung from 
                  (
                    select  tabledata, response ,count(1) as hitung from (
                      select a.*, b.response from (
                      select phoneno, tabledata,  max(uploaddate) as maxdate
                      from work where tabledata = '".$tdselector."'
                      group by phoneno, tabledata
                      ) a
                      inner join
                      work b
                      on a.phoneno = b.phoneno  and a.tabledata = b.tabledata and
                      a.maxdate = b.uploaddate 
                      where b.tabledata = '".$tdselector."'
                    ) total group by tabledata,response
                  ) acc 
                )satu 
                right join 
                ( 
                  select tdm.tabledata, rsp.response from 
                  (
                    select distinct tabledata from tabledatamapping where tabledata = '".$tdselector."'
                  ) tdm
                  cross join
                  (
                    select response from responses
                  ) rsp
                )cros
                on satu.response = cros.response and satu.tabledata = cros.tabledata
              ) uni
              order by  uni.response

              ";
              // $work = $this->m_masters->reportsisadata_tdm($tdselector)->result();
              $work = $this->m_masters->querying($querystring)->result();
            }

     
            $column = 0;

            

          require_once APPPATH . "/third_party/PHPExcel.php";
            $object= new PHPExcel();
            $object->setActiveSheetIndex(0);
            $object->getDefaultStyle()->getNumberFormat()->setFormatCode(
            PHPExcel_Style_NumberFormat::FORMAT_TEXT
          );
           foreach($table_columns as $field){

              $object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);

              $column++;
          }
            $excel_row = 2;

            if($ogselector <> "blank")
            {

              $totaltabledata = count($work)/7;
              for($loop = 0;$loop<$totaltabledata;$loop++)
              {
                $totaldata = $work[$loop * 7]->count + $work[$loop * 7 + 1]->count + $work[$loop * 7 + 6]->count + $work[$loop * 7 + 3]->count + $work[$loop * 7 + 5]->count + $work[$loop * 7 + 4]->count + $work[$loop * 7 + 2]->count;
                $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$work[$loop*7]->tabledata);
                $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row,$work[$loop * 7]->ID);
                $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row,$totaldata);
                $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row,$work[$loop * 7]->count);
                $object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row,$work[$loop * 7 + 1]->count);
                $object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row,$work[$loop * 7 + 6]->count);
                $object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row,$work[$loop * 7 + 3]->count);
                $object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row,$work[$loop * 7 + 5]->count);
                $object->getActiveSheet()->setCellValueByColumnAndRow(8, $excel_row,$work[$loop * 7 + 4]->count);
                $object->getActiveSheet()->setCellValueByColumnAndRow(9, $excel_row,$work[$loop * 7 + 2]->count);
                $excel_row++;
              }
            }
            else
            {
              $totaltabledata = count($work)/7;
              for($loop = 0;$loop<$totaltabledata;$loop++)
              {
                $totaldata = $work[$loop * 7]->count + $work[$loop * 7 + 1]->count + $work[$loop * 7 + 6]->count + $work[$loop * 7 + 3]->count + $work[$loop * 7 + 5]->count + $work[$loop * 7 + 4]->count + $work[$loop * 7 + 2]->count ;
                $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$work[0]->tabledata);
                $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row,$totaldata);
                $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row,$work[$loop * 7]->count);
                $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row,$work[$loop * 7 + 1]->count);
                $object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row,$work[$loop * 7 + 6]->count);
                $object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row,$work[$loop * 7 + 3]->count);
                $object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row,$work[$loop * 7 + 5]->count);
                $object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row,$work[$loop * 7 + 4]->count);
                $object->getActiveSheet()->setCellValueByColumnAndRow(8, $excel_row,$work[$loop * 7 + 2]->count);
                $excel_row++;
              }
            }
          }

        if($reporttype == "rawreport")
          {
            $table_columns = array("PhoneNo", "Username","Response","Data", "Group","Tele", "Date");
            $column = 0;
            // $querystring = "select phoneno,username,response,tabledata,creatoroperatorgroup,creator,uploaddate from work where uploaddate > '" .$datefrom . " 00:00:00' and uploaddate < '" .$dateto ." 23:59:59'";
          $work = $this->m_masters->reportrawreport($datefrom,$dateto)->result();

          require_once APPPATH . "/third_party/PHPExcel.php";
            $object= new PHPExcel();
            $object->setActiveSheetIndex(0);
            $object->getDefaultStyle()->getNumberFormat()->setFormatCode(
            PHPExcel_Style_NumberFormat::FORMAT_TEXT
          );
           foreach($table_columns as $field){

              $object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);

              $column++;
          }
            $excel_row = 2;
            foreach($work as $row){

            $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$row->phoneno);
            $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $row->username);
            $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $row->response);
            $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $row->tabledata);
            $object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $row->creatoroperatorgroup);
            $object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $row->creator);
            $object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row, $row->uploaddate);
            $excel_row++;
            }
          }

          if($reporttype == "requestedplayers" || $reporttype == "requestedplayersall")
          {
            $table_columns = array("PhoneNo", "Username", "NoRek", "NamaRek", "Bank", "Website", "WANo", "Referral", "Data", "Tele", "Group", "Date");
            $column = 0;
            // $querystring = "select phoneno,username,response,tabledata,creatoroperatorgroup,creator,uploaddate from work where uploaddate > '" .$datefrom . " 00:00:00' and uploaddate < '" .$dateto ." 23:59:59'";
            if($reporttype == "requestedplayers")
            {
            $work = $this->m_masters->reportrequestedplayers($datefrom,$dateto,$this->session->userdata('privilege'))->result();
          }
          else
          {
            $work = $this->m_masters->reportrequestedplayersall($datefrom,$dateto)->result();
          }

          require_once APPPATH . "/third_party/PHPExcel.php";
            $object= new PHPExcel();
            $object->setActiveSheetIndex(0);
            $object->getDefaultStyle()->getNumberFormat()->setFormatCode(
            PHPExcel_Style_NumberFormat::FORMAT_TEXT
          );
           foreach($table_columns as $field){

              $object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);

              $column++;
          }
            $excel_row = 2;
            foreach($work as $row){

            $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$row->PhoneNo);
            $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $row->UserName);
            $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $row->NomorRekening);
            $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $row->NamaRekening);
            $object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $row->BankRekening);
            $object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $row->Website);
            $object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row, $row->WANo);
            $object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row, $row->Referral);
            $object->getActiveSheet()->setCellValueByColumnAndRow(8, $excel_row, $row->TableData);
            $object->getActiveSheet()->setCellValueByColumnAndRow(9, $excel_row, $row->Operator);
            $object->getActiveSheet()->setCellValueByColumnAndRow(10, $excel_row, $row->OperatorGroup);
            $object->getActiveSheet()->setCellValueByColumnAndRow(11, $excel_row, $row->CreatedDate);
            $excel_row++;
            }
          }



          if($reporttype == "calloperator")
          {
            $table_columns = array("Tele", "Group","TeleCall","GroupCall","User Created", "Interested", "Not Active", "Not Pickedup","Not Interested","Invalid Number");
            
            $column = 0;

            

            if ($ogselector == 'blank')
            {
              $work = $this->m_masters->reportcalloperator($datefrom,$dateto)->result();
          }
          else
          {
            $work = $this->m_masters->reportcalloperator_og($datefrom,$dateto,$ogselector)->result();
          }

          require_once APPPATH . "/third_party/PHPExcel.php";
            $object = new PHPExcel();
            $object->setActiveSheetIndex(0);
            $object->getDefaultStyle()->getNumberFormat()->setFormatCode(
            PHPExcel_Style_NumberFormat::FORMAT_TEXT
          );
           foreach($table_columns as $field){

              $object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);

              $column++;
          }
            $excel_row = 2;
            foreach($work as $row){

            $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$row->Creator);
            $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row,$row->CreatorOperatorGroup);
            $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $row->total_call_operator);
            // $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $row->total_call_operator_distinct);
            $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $row->total_group_call);
            // $object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $row->total_group_call_distinct);
            $object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $row->UserCreated);
            $object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $row->interested);
            $object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row,$row->not_active);
            $object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row, $row->not_picked_up);
            $object->getActiveSheet()->setCellValueByColumnAndRow(8, $excel_row, $row->not_interested);
            $object->getActiveSheet()->setCellValueByColumnAndRow(9, $excel_row, $row->invalid_number);
            $excel_row++;
            }
          }
          
            

        $object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel5');
        header('Content-Type: application/vnd.ms-excel');
        $excelname = $reporttype . date("Y_m_d_h_i_sa").".xls";
        header('Content-Disposition: attachment;filename="'.$excelname.'"');
        $object_writer->save('php://output');
      }
      else
      {
        $this->session->set_flashdata('reportcrd', $errmsg);
          // $this->load->view("v_reports");
          redirect("c_modules");
      }
  }


  public function export()
  {
        $errmsg = "";
      
      $datefrom = $this->input->post("datefrom");
      $dateto = $this->input->post("dateto");
      $reporttype = $this->input->post("reporttype");
      if($datefrom == "")
      {
        $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill date from!
                            </div>';
      }
      if($dateto == "")
      {
        $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill date to!
                            </div>';
      }
      if ($reporttype == "blank")
      {
        $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill Report Type!
                            </div>';
      }

            $table_columns = array("PhoneNo");
            $column = 0;
          $work = $this->m_masters->querying("select phoneno from work")->result();

          require_once APPPATH . "/third_party/PHPExcel.php";
            $object= new PHPExcel();
            $object->setActiveSheetIndex(0);
            $object->getDefaultStyle()->getNumberFormat()->setFormatCode(
            PHPExcel_Style_NumberFormat::FORMAT_TEXT
          );
           foreach($table_columns as $field){

              $object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);
              $column++;
          }
            $excel_row = 2;
            foreach($work as $row){

            $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$row->phoneno);
            $excel_row++;
            }
            $object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel5');
            header('Content-Type: application/vnd.ms-excel');
            $excelname = "gablo.xls";
            header('Content-Disposition: attachment;filename="'.$excelname.'"');
            $object_writer->save('php://output');
  }
  public function renametabledata()
  {
    $errmsg = "";
    $DBName = "work";
    $newtabledata = $this->input->post("newtabledata");
    $tabledata = $this->input->post("tabledata");

    if($tabledata == 'blank')
    {
      $errmsg = $errmsg . "<br>" . '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please Choose table data!
                            </div>';
    }
    if($newtabledata == '')
    {
      $errmsg = $errmsg . "<br>" . '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              New Table Data Name cannot be empty!
                            </div>';
    }

    $querycheck = "select tabledata from tabledatamapping where tabledata = '" . $newtabledata ."'";
    $exist = $this->m_masters->querying($querycheck)->num_rows();

    // echo $querycheck ; 
    if($exist >= 1)
    {
      $errmsg = $errmsg. "<br>" . '<div class="alert alert-warning alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                              Table Data Name has already been reserved. Please choose another Table Data Name
                            </div>';
    }

    if($errmsg == '')
    {
      if (substr($tabledata,0,3) == 'wa_')
      {
        if (substr($newtabledata,0,3) == 'wa_')
        {
          $resptabledata = $this->warenametabledata($newtabledata,$tabledata);
          $respwork = $this->warenamework($newtabledata,$tabledata);

          // echo json_decode($resptabledata)->{'Info'};
          // echo "<br>".json_decode($respwork)->{'Info'};
          if(strpos(json_decode($resptabledata)->{'Info'} ,"Berhasil di update") > 1 && strpos(json_decode($respwork)->{'Info'} ,"Berhasil di update") > 1 )
          {
            $querystring = "update tabledatamapping set tabledata = '".$newtabledata ."' where tabledata = '".$tabledata . "'";
            $this->m_masters->querying($querystring);

            echo "Rename table data from  ".$tabledata . " to ". $newtabledata ." successful di babiair dan TMP!";
          }
          else if(strpos(json_decode($resptabledata)->{'Info'} ,"Berhasil di update") > 1 && strpos(json_decode($respwork)->{'Info'} ,"Berhasil di update") <= 1 )
          {
            echo "Rename table data from  ".$tabledata . " to ". $newtabledata ." successful di babiair dan TMP , tapi belum terupdate di work! Follow these step : 
            <br>1. Rename table data yang baru ke nama yang lama";
          }
          else if(strpos(json_decode($respwork)->{'Info'} ,"Berhasil di update") > 1 && strpos(json_decode($resptabledata)->{'Info'} ,"Berhasil di update") <= 1 )
          {
            echo "Rename table data from  ".$tabledata . " to ". $newtabledata ." successful di babiair dan TMP , tapi belum terupdate di tabledatamapping! Follow these step : 
            <br>1. Rename table data yang baru ke nama yang lama";
          }
          
          
        }
        else
        {
          echo '<div class="alert alert-danger alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                    Table Data tipe WA harus mengikuti format tipe WA
                </div>';
        }
      }
      else
      {
        $querystring = "update tabledatamapping set tabledata = '".$newtabledata ."' where tabledata = '".$tabledata . "'";
        $this->m_masters->querying($querystring);

        $querystring = "update work set tabledata = '".$newtabledata ."' where tabledata = '".$tabledata . "'";
        $this->m_masters->querying($querystring);
        echo "Rename table data from  ".$tabledata . " to ". $newtabledata ." successful!";
      }

    }
    else
    {
      echo $errmsg;
    }
  }

  public function inquiretabledata()
  {
    $errmsg = "";
    $DBName = "work";
    $operatorgroup = $this->input->post("operatorgroup");
    $priority = $this->input->post("priority");
    $prioritydoneonly = $this->input->post("prioritydoneonly");
    $priorityinactive = $this->input->post("priorityinactive");
    $tabledata = $this->input->post("tabledata");
    $firstupload = $this->input->post("firstupload");

    if($tabledata == 'blank')
    {
      $tabledata = '';
      $querytabledata = " tabledata like '%%'";
    }
    else
    {
      $querytabledata = " tabledata = '".$tabledata . "'";
    }

    if($operatorgroup == 'blank')
    {
      $operatorgroup = '';
      $queryoperatorgroup = " operatorgroup  like '%%'";
    }
    else
    {
      $queryoperatorgroup = " operatorgroup  = '".$operatorgroup . "'";
    }

    if($firstupload == "firstupload")
    {
      $querycheck = "select * from tabledatamapping where operatorgroup = '' and ".$querytabledata ;
    }


    else if($priorityinactive == "")
    {
      // echo "asdf". $priorityinactive . "asdf2".$prioritydoneonly;
      $querycheck = "select * from tabledatamapping where ".$queryoperatorgroup." and ".$querytabledata." and operatorgroup <> '' and(";
      if($priority <> "")
      {
        $querycheck = $querycheck . "ID = '".$priority . "')";
      }
      else
      {
        $querycheck = $querycheck . "ID like '%".$priority . "%')";
      }
      
    }
    else
    {
      $querycheck = "select * from tabledatamapping where ".$queryoperatorgroup ." and ".$querytabledata ." and (";
      // if($priorityinactive <> "" && $prioritydoneonly <> "")
      // {
      //  $querycheck = $querycheck . "ID = '".$priorityinactive . "' or ";
      //  $querycheck = $querycheck . "ID = '".$prioritydoneonly . "')";
      // }

        $querycheck = $querycheck . "ID = '".$priorityinactive . "')";

      // else 
      // {
      //  $querycheck = $querycheck . "ID = '".$prioritydoneonly . "')";

      // }

    }
    // echo $querycheck;
    $querycheck = "select a.*, coalesce(b.total_data,0) as total_data, coalesce(c.sisa_data,0) as sisa_data from 
    (" . $querycheck . 
    ")a
    left join 
    (
      select tabledata, count(1) as total_data from work where ".$querytabledata ." and response <> 'callback' group by tabledata
    )b on a.tabledata = b.tabledata
    left join 
    (
      select tabledata, count(1) as sisa_data from work where ".$querytabledata ." and response = '' group by tabledata
    )c on a.tabledata = c.tabledata ";
    if($prioritydoneonly <> "")
    {
      $querycheck = $querycheck . " where coalesce(c.sisa_data,0) = 0";
    }
    $querycheck = $querycheck . " order by operatorgroup, id";

    // $querycheck = $querycheck . " order by operatorgroup, id";
    // echo $querycheck;

    $data['listtabledatamapping'] = $this->m_masters->querying($querycheck);
    $data['listscounts'] = $data['listtabledatamapping']->num_rows();
    $data['listtabledatamappingarr'] = $data['listtabledatamapping']->result();
    



    if($data['listscounts'] == 0) 
    {
      echo '<div class="alert alert-danger alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                    There is no such table data mapping!
                </div>';
    }
    else
    {
      // echo $querycheck;
        $this->load->view('v_TDM_dg',$data);
    }
  }

  public function deletetabledata()
  {
    $errmsg = "";
    $DBName = "operatorgroups";
    $operatorgroup = $this->input->post("operatorgroup");
    $priority = $this->input->post("priority");
    $tabledata = $this->input->post("tabledata");

    if($tabledata == "blank")
    {
      $errmsg = $errmsg. "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please select Table Data!
                            </div>';
    }


    if ($errmsg == "")
    {
      if ($operatorgroup == "blank")
      {
        $querytabledata = "select * from tabledatamapping where   tabledata = '" . $tabledata ."'";
        $checkexist = $this->m_masters->querying($querytabledata)->num_rows();
        if ($checkexist == 0)
        {
          echo '<div class="alert alert-warning alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                      No Table Data Found!
                    </div>';
        }
        else
        {
          $querydelete = "delete from tabledatamapping where tabledata = '" . $tabledata ."'";
          $this->m_masters->querying($querydelete);
          $querydelete2 = "delete from work where tabledata = '" . $tabledata ."'";
          $this->m_masters->querying($querydelete2);
          echo "Data Successfully deleted for tabledata :".$tabledata ;
        } 
      }
      else
      {
        $querycheck = "select * from tabledatamapping where operatorgroup ='".$operatorgroup ."' and tabledata = '" . $tabledata ."'";
        $checkexist = $this->m_masters->querying($querycheck)->num_rows();
        if ($checkexist == 0 )
        {
          // $queryinsert = "insert into tabledatamapping values ('" .$tabledata. "','".$operatorgroup ."','". $priority ."','Admin',now())";
          // $this->m_masters->querying($queryinsert); 
          // echo "Data Successfully inserted for tabledata :".$tabledata . " and operatorgroup : " .$operatorgroup; 
          echo '<div class="alert alert-warning alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                      No Table Data and Operator Group Mapping Found!
                    </div>';
        }
        else
        {
          $querydelete = "delete from tabledatamapping where operatorgroup ='".$operatorgroup ."' and tabledata = '" . $tabledata ."'";
         $this->m_masters->querying($querydelete);
         echo "Data Successfully deleted for tabledata :".$tabledata . " and operatorgroup : " .$operatorgroup;
        }
      }

      // echo $querycheck;
    }
    else
    {
      echo $errmsg ;
    }
  }




  public function submittabledata()
  {
    $errmsg = "";
    $DBName = "operatorgroups";
    $operatorgroup = $this->input->post("operatorgroup");
    $priority = $this->input->post("priority");
    $tabledata = $this->input->post("tabledata");

    if($operatorgroup == "blank")
    {
      $errmsg = $errmsg. "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please select Operator Group!
                            </div>';
    }
    if($tabledata == "blank")
    {
      $errmsg = $errmsg. "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please select Table Data!
                            </div>';
    }
    if($priority == "" || $priority == "0")
    {
      $errmsg = $errmsg. "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill ID / Priority From correctly
                            </div>';
    }

    if ($errmsg == "")
    {
      $querycheck = "select * from tabledatamapping where operatorgroup = '".$operatorgroup ."' and tabledata = '" . $tabledata ."'";
      $checkexist = $this->m_masters->querying($querycheck)->num_rows();
      if ($checkexist == 0 )
      {
        $querycheckid = "select * from tabledatamapping where operatorgroup = '".$operatorgroup ."' and ID = '" .$priority . "'";
        $checkexistid = $this->m_masters->querying($querycheckid)->num_rows();
        if($checkexistid == 0 || $priority == "inactive")
        {
          if (substr($tabledata,0,3) == 'wa_')
          {
            

            // $querystring = "select createddate from tabledatamapping where operatorgroup = '".$operatorgroup . "' and tabledata = '".$tabledata."'";
            // $createddate = $this->m_masters->querying($querystring)->result()[0]->createddate;
            $response = $this->wasubmittabledata($tabledata,$operatorgroup,$priority);
            // echo $response;
            if(strpos(json_decode($response)->{'Info'} ,"Berhasil disimpan") > 1)
            {
              $queryinsert = "insert into tabledatamapping values ('" .$tabledata. "','".$operatorgroup ."','". $priority ."','Admin',now())";
              $this->m_masters->querying($queryinsert); 
              $pesan = "Berhasil Insert tabledatamapping di babi air dan TMP untuk tabledata ".$tabledata ." dan operatorgroup : ".$operatorgroup;
              $pesan = '<div class="alert alert-success alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-check"></i> Alert!</h5>'.$pesan.' </div>';
            }
            else
            {
              $pesan = "Koneksi ke babi air gagal! Mohon dicoba kembali";
              $pesan = '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>'.$pesan.' </div>';
            }
          }
          else
          {
            $queryinsert = "insert into tabledatamapping values ('" .$tabledata. "','".$operatorgroup ."','". $priority ."','Admin',now())";
            $this->m_masters->querying($queryinsert); 
            $pesan = "Berhasil Insert tabledatamapping di TMP untuk tabledata ".$tabledata ." dan operatorgroup : ".$operatorgroup;
              $pesan = '<div class="alert alert-success alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-check"></i> Alert!</h5>'.$pesan.' </div>';
          }
          echo $pesan; 
        }
        else
        {
          echo '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>          
                            Priority / ID : '.$priority .' for operatorgroup : ' .$operatorgroup. ' already exist!</div>';
        }
      }
      else
      {
        $querycheckid = "select * from tabledatamapping where operatorgroup = '".$operatorgroup ."' and ID = '" .$priority . "'";
        $checkexistid = $this->m_masters->querying($querycheckid)->num_rows();
        if($checkexistid == 0 || $priority == "inactive")
        {
          if (substr($tabledata,0,3) == 'wa_')
          {
            
            
            $response=$this->waupdatetabledata($tabledata,$operatorgroup,$priority);
            if(strpos(json_decode($response)->{'Info'} ,"Berhasil di update") > 1)
            {
              $queryupdate = "update tabledatamapping set ID = '".$priority . "' where operatorgroup like '%".$operatorgroup ."%' and tabledata like '%" . $tabledata ."%'";
              $this->m_masters->querying($queryupdate);
              $pesan = "Berhasil Update tabledatamapping di babi air dan TMP untuk tabledata ".$tabledata ." dan operatorgroup : ".$operatorgroup;
              $pesan = '<div class="alert alert-success alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-check"></i> Alert!</h5>'.$pesan.' </div>';
            }
            else
            {
              $pesan = "Koneksi ke babi air gagal! Mohon dicoba kembali";
              $pesan = '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>'.$pesan.' </div>';
            }
          }
          else
          {
            $queryupdate = "update tabledatamapping set ID = '".$priority . "' where operatorgroup like '%".$operatorgroup ."%' and tabledata like '%" . $tabledata ."%'";
            $this->m_masters->querying($queryupdate);
            $pesan = "Berhasil Insert tabledatamapping di TMP untuk tabledata ".$tabledata ." dan operatorgroup : ".$operatorgroup;
            $pesan = '<div class="alert alert-success alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-check"></i> Alert!</h5>'.$pesan.' </div>';
          }
          echo $pesan;
        }
        else
        {
          echo '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>          
                            Priority / ID : '.$priority .' for operatorgroup : ' .$operatorgroup. ' already exist!</div>';

        }
      }
    }
    else
    {
      echo $errmsg ;
    }
    // echo $priority.$tabledata.$operatorgroup;
  }

  public function exporttocallback()
  {
    // echo 'asdf';
    $errmsg = "";
    $DBName = "work";
    $phoneno = $this->input->post("phonenoselector");

    // $querycheck =  "select * from (
    //        select a.phoneno, b.username as username,a.creator, a.creatoroperatorgroup, 
    //        a.tabledata, a.lastresponsedate, b.response as response, b.keterangan as keterangan from 
    //        ( 
    //          select phoneno, creator,creatoroperatorgroup,tabledata, max(uploadDate) As lastresponsedate from work 
    //          where uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['interval'] . " DAY) as char), ' 00:00:00')  
    //          and creator = '". $this->session->userdata('username') . "' and creatoroperatorgroup = '". $this->session->userdata('privilege') . "' 
    //          group by phoneno,creator,creatoroperatorgroup,tabledata 
    //        )a 
    //        inner join 
    //        ( 
    //          select * from work where uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['interval'] . " DAY) as char), ' 00:00:00') and creator = '". $this->session->userdata('username') . "' and creatoroperatorgroup = '". $this->session->userdata('privilege') . "'
    //           and response in( 
    //            select response from responses where callbackf = 1 ) 
    //        ) b on a.Phoneno = b.phoneno and a.creatoroperatorgroup = b.creatoroperatorgroup 
    //        and a.creator = b.creator and a.tabledata = b.tabledata and a.lastresponsedate = b.uploaddate
    //        ) total";


    $querycheck =   "select * from (
            select a.phoneno, b.username as username,a.creator, a.creatoroperatorgroup, 
            a.tabledata, a.lastresponsedate, b.response as response, b.keterangan as keterangan from 
            ( 
              select phoneno, creator,creatoroperatorgroup,tabledata, max(uploadDate) As lastresponsedate from work 
              where creator = '". $this->session->userdata('username') . "' and creatoroperatorgroup = '". $this->session->userdata('privilege') . "' and phoneno like '%".$phoneno."%'
              group by phoneno,creator,creatoroperatorgroup,tabledata 
            )a 
            inner join 
            ( 
              select * from work where creator = '". $this->session->userdata('username') . "' and creatoroperatorgroup = '". $this->session->userdata('privilege') . "'
               and response in( 
                select response from responses where callbackf = 1 ) 
            ) b on a.Phoneno = b.phoneno and a.creatoroperatorgroup = b.creatoroperatorgroup 
            and a.creator = b.creator and a.tabledata = b.tabledata and a.lastresponsedate = b.uploaddate
            ) total order by lastresponsedate limit 5";

    // $querycheck = "select terpilih.*, getresponse.response,getresponse.username,getresponse.keterangan from (
    //     select phoneno,tabledata,creator,creatoroperatorgroup, max(uploaddate) as lastresponsedate from (
    //       select phoneno, tabledata, creator, creatoroperatorgroup,response, uploaddate from work where
    //           (
    //         (
    //           response = 'interested' and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinterested'] . " DAY) as char), ' 00:00:00')  
    //         )
    //         or
    //         (
    //           response in ( 'not active','not picked up') and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinactnotpickedup'] . " DAY) as char), ' 00:00:00')  
    //         )
    //       )
    //       and creator = '". $this->session->userdata('username') . "' and creatoroperatorgroup = '". $this->session->userdata('privilege') . "'
    //     ) filterinterval
    //     where
    //       (
    //       (
    //         response = 'interested' and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinterested'] . " DAY) as char), ' 00:00:00')  
    //       )
    //       or
    //       (
    //         response in ( 'not active','not picked up') and uploaddate >= concat(cast(date_sub(date_format(now(),'%Y-%m-%d'), INTERVAL ". $this->data['intervalinactnotpickedup'] . " DAY) as char), ' 00:00:00')  
    //       )
    //       )
    //     and creator = '". $this->session->userdata('username') . "' and creatoroperatorgroup = '". $this->session->userdata('privilege') . "'
    //     group by phoneno, tabledata,creator,creatoroperatorgroup
    //   ) terpilih
    //   left join work getresponse on getresponse.phoneno = terpilih.phoneno and getresponse.tabledata = terpilih.tabledata and 
    //   getresponse.creator = terpilih.creator and getresponse.creatoroperatorgroup = terpilih.creatoroperatorgroup  and terpilih.lastresponsedate = getresponse.uploaddate
    //   order by terpilih.lastresponsedate desc";



    
    $data['listphoneno'] = $this->m_masters->querying($querycheck);
    $data['listscounts'] = $data['listphoneno']->num_rows();
    // echo $data['listscounts'];

    if($data['listscounts'] == 0) 
    {
      echo '<div class="alert alert-info alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <h5><i class="icon fas fa-info"></i> Info!</h5>
                    There is no more work to be done!
                  </div>';
    }

    else
    {
      //  echo $data['listscounts'];
      // }
      
      $querycheck = "select Response from responses";

      $data['listresponse'] = $this->m_masters->querying($querycheck);
      
      $data['listphonenoarr'] = $data['listphoneno']->result();
        $data['listresponsearr'] = $data['listresponse']->result();

        $querystring = "select website from websites";
        $data['listwebsite'] = $this->m_masters->querying($querystring)->result();

        $querystring = "select bank from bankmaster";
        $data['listbankrekening'] = $this->m_masters->querying($querystring)->result();
        
        // echo $querystring;

        $this->load->view('v_CB_dg',$data);
    }
  }


  public function savecallback()
  {
    $errmsg = "";
    $response = $this->input->post("response");
    $phoneno = $this->input->post("phoneno");
    $username = $this->input->post("username");
    $tabledata = $this->input->post("tabledata");
    $keterangan = $this->input->post("keterangan");

    if($response == 'blank')
    {
      $errmsg = "error";
    }

    else 
    {
      $querystring = "insert into work values ('Callback','". $phoneno."','".$username ."','".$response."','".$keterangan."','".$tabledata."','".$this->session->userdata('privilege')."','".$this->session->userdata('username')."',now())";
      $this->m_masters->querying($querystring);
      $errmsg = "Saved Callback for ".$phoneno ;
    }

    echo $errmsg; 
  }

  public function checkavail()
  {
    $username = $this->input->post('username');
    $response = $this->apicheckavail($username);
    // echo $username.$response;
    $data['listblast'] = json_decode($response); 
    if(count($data['listblast']) == 0)
    {
      echo '<div class="alert alert-success alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-check"></i> Success!</h5>
                      Username could be used!
                    </div>';
    }
    else
    {
      echo '<div class="alert alert-danger alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-check"></i> Danger!</h5>
                      Username is taken!
                    </div>'; 
    }
  }

  public function checkavailnorek()
  {
    $norek = $this->input->post('norek');
    $response = $this->apicheckavailnorek($norek);
    // echo $username.$response;
    $data['listblast'] = json_decode($response); 
    if(count($data['listblast']) == 0)
    {
      echo '<div class="alert alert-success alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-check"></i> Success!</h5>
                      No Rekening could be used!
                    </div>';
    }
    else
    {
      echo '<div class="alert alert-danger alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-check"></i> Danger!</h5>
                      No Rek is already registered!
                    </div>'; 
    }
  }
  

  

  public function inquiretelemarket()
  {
    // echo 'asdf';
    $errmsg = "";
    $DBName = "work";

    // $querysp = "select b.id,b.Tabledata, b.OperatorGroup,a.PhoneNo,a.Username from work a inner join tabledatamapping b on a.Tabledata = b.Tabledata where b.OperatorGroup = '".$this->session->userdata('privilege') ."' and response = '' and (a.creator = '' or a.creator = '".$this->session->userdata('username')."')  and b.ID <> '0' and b.ID <> 'inactive' order by CAST(b.ID As Unsigned),CAST(a.RunningNo As Unsigned)   limit 1" ;

   
    //   $queryspg = 
    //   "SET autocommit = 1;".
    //   "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;".
    //   "START TRANSACTION;".

    // "select b.id,b.Tabledata, b.OperatorGroup,a.PhoneNo,a.Username from work a inner join tabledatamapping b on a.Tabledata = b.Tabledata where b.OperatorGroup = '".$this->session->userdata('privilege') ."'
    //   and response = '' and (a.creator = '' or a.creator = '".$this->session->userdata('username')."' or (a.creator <> '".$this->session->userdata('username')."'
    //   and TIMESTAMPDIFF(MINUTE,a.uploaddate,NOW()) > 1440 ))  and b.ID <> '0' and b.ID <> 'inactive' order by CAST(b.ID As Unsigned),CAST(a.RunningNo As Unsigned)   limit 1 for update;".

      
    //   "update work a , tabledatamapping b on a.Tabledata = b.Tabledata 
    //  set a.creator = '".$this->session->userdata('username')."' , a.creatoroperatorgroup = '".$this->session->userdata('privilege') ."', uploaddate = now() where
    //  b.OperatorGroup = '".$this->session->userdata('privilege') ."' and response = '' and (a.creator = '' or a.creator = '".$this->session->userdata('username')."' or 
    //  (a.creator <> '".$this->session->userdata('username')."' and TIMESTAMPDIFF(MINUTE,a.uploaddate,NOW()) > 1440 ))  and b.ID <> '0' 
    //  and b.ID <> 'inactive' order by CAST(b.ID As Unsigned),CAST(a.RunningNo As Unsigned)   limit 1;" ;

    $this->m_masters->querying("LOCK TABLES work WRITE, work as kerja WRITE, work as a WRITE, tabledatamapping WRITE, tabledatamapping as b WRITE");
    $this->m_masters->querying("update  work as kerja
    inner join ( 
    select b.id,b.Tabledata, b.OperatorGroup,a.PhoneNo,a.Username from work a inner join tabledatamapping b on a.Tabledata = b.Tabledata where b.OperatorGroup = '".$this->session->userdata('privilege') ."' and response = '' and (a.creator = '' or a.creator = '".$this->session->userdata('username')."'
    or (a.creator <> '".$this->session->userdata('username')."' and TIMESTAMPDIFF(MINUTE,a.uploaddate,NOW()) > 1440 )) and b.ID <> '0' and b.ID <> 'inactive' order by CAST(b.ID As Unsigned),CAST(a.RunningNo As Unsigned) limit 1 
    )
    total on kerja.tabledata = total.tabledata and kerja.phoneno = total.phoneno set kerja.uploaddate = now(),kerja.creator = '".$this->session->userdata('username')."', kerja.creatoroperatorgroup = '".$this->session->userdata('privilege') ."'");
    // $this->m_masters->querying("update work a  set a.creator = 'burungloegede'  where a.phoneno = '+6285333706069'  and a.tabledata = 'TSP-timsus-casino-020220215.xlsx' order by a.creator limit 1");
    $this->m_masters->querying("UNLOCK TABLES");
    
    // $this->m_masters->querying($queryspg);

    
    //  "update work a left join tabledatamapping b on a.tabledata = b.tabledata set a.creator = 'Gablo12345'  where a.phoneno = '+6285333706069'  and a.tabledata = 'TSP-timsus-casino-020220215.xlsx' order by a.creator limit 1" ; 
    //  "COMMIT;";

     
    
     
     
     
     $querysp = 
      "select b.id,b.Tabledata, b.OperatorGroup,a.PhoneNo,a.Username from work a inner join tabledatamapping b on a.Tabledata = b.Tabledata where b.OperatorGroup = '".$this->session->userdata('privilege') ."'
      and response = '' and (a.creator = '' or a.creator = '".$this->session->userdata('username')."' or (a.creator <> '".$this->session->userdata('username')."'
      and TIMESTAMPDIFF(MINUTE,a.uploaddate,NOW()) > 1440 ))  and b.ID <> '0' and b.ID <> 'inactive' order by CAST(b.ID As Unsigned),CAST(a.RunningNo As Unsigned)   limit 1;";
      
      
      

      
      
      
      $data['listphoneno'] = $this->m_masters->querying($querysp);
      $data['listscounts'] = $data['listphoneno']->num_rows();
      $data['listphonenoarr'] = $data['listphoneno']->result();

      $currphoneno = $data['listphonenoarr'][0]->PhoneNo;
      $curroperatorgroup = $data['listphonenoarr'][0]->OperatorGroup;
      $currtabledata = $data['listphonenoarr'][0]->Tabledata;


    //  $querylock = 
    // //  "BEGIN;".
    //  "select * from work where phoneno = '" . $currphoneno . "' and tabledata = '" .$currtabledata . "' for update;".
    //  "Update work set creator = '".$this->session->userdata('username')."' , creatoroperatorgroup =  '".$this->session->userdata('privilege') ."' where phoneno = '" . $currphoneno . "' and tabledata = '" .$currtabledata . "';" .
    //  "COMMIT;"
    //  ;
     
    //  $this->m_masters->querying($querylock);
     
     

    


    if($data['listscounts'] == 0) 
    {
      echo '<div class="alert alert-info alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <h5><i class="icon fas fa-info"></i> Info!</h5>
                    There is no more work to be done!
                  </div>';
    }

    else
    {
      
//      $querycheck = "select Response from responses";
//      $data['listresponse'] = $this->m_masters->querying($querycheck);
//        $data['listresponsearr'] = $data['listresponse']->result();

      //  $querystring = "select website from websites";
      //  $data['listwebsite'] = $this->m_masters->querying($querystring)->result();

      //  $querystring = "select bank from bankmaster";
      //  $data['listbankrekening'] = $this->m_masters->querying($querystring)->result();


      $data['website'] = $this->session->userdata('privilege');

      $currphoneno = $data['listphonenoarr'][0]->PhoneNo;
      $curroperatorgroup = $data['listphonenoarr'][0]->OperatorGroup;
      $currtabledata = $data['listphonenoarr'][0]->Tabledata;


    
            
            echo $queryspg . "<br>"  ;
        $this->load->view('v_ILK_dg',$data);

    }
//    echo $querysp;
//    echo "<br>".$queryowned;

  }
  public function changeoperatorass()
  {
    $errmsg = "";
    $DBName = "work";
    $privilege = $this->input->post('privilege');
    $operator = $this->input->post('operator');

    if($operator == 'blank')
    {
      $operator = '';
      $errmsg = $errmsg . "<br>" . '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Operator cannot be empty!
                            </div>';
    }

    if($privilege == 'blank')
    {
      $operatorgroup = '';
      $errmsg = $errmsg . "<br>" . '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Privilege cannot be empty!
                            </div>';
    }

    if ($errmsg <> '')
    {

      echo $errmsg;
    }
    else
    {
      $operatorgroupfrom = explode("-",$operator)[1];
      $operator = explode("-",$operator)[0];
    

      $querystring = "update operators set privilege = '" . $privilege ."' where operator = '".$operator . "'";
      $this->m_masters->querying($querystring);
      // echo $querystring;
      echo '<div class="alert alert-success alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-check"></i> Success!</h5>
                      Operator Privilege Successfully Updated!
                    </div>';
      // echo $querystring;
    }
  }

  public function nextalert()
  { 
    if(empty($this->session->userdata('username')))
    {
      echo "0";
    }
    else
    {
      $phoneno = $this->input->post("phoneno");
      $response = $this->input->post("response");
      $tabledata = $this->input->post("tabledata");
      $keterangan = $this->input->post("keterangan");
      if($response == 'blank')
      {
        // echo '<div class="alert alert-danger alert-dismissible">
      //                 <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
      //                 <h5><i class="icon fas fa-ban"></i> Alert!</h5>
      //                 Pick Response Correctly!
      //               </div>';
            // $this->load->view('v_noresponseerror');
        echo "Pick Response!";
      }
      else
      { 
        $querystring = "update work set response = '".$response."', keterangan ='" . $keterangan ."'  where phoneno = '".$phoneno . "' and tabledata = '".$tabledata."'";
        $this->m_masters->querying($querystring);

        $querystring = "select * from work where response = '' and tabledata = '".$tabledata . "'";
        // $jumlahdatasisa = $this->m_masters->querying($querystring)->num_rows();
        // if($jumlahdatasisa == 0)
        // {
        //  $querystring = "update tabledatamapping set id = '0' where tabledata = '".$tabledata ."'";
        //  $this->m_masters->querying($querystring);
        // }
        $this->inquiretelemarket(1);
      }
    }
  }

  public function saveresponse()
  {
    $phoneno = $this->input->post("phoneno");
    $response = $this->input->post("response");
    $tabledata = $this->input->post("tabledata");


    $querystring = "update work set response ='" . $response ."' ,uploaddate = now()   where phoneno = '".$phoneno . "' and tabledata = '".$tabledata."'";
    $this->m_masters->querying($querystring);
    
    // echo $querystring;
  }

  public function submitplayer()
  {

    $errmsg = "";

    $phoneno = $this->input->post("phoneno");
    $username = $this->input->post("username");
    $password = $this->input->post("password");
    $rekening = $this->input->post("rekening");
    $namarekening = $this->input->post("namarekening");
    $bank = $this->input->post("bank");
    // $website = $this->input->post("website");
    $website = $this->session->userdata('privilege');
    $wa = $this->input->post("wa");
    $referral = $this->input->post("referral");
    $td = $this->input->post("td");
    $note = $this->input->post("note");



    if($username == "")
    {
      $errmsg = $errmsg . "<br>" . '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please Input Username!
                            </div>';
    }

    if($username == "")
    {
      $errmsg = $errmsg . "<br>" . '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please Input Password!
                            </div>';
    }

    if($rekening == "")
    {
      $errmsg = $errmsg . "<br>" . '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please Input Nomor Rekening!
                            </div>';
    }
    if($namarekening == "")
    {
      $errmsg = $errmsg . "<br>" . '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please Input Nama Rekening!
                            </div>';
    }
    if($bank == "blank")
    {
      $errmsg = $errmsg . "<br>" . '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please Input Bank!
                            </div>';
    }
    if($website == "blank")
    {
      $errmsg = $errmsg . "<br>" . '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please Input Website!
                            </div>';
    }

    if($errmsg == "")
    {
      $querystring = "insert into players values ('". $phoneno . "','" . $username ."','". $password."','". $rekening . "','".$namarekening."','".$bank."','".$website."','".$wa."','".$referral."','".$td."','".$this->session->userdata('username') . "','".$this->session->userdata('privilege')."',now(),'Open','".$note."')";
      $this->m_masters->querying($querystring);
      echo '<div class="alert alert-success alert-dismissible">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                  <h5><i class="icon fas fa-check"></i> Success!</h5>
                 Player Data Submission Successful!
                </div>';
      // echo $querystring;
    }
    else
    {
      echo $errmsg;
    }

  }

  public function saveoperatorgroup()
  {
    $phoneno = $this->input->post("phoneno");
        $operatorgroup = $this->input->post("operatorgroup");

        if($operatorgroup == "blank")
        {
          $operatorgroup = "";
        }
    $querystring = "update work set operatorgroup ='" . $operatorgroup ."' where phoneno = '".$phoneno . "'";
    $this->m_masters->updating($querystring);

  }



  public function saveidpriority()
  {
    $phoneno = $this->input->post("phoneno");
        $ID = $this->input->post("ID");
        if($ID == "blank")
        {
          $ID = "";
        }
    $querystring = "update work set ID ='" . $ID ."' where phoneno = '".$phoneno . "'";
    $this->m_masters->updating($querystring);
  }


  public function inquireoperatorgroup()
  {
    $errmsg = "";
    $DBName = "operatorgroups";
    $operatorgroup = $this->input->post('operatorgroup');
    $data['querycheck'] = "select * from operatorgroups where operatorgroup like '%". $operatorgroup ."%' order by operatorgroup" ;
    $data['lists'] = $this->m_masters->querying($data['querycheck']);
    $data['listscounts'] = $data['lists']->num_rows();
    if($data['listscounts'] == 0) 
    {
      echo '<div class="alert alert-warning alert-dismissible">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                  <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                  There is no said operator group!
                </div>';
    }
    else
    {
        $data['listoperatorgroups'] = $data['lists']->result();
        $this->load->view('v_IOG_dg',$data);
    }
  }

  

  public function submitoperatorgroup()
  {
    $errmsg = "";
    $DBName = "operatorgroups";
    $operatorgroup = $this->input->post('operatorgroup');

    if($operatorgroup == "")
    {
      $errmsg = $errmsg. "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill Operator Group!
                            </div>';
    }

    if ($errmsg == "")
    {
      $data['querycheck'] = "select * from operatorgroups where operatorgroup = '". $operatorgroup ."'" ;
      $data['lists'] = $this->m_masters->querying($data['querycheck']);
      $data['listscounts'] = $data['lists']->num_rows();
      if($data['listscounts'] >= 1) 
      {
        echo '<div class="alert alert-warning alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                      Operator Group already exists!
                    </div>';
      }

      else
      {
          $data['querystring0'] = "insert into ". $DBName . " values ('";
        $data['querystring1'] = $operatorgroup . "'";
        $data['querystring3'] = ",'" .$this->session->userdata('username') . "',now())";    
        $data['querystring'] =  
            $data['querystring0'].
            $data['querystring1'].
            $data['querystring3'];
        $this->m_masters->inserting(
          $data['querystring']
        );  
        echo '<div class="alert alert-success alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-check"></i> Success!</h5>
                      Successfully Submitted!
                    </div>';
            // echo $data['querystring'];
      }
    }
    else
    {
      echo $errmsg ;
    }
  }


  public function deleteoperatorgroup()
  {
    $errmsg = "";
    $DBName = "operatorgroups";
    $operatorgroup = $this->input->post('operatorgroup');
    if($operatorgroup == "")
    {
      $errmsg = $errmsg. "<br>". "Please Operator Group to delete!";
    }
    if ($errmsg == "")
    {
      $data['querycheck'] = "select * from operatorgroups where operatorgroup = '". $operatorgroup ."'" ;
      $data['lists'] = $this->m_masters->querying($data['querycheck']);
      $data['listscounts'] = $data['lists']->num_rows();
      if($data['listscounts'] == 0) 
      {
        echo '<div class="alert alert-warning alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                      There is no said Operator Group!
                    </div>';
      }
      else
      {
          $querydelete = "delete from operatorgroups where operatorgroup = '" .$operatorgroup ."'";
          $this->m_masters->querying($querydelete);
          echo '<div class="alert alert-success alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-check"></i> Success!</h5>
                      Deletion Successful!
                    </div>';
      }
    }
    else
    {
      echo $errmsg ;
    }
  }

  public function inquirefooter()
  {
    $errmsg = "";
    $DBName = "messages";
    $cdselector = $this->input->post('cdselector');
    $dselector = $this->input->post('dselector');
    $sselector = $this->input->post('sselector');

    if($cdselector <> "")
    {
      $data['querycheck'] = "select * from footers where ftcd = '".$cdselector . "' and  detail like '%". urlencode($dselector) ."%' and summary like '%" .urlencode($sselector). "%'" ;
    }
    else
    {
      $data['querycheck'] = "select * from footers where detail like '%" .urlencode($dselector) ."%' and summary like '%" .urlencode($sselector). "%'";
    }
    // echo $data['querycheck'];
    $data['lists'] = $this->m_masters->querying($data['querycheck']);
    $data['listscounts'] = $data['lists']->num_rows();

    // echo $data['listscounts'];
    if($data['listscounts'] == 0) 
    {
      echo '<div class="alert alert-warning alert-dismissible">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                  <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                  There is no said Footer Code!
                </div>';
    }
    else
    {

        $data['listmessage'] = $data['lists']->result();
        $this->load->view('v_FC_dg',$data);
    }
    
  }

  public function showfooter($type,$ftcd)
  {
    $data['string'] = explode("_",$ftcd);

    for($i = 0; $i<count($data['string']);$i++)
    {
      $querystring = "select detail,summary from footers where ftcd = '".$data['string'][$i]."'";
      $data['detail'][$i] = urldecode($this->m_masters->querying($querystring)->result()[0]->detail);
      $data['summary'][$i] = urldecode($this->m_masters->querying($querystring)->result()[0]->summary);
    }
    
    if($type == 1)
    {
      $this->load->view('v_footer_type1',$data);
    }
    else if($type == 2)
    {
      $this->load->view('v_footer_type2',$data);
    }
    if($type == 3)
    {
      $this->load->view('v_footer_type3',$data);
    }
    if($type == 4)
    {
      $this->load->view('v_footer_type4',$data);
    }
  }

  public function inquiremessage()
  {
    $errmsg = "";
    $DBName = "messages";
    $cdselector = $this->input->post('cdselector');
    $msgselector = $this->input->post('msgselector');

    if($cdselector <> "")
    {
      $data['querycheck'] = "select * from messages where msgcd = '".$cdselector . "' and  message like '%". urlencode($msgselector) ."%'" ;
    }
    else
    {
      $data['querycheck'] = "select * from messages where message like '%" .urlencode($msgselector) ."%'";
    }
    // echo $data['querycheck'];
    $data['lists'] = $this->m_masters->querying($data['querycheck']);
    $data['listscounts'] = $data['lists']->num_rows();

    // echo $data['listscounts'];
    if($data['listscounts'] == 0) 
    {
      echo '<div class="alert alert-warning alert-dismissible">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                  <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                  There is no said Message Code!
                </div>';
    }
    else
    {

        $data['listmessage'] = $data['lists']->result();
        $this->load->view('v_WB_dg',$data);
    }
    
  }

  public function inquireoperator()
  {
    $errmsg = "";
    $DBName = "operators";
    $operator = $this->input->post('operator');
    $operatorgroup = $this->input->post('operatorgroup');
    $privilege = $this->input->post('privilege');
    if ($privilege == 'blank')
    {
      $privilege = '';
    }
    if ($operatorgroup == 'blank')
    {
      $operatorgroup = '';
    }
    $data['querycheck'] = "select * from operators where operator like '%". $operator ."%' and operatorgroup like '%" .$operatorgroup ."%' and privilege like '%".$privilege."%'" ;
    $data['lists'] = $this->m_masters->querying($data['querycheck']);
    $data['listscounts'] = $data['lists']->num_rows();
    if($data['listscounts'] == 0) 
    {
      echo '<div class="alert alert-warning alert-dismissible">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                  <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                  There is no said operator!
                </div>';
    }
    else
    {
        $data['listoperator'] = $data['lists']->result();
        $this->load->view('v_IO_dg',$data);
        
    }
    
    // echo $data['querycheck'];
  }

  public function changepasswordawal()
  {
    $this->load->view('v_CPA');
  }

  public function changepasswordtele()
  {
    $errmsg = "";
    $operator = $this->input->post('operator');
    $password = $this->input->post('password');
    $confpassword = $this->input->post('confpassword');
    if($password == "blank")
    {
      $errmsg = $errmsg. "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Pick Operator to change password!
                            </div>';
    }
    if($password == "")
    {
      $errmsg = $errmsg. "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Password cannot be empty!
                            </div>';
    }
    if($password <> $confpassword)
    {
      $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Password and Confirm Password does not match!
                            </div>';
    }

    if ($errmsg == "")
    {
          $querystring = "update operators set password = password('".$password."') where operator = '".$operator."'";
        $this->m_masters->querying($querystring); 
        echo '<div class="alert alert-success alert-dismissible">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                  <h5><i class="icon fas fa-check"></i> Success!</h5>
                  Password Successfully updated!
                </div>';
    }
    else
    {
      echo $errmsg ;
    }
  }

  public function changepassword()
  {
    $errmsg = "";
    $password = $this->input->post('password');
    $confpassword = $this->input->post('confpassword');

    if($password == "")
    {
      $errmsg = $errmsg. "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Password cannot be empty!
                            </div>';
    }
    if($password <> $confpassword)
    {
      $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Password and Confirm Password does not match!
                            </div>';
    }

    if ($errmsg == "")
    {
          $querystring = "update operators set password = password('".$password."') where operator = '".$this->session->userdata('username')."'";
        $this->m_masters->querying($querystring); 
        echo '<div class="alert alert-success alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-check"></i> Success!</h5>
                      Password Successfully updated!
                    </div>';
    }
    else
    {
      echo $errmsg ;
    }
  }

  public function submitfooter()
  {
    $errmsg = "";
    $DBName = "footers";
    $cdselector = $this->input->post('cdselector');
    $dselector = $this->input->post('dselector');
    $sselector = $this->input->post('sselector');

    // echo $cdselector . $msgselector;
    if($cdselector == "")
    {
      $errmsg = $errmsg. "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill Message Code!
                            </div>';
    }


    if($dselector == "" || $sselector == "")
    {
      $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill Detail and Summary!
                            </div>';
    }
    if ($errmsg == "")
    {

      $data['querycheck'] = "select * from footers where ftcd = '". $cdselector ."'" ;

      $data['lists'] = $this->m_masters->querying($data['querycheck']);
      $data['listscounts'] = $data['lists']->num_rows();

      if($data['listscounts'] >= 1) 
      {
        echo '<div class="alert alert-danger alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                      Footer Code already exists!
                    </div>';
      }

      else
      {
          $data['querystring0'] = "insert into ". $DBName . " values ('";
        $data['querystring1'] = $cdselector . "','";
        $data['querystring1a'] = urlencode($sselector) . "','";
        $data['querystring2'] = urlencode($dselector) . "','";
        $data['querystring4'] = $this->session->userdata('username') . "',now())";    
        $data['querystring'] =  
            $data['querystring0'].
            $data['querystring1'].
            $data['querystring1a'].
            $data['querystring2'].
            $data['querystring4'];
        $this->m_masters->inserting(
          $data['querystring']
        );  

        
        echo '<div class="alert alert-success alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-check"></i> Success!</h5>
                      Successfully Submitted Footer ke TMP!
                    </div>';
            // echo $data['querystring'];
      }
    }
    else
    {
      echo $errmsg ;
    }
  }

  public function submitmessage()
  {
    $errmsg = "";
    $DBName = "messages";
    $cdselector = $this->input->post('cdselector');
    $msgselector = $this->input->post('msgselector');

    // echo $cdselector . $msgselector;
    if($cdselector == "")
    {
      $errmsg = $errmsg. "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill Message Code!
                            </div>';
    }


    if($msgselector == "")
    {
      $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill Message!
                            </div>';
    }
    if ($errmsg == "")
    {

      $data['querycheck'] = "select * from messages where msgcd = '". $cdselector ."'" ;

      $data['lists'] = $this->m_masters->querying($data['querycheck']);
      $data['listscounts'] = $data['lists']->num_rows();

      if($data['listscounts'] >= 1) 
      {
        echo '<div class="alert alert-danger alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                      Message Code already exists!
                    </div>';
      }

      else
      {
          $data['querystring0'] = "insert into ". $DBName . " values ('";
        $data['querystring1'] = $cdselector . "','";
        $data['querystring2'] = urlencode($msgselector) . "','";
        $data['querystring4'] = $this->session->userdata('username') . "',now())";    
        $data['querystring'] =  
            $data['querystring0'].
            $data['querystring1'].
            $data['querystring2'].
            $data['querystring4'];
        $this->m_masters->inserting(
          $data['querystring']
        );  

        // $querystring = "select createddate from messages where msgcd = '".$cdselector . "'";
        // $createddate = $this->m_masters->querying($querystring)->result()[0]->createddate;
        $response = $this->wainsertmessage($cdselector,urlencode($msgselector));
        if(strpos(json_decode($response)->{'Info'} ,"Berhasil disimpan") > 1)
        {

        
            $data['querystring0'] = "insert into ". $DBName . " values ('";
          $data['querystring1'] = $cdselector . "','";
          $data['querystring2'] = urlencode($msgselector) . "','";
          $data['querystring4'] = $this->session->userdata('username') . "',now())";    
          $data['querystring'] =  
              $data['querystring0'].
              $data['querystring1'].
              $data['querystring2'].
              $data['querystring4'];
          $this->m_masters->inserting(
            $data['querystring']
          );  
        }
        else
        {
          '<div class="alert alert-danger alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                    Putus koneksi ke babi air! Tolong submit ulang message!
                </div>';
          
        }
        echo '<div class="alert alert-success alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-check"></i> Success!</h5>
                      Successfully Submitted di babi air dan TMP!
                    </div>';
            // echo $data['querystring'];
      }
    }
    else
    {
      echo $errmsg ;
    }
  }

  public function submitoperator()
  {
    $errmsg = "";
    $DBName = "operators";
    $operator = $this->input->post('operator');
    $operatorgroup = $this->input->post('operatorgroup');
    $password = $this->input->post('password');
    $confpassword = $this->input->post('confpassword');
    $privilege = $this->input->post('privilege');

    // echo "asdf";
    if($operator == "")
    {
      $errmsg = $errmsg. "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please fill Operator!
                            </div>';
    }
    if($operatorgroup == "blank")
    {
      $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please choose Operator Group !
                            </div>';
    }
    if($privilege == "blank")
    {
      $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Please choose Privilege!
                            </div>';
    }
    if($password == "")
    {
      $errmsg = $errmsg. "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Password cannot be empty!
                            </div>';
    }
    if($password <> $confpassword)
    {
      $errmsg = $errmsg . "<br>". '<div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-ban"></i> Alert!</h5>
                              Password and Confirm Password does not match!
                            </div>';
    }

    if ($errmsg == "")
    {
      $data['querycheck'] = "select * from operators where operator = '". $operator ."'" ;
      $data['lists'] = $this->m_masters->querying($data['querycheck']);
      $data['listscounts'] = $data['lists']->num_rows();
      if($data['listscounts'] >= 1) 
      {
        echo '<div class="alert alert-warning alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                      Operator already exists!
                    </div>';
      }

      else
      {
          $data['querystring0'] = "insert into ". $DBName . " values ('";
        $data['querystring1'] = $operator . "',";
        $data['querystring2'] = "password('".$password ."'),'";
        $data['querystring3'] = $operatorgroup . "','" . $privilege . "','0'";
        $data['querystring4'] = ",'" .$this->session->userdata('username') . "',now())";    
        $data['querystring'] =  
            $data['querystring0'].
            $data['querystring1'].
            $data['querystring2'].
            $data['querystring3'].
            $data['querystring4'];
        $this->m_masters->inserting(
          $data['querystring']
        );  
        // echo $data['querystring'];
        echo '<div class="alert alert-success alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-check"></i> Success!</h5>
                      Successfully Submitted!
                    </div>';
            // echo $data['querystring'];
      }
    }
    else
    {
      echo $errmsg ;
    }
  }

  public function deletefooter()
  {
    $errmsg = "";
    $DBName = "footers";
    $cdselector = $this->input->post('cdselector');
    $dselector = $this->input->post('dselector');
    $sselector = $this->input->post('sselector');

    if($cdselector == "")
    {
      $errmsg = $errmsg. "<br>". '<div class="alert alert-warning alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                              Please fill Footer Code to delete!
                            </div>';
    }

    if ($errmsg == "")
    {
      $data['querycheck'] = "select * from footers where ftcd = '". $cdselector ."'" ;
      $data['lists'] = $this->m_masters->querying($data['querycheck']);
      $data['listscounts'] = $data['lists']->num_rows();
      if($data['listscounts'] == 0) 
      {
        echo '<div class="alert alert-warning alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                      There is no said Message Code!
                    </div>';
      }
      else
      {
          $querydelete = "delete from footers where ftcd = '" .$cdselector ."'";
          $this->m_masters->querying($querydelete);
          echo '<div class="alert alert-success alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-check"></i> Success!</h5>
                      Deletion Successful!
                    </div>';
      }
    }
    else
    {
      echo $errmsg ;
    }
  }


  public function deletemessage()
  {
    
    $errmsg = "";
    $DBName = "messages";
    $cdselector = $this->input->post('cdselector');
    $msgselector = $this->input->post('msgselector');
    
    
    
    if($cdselector == "")
    {
      $errmsg = $errmsg. "<br>". '<div class="alert alert-warning alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                              Please fill Message Code to delete!
                            </div>';                           
    }
    
    if ($errmsg == "")
    {
    
      $data['querycheck'] = "select * from messages where msgcd = '". $cdselector ."'" ;
      $data['lists'] = $this->m_masters->querying($data['querycheck']);
      $data['listscounts'] = $data['lists']->num_rows();
      
      if($data['listscounts'] == 0) 
      {
        echo '<div class="alert alert-warning alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                      There is no said Message Code!
                    </div>';
      }
      else
      {
          $querydelete = "delete from messages where msgcd = '" .$cdselector ."'";
          $this->m_masters->querying($querydelete);
          echo '<div class="alert alert-success alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-check"></i> Success!</h5>
                      Deletion Successful!
                    </div>';
        //  echo $querydelete;
      }
    }
    else
    {
      echo $errmsg ;
    }
  }

  public function deleteoperator()
  {
    $errmsg = "";
    $DBName = "operators";
    $operator = $this->input->post('operator');
    if($operator == "")
    {
      $errmsg = $errmsg. "<br>". '<div class="alert alert-warning alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                              <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                              Please Operator to delete!
                            </div>';
    }
    if ($errmsg == "")
    {
      $data['querycheck'] = "select * from operators where operator = '". $operator ."'" ;
      $data['lists'] = $this->m_masters->querying($data['querycheck']);
      $data['listscounts'] = $data['lists']->num_rows();
      if($data['listscounts'] == 0) 
      {
        echo '<div class="alert alert-warning alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                      There is no said Operator!
                    </div>';
      }
      else
      {
          $querydelete = "delete from operators where operator = '" .$operator ."'";
          $this->m_masters->querying($querydelete);
          echo '<div class="alert alert-success alert-dismissible">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <h5><i class="icon fas fa-check"></i> Success!</h5>
                      Deletion Successful!
                    </div>';
      }
    }
    else
    {
      echo $errmsg ;
    }
  }


}