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

class CT_supplier extends CI_Controller {
    function __construct()
	{
	  parent::__construct();
		if (!$this->dx_auth->is_logged_in()) {
			header('HTTP/1.1 401 Unauthorize');die('expire'); 
		}
		
		$uid = $this->session->userdata('DX_user_id');
		
		if(!permissionAuth(2) && $uid != RID){ 
			header('HTTP/1.1 401 Unauthorize');die('noaccess');
		}
		$this->load->helper(array('url', 'form'));
	    $this->load->library(array('session', 'encrypt'));
		$this->load->model("settings/mdl_settings", 'mdl_settings');
		$this->load->library('msdb'); 
	}
    
    
    function index()
    {
        $this->load->view('settings/view_supplier');
    }
	function loaddatasupplier(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'inv_hdr_id'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "supplier_code" ) {
						$searchString = $k->data;
						$where .= " and supplier_code like  '%".$searchString."%'"; 
					} else if ( $k->field == "supplier_name" ) {
						$searchString = $k->data;
						$where .= " and supplier_name like  '%".$searchString."%'";
					} else if ( $k->field == "supplier_address" ) {
						$searchString = $k->data;
						$where .= " and supplier_address like  '%".$searchString."%'"; 
					} else if ( $k->field == "supplier_country" ) {
						$searchString = $k->data;
						$where .= " and supplier_country like  '%".$searchString."%'"; 
					} else if ( $k->field == "base_price" ) {
						$searchString = $k->data;
						$where .= " and base_price like  '%".$searchString."%'"; 
					} else if ( $k->field == "copper_base_reff" ) {
						$searchString = $k->data;
						$where .= " and copper_base_reff like  '%".$searchString."%'"; 
					} else if ( $k->field == "subgct" ) {
						$searchString = $k->data;
						$where .= " and subgct like  '%".$searchString."%'"; 
					} else if ( $k->field == "subcode_as400" ) {
						$searchString = $k->data;
						$where .= " and subcode_as400 like  '%". $searchString."%'";
					}
				}
			}
		}
		
		
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->datasupplier_All($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->datasupplier_CountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
        foreach($records as $r){
						
			$responce->rows[$i]['id']=$r->id; 
			$responce->rows[$i]['supplier_code']=$r->supplier_code; 
			$responce->rows[$i]['supplier_name']=$r->supplier_name; 
			$responce->rows[$i]['supplier_address']=$r->supplier_address;
			$responce->rows[$i]['supplier_addressa']=$r->supplier_address1;
			$responce->rows[$i]['supplier_country']= $r->supplier_country;
			$responce->rows[$i]['base_price']=$r->base_price;
			$responce->rows[$i]['copper_base_reff']=$r->copper_base_reff; 
			$responce->rows[$i]['subgct']=$r->subgct; 
			$responce->rows[$i]['subcode_as400']=$r->subcode_as400;
			$responce->rows[$i]['NPWP']= $r->NPWP;
			$responce->rows[$i]['NOIJIN']=$r->NOIJIN;
			$responce->rows[$i]['NOKONTRAK']=$r->NOKONTRAK; 
			$responce->rows[$i]['TGLIJIN']=$r->TGLIJIN; 
			$responce->rows[$i]['TGLKONTRAK']=$r->TGLKONTRAK;
	
			$i++;
		}
		echo json_encode($responce);
	
	}
	
	function view_update_datasupplier(){
	
		$this->load->view('settings/view_update_datasupplier');
	
	}
	
	function getdataalamatsuppier(){
		
		$bc23dir = $this->config->item('APP_modulbc23');
		
		echo " exec('spi_getdataalamat_supplier @conn=''$bc23dir''')";
		die();
		
		$qry = $this->db->query("
			
			 exec('spi_getdataalamat_supplier @conn=''$bc23dir''')
			 
			
			 ");
		 $rs = $qry->result_array();
         // $r = $qry->result();		
		 // var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description']);
		 }  
		  echo json_encode($responce);
	
	}
	
	function getdatasupplier(){
	
		$qry = $this->db->query("
			
			BEGIN TRY
				exec('spi_supplier')
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			
			");
		 $rs = $qry->result_array();
         // $r = $qry->result();		
		 // var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' File/s Loaded');
		 }  
		  echo json_encode($responce);
		 // $stmt = " exec('spi_supplier') ";
		 // $qry = mssql_query($stmt); 
		 // $row = mssql_fetch_array($qry); 
		 // var_dump($row);die();
	
	}
	public function upload_file_supplier(){
	
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfilesupplier';
	   //$username = $this->session->userdata('DX_user_id');
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'supplier';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'invoice/supplier/';
		  $config['allowed_types'] = 'xls';
		  $config['max_size']  = 1024 * 100;
		  $config['encrypt_name'] = false;
		  $config['overwrite']=true;
		  $config['remove_spaces']=true;
		  $this->load->library('upload', $config);
		  if (!$this->upload->do_upload($file_element_name))
		  {
			 $status = 'error';
			 $msg = $this->upload->display_errors('', '');
		  }
		  else
		  {
			 $data = $this->upload->data();
			 
			 // print_r($data);
			 // die();
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'invoice/supplier/log/'.$data['file_name'];
				$filename=$data['file_name'];
				
				$qry = $this->db->query("
					BEGIN TRY
					
					 exec('[spuload_supplier] @filepath=''$myFile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ')
					
					END TRY
					BEGIN CATCH 
						SELECT 
						'error' AS status
						,ERROR_MESSAGE() AS description;
						
					END CATCH;
					
					");
				 $rs = $qry->result_array();
				 // $r = $qry->result();		
				 // var_dump($r);die();
				 foreach ($rs as $row){
					 $status = $row['status'];
					 $msg = $row['description'];
				 }  
				//  echo json_encode($responce);
				 // $stmt = " exec('[spuload_supplier]') ";
				 // $qry = mssql_query($stmt); 
				 // $row = mssql_fetch_array($qry); 
				 // var_dump($row);die();
						
				
				
				
				$status = $status;
				$msg = $msg;
			 }
			 else
			 {
				unlink($data['full_path']);
				$status = "error";
				$msg = "Something went wrong when saving the file, please try again.";
			 }
		  }
		  @unlink($_FILES[$file_element_name]);
	   }
	   echo json_encode(array('status' => $status, 'msg' => $msg));
	
	
	}
	
	function data_uploadsupplier(){
	
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_invoice_upload'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "filename" ) {
						$searchString = $k->data;
						$where .= " and filename like  '%".$searchString."%'"; 
					} else if ( $k->field == "date_upload" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[date_upload],101)  =  '$searchString'"; 
					} else if ( $k->field == "status_upload" ) {
						$searchString = $k->data;
						$where .= " and status_upload like  '%".$searchString."%'"; 
					}  else if ( $k->field == "create_by" ) {
						$searchString = $k->data;
						$where .= " and create_by like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->upload_supplierAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->upload_suppliercountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
        foreach($records as $r){
						
			$responce->rows[$i]['id_supplier_upload']=$r->id_supplier_upload; 
			$responce->rows[$i]['date_upload']=$r->date_upload; 
			$responce->rows[$i]['filename']= $r->filename;//str_replace(".csv","", $r->filename); 
			$responce->rows[$i]['filename2']=str_replace(".xls","", $r->filename);
			$responce->rows[$i]['status_upload']=$r->status_upload;
			$responce->rows[$i]['create_date']=$r->create_date;
			$responce->rows[$i]['create_by']=$r->create_by;
			$responce->rows[$i]['tipe']=$r->tipe;
		
			
			$i++;
		}
		echo json_encode($responce);	
	
	
	}
	
	function deletefile_supplier(){
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$tipe = (isset($_POST['tipe']) && !empty($_POST['tipe']))?$_POST['tipe']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$id_supplier_upload = (isset($_POST['id_supplier_upload']) && !empty($_POST['id_supplier_upload']))?$_POST['id_supplier_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		//$username = $this->session->userdata('DX_user_id');
	    $username = $this->session->userdata('DX_username');
		$apppath = $this->config->item('APP_upload_path');
		
		$path=$apppath.'invoice/supplier/'.$filename;
		$pathnew=$apppath.'invoice/supplier/log/'.$filename;
		
		if (!file_exists($path)) {
		   echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
			die();
		}
		
		
		
		$qry = $this->db->query("
			BEGIN TRY
			
			 exec('[spuload_supplier] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_supplier_upload ')
			
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
			");
		 $rs = $qry->result_array();
		 // $r = $qry->result();		
		 // var_dump($r);die();
		 foreach ($rs as $row){
			 $status = $row['status'];
			 $msg = $row['description'];
		 }  
		//  echo json_encode($responce);
		 // $stmt = " exec('[spuload_supplier]') ";
		 // $qry = mssql_query($stmt); 
		 // $row = mssql_fetch_array($qry); 
		 // var_dump($row);die();
		
		$status = $status;
		$msg = $msg;
		
		if ($status=='00'){
			copy($path, $pathnew) or die(array('sts' => '00','desc' => "Unable to copy $path to $pathnew."));
			if (file_exists($path)) {
				unlink($path);
			} else {
				echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
				die();
			}
		}
		echo json_encode(array('sts' => $status, 'desc' => $msg));
	
	
	}
	
	function view_supplier_frommodul(){
	
		$this->load->view('settings/view_supplier_frommodul');
	
	}
	function data_modulsupplier(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'PasokNama'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "PasokNama" ) {
						$searchString = $k->data;
						$where .= " and PasokNama like  '%".$searchString."%'"; 
					} else if ( $k->field == "PasokAlmt" ) {
						$searchString = $k->data;
						$where .= " and PasokAlmt like  '%".$searchString."%'"; 
					}  else if ( $k->field == "PasokNeg" ) {
						$searchString = $k->data;
						$where .= " and PasokNeg like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->upload_modulsupplierAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->upload_modulsuppliercountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
        foreach($records as $r){
						
			$responce->rows[$i]['PasokNama']=$r->PasokNama; 
			$responce->rows[$i]['PasokAlmt']=$r->PasokAlmt; 
			$responce->rows[$i]['PasokNeg']=$r->PasokNeg;
			
			
			$i++;
		}
		echo json_encode($responce);	
	
	
	
	}
	
	function get_supplier_frommodul(){
	    $bc23dir = $this->config->item('APP_modulbc23');
		//echo  "exec('[spget_data_modulsupplier] @dbpath=''$bc23dir'' ')"; die();
		$qry = $this->db->query("
			BEGIN TRY
			
			 exec('[spget_data_modulsupplier] @dbpath=''$bc23dir'' ')
			
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
			");
		 $rs = $qry->result_array();
		 // $r = $qry->result();		
		 // var_dump($r);die();
		 foreach ($rs as $row){
			 $status = $row['status'];
			 $msg = $row['description'];
		 }  
		 
		 echo json_encode(array('sts' => $status, 'desc' => $msg));
	
	}
	

	
	function update_data_supplier(){
		$this->load->helper('obj2array');
		$this->load->library('arraytoxml');
		$uid = $this->session->userdata('DX_username');
		$postData = (isset($_POST['postData']) && !empty($_POST['postData']))?$_POST['postData']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan or not selected"}');
		
				
		$array = json_decode($postData);
		$array = objectToArray($array);
		
		$postdata = $this->arraytoxml->toXml($array);
		 
		//print_r($postdata); die();
		
		if( strpos($postdata, '&amp;lt;input role="textbox"') ){
			die('{"sts":"ERROR","desc":" Silahkan klik pada kolom Supplier Name, agar data terkunci, kemudian baru klik update"}');				
		}
		
		//echo  " exec('[spu_supplier]  @username=''$uid'', @xmldata=''$postdata'' ') "; die();
		
		$qry_inv_mesin = $this->db->query("
			
			BEGIN TRY
			
			 exec('[spu_supplier]  @username=''$uid'', @xmldata=''$postdata'' ')
			
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
			");
		$rs = $qry_inv_mesin->result_array();
        //$r = $qry_inv_mesin->result();		
		//var_dump($rs);die();
		foreach ($rs as $row){
			$responce = array("sts" => $row['status'], "desc" => $row['description']);
		}  
		echo json_encode($responce);
		
		
	
	
	}
    
    
        
}
    



?>