<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*	
 *	Author 	: Tagor / 15-09-2014	
 *	Revisi 	: Ferry / 01-01-2015 / Insert Branch P/L Account while adding only
 */
 
class Branch_info extends CI_Controller {
    public $menu_id 	= 260;
    public $menu_model 	= 'm_branchinfo';
	
    public function __construct(){
        parent::__construct();
        $this->load->model('m_branchinfo');
		$this->load->model('m_changepassword');
		
		$this->load->model('list/m_compaccountgl');
		$this->load->model('list/m_employee');
		$this->load->model('list/m_inventories');
		$this->load->model('custom/m_custom');
	
		$this->load->helper('message_helper');
		$this->load->helper('status');	
    }
	
    public function index(){
		
		if ($this->session->userdata("login") == TRUE) { 
            $group_menu             = $this->session->userdata('group_menu');
            $arr_group_id           = $this->m_menu->get_menu_by_group($group_menu, $this->menu_id);
            if(!empty($arr_group_id)){
				$data['available_menu'] = array_unique($arr_group_id);
				if(!in_array($this->menu_id, $data['available_menu'])) { 
					redirect(base_url() . 'error', 'refresh');	
				}
				else{
					$group_menu 		= $this->session->userdata('group_menu');
					$data['menu_id'] 	= $this->menu_id;
					$data['menu_model'] = $this->menu_model;
			
					$data['menu_link']  = $this->m_menu->get_menulink($this->menu_id);
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					$this->load->view('v_header');
					$this->load->view('setup/branch/v_branchinfo', $data);	
					$this->load->view('v_footer');	
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
    
    public function city(){
        $all_city = $this->m_branchinfo->get_city();
        echo json_encode($all_city);
    }
	
    public function check_branch(){
        $code		= $this->input->post('number');
        $get_code	= $this->m_branchinfo->get_code($code);
        
        $return_code	= $get_code->BranchCode;
        $data           = array('last_code' => $return_code);
        
        echo json_encode($data);
    }
	
    public function add(){
		if ($this->session->userdata("login") == TRUE) { 
            $group_menu             = $this->session->userdata('group_menu');
            $arr_group_id           = $this->m_menu->get_menu_by_group_add($group_menu, $this->menu_id);
            if(!empty($arr_group_id)){
				$data['available_menu'] = array_unique($arr_group_id);
				if(!in_array($this->menu_id, $data['available_menu'])) { 
					redirect(base_url() . 'error', 'refresh');	
				}
				else{
					$data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
					$data['menu_link'] 	= $this->m_menu->get_menulink($this->menu_id);
					$group_menu 		= $this->session->userdata('group_menu');
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					$data['company'] 	= $this->m_branchinfo->get_company_session($this->session->userdata('company'));
					$data['region']		= $this->m_branchinfo->get_region();
					$data['city'] 		= $this->m_branchinfo->get_city();
					$data['state'] 		= $this->m_branchinfo->get_state();
					$data['country'] 	= $this->m_branchinfo->get_country();
			
					$sess_company		= $this->session->userdata('company');
					$sess_branch		= $this->session->userdata('branch');
			//        $sess_branch_status	= $this->session->userdata('branch_status');
					
					$ceknourut	= $this->m_branchinfo->get_last_branch_code($sess_company,$sess_branch);
				
					if(!empty($ceknourut)){
						foreach($ceknourut as $rows){
							$pecah 		= explode("-", $rows->BranchCode);
			
							if(empty($pecah[0])){
								$CodeCompany = $sess_company;
							}
							else{
								$CodeCompany = $pecah[0];
							}
							
							if(empty($pecah[1])){
								$CodeBranch = $sess_branch;
							}
							else{
								$CodeBranch = $pecah[1];
							}
							
							if(empty($pecah[2])){
								$no_urut = "001";
							}
							else{
								$no_urut = $pecah[2]+1;
							}
			
							$new_nourut = $no_urut;
							$cnim       = strlen($new_nourut);
			
							if($cnim == "1"){ 
							   $no = "00"; 
							}
							 elseif($cnim == "2"){
							   $no = "0";
							}
							 elseif($cnim == "3"){
							   $no = "";
							}
						}
						$data['branch_code'] = $CodeCompany.'-'.$CodeBranch.'-'.$no.$new_nourut;
					}
					else{
						$data['branch_code'] = $sess_company.'-'.$sess_branch.'-001';
					}
					
					$this->load->view('v_header');
					$this->load->view('setup/branch/v_add_branch',$data);	
					$this->load->view('v_footer');	
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
    
    function insert(){
        try{
            $check_pl_status = $this->m_compaccountgl->check_pl_status();

            if($check_pl_status){        
                $company_code           = strtoupper($this->session->userdata('company'));
                $txt_branch_code        = strtoupper($this->input->post('txt_branch_code'));
                $txt_branch_name        = strtoupper($this->input->post('txt_branch_name'));
                $txt_address            = strtoupper($this->input->post('txt_address'));
                $cmb_city               = $this->input->post('cmb_city');
                $cmb_state              = $this->input->post('cmb_state');
                $cmb_country            = $this->input->post('cmb_country');
                $password               = rand(000000,999999);
                $dataSend               = [];
                $check_existing_data = $this->m_branchinfo->check_exsisting_data($txt_branch_code);

                if($check_existing_data){
                    throw new Exception(msg_already_used($txt_branch_code));
                }
                else {
                    //$this->db->trans_begin();

                    $dataSend['data'] = array(
                                'CompanyCode'       => $company_code,
                                'BranchCode'        => $txt_branch_code,
                                'BranchName'        => $txt_branch_name,
                                'BranchAddress'     => $txt_address,
                                'BranchCity'        => $cmb_city,
                                'BranchState'       => $cmb_state,
                                'BranchCountry'     => $cmb_country,
                                'CustomerStatus'    => 0,
                                'BranchStatus'      => 1,
                                'TransStatus'       => 1,
                                'LastUser'          => $this->session->userdata('user')
                            );

                    //Insert Branch Info
                    //$result_insert = $this->m_branchinfo->insert($data);
                    //------------------------------------------------------------------------------------------//
                    
                    $hasil 			= $this->m_compaccountgl->get_comp_pl_account('');
//                    throw new Exception("woooyy  last query = ".$this->db->last_query());
                    $arrayAccountNumber = [];
                    foreach($hasil as $branch_pl_row) {
                        $gl_account_number   = $branch_pl_row->AccountNumber;
                        //Insert Branch P/L Account (jika akun sudah ada maka tidak akan diproses)
                        if(!in_array($gl_account_number,$arrayAccountNumber)){       
                            $dataSend['branch_pl_account'][] = array(
                                'CompanyCode'       => $company_code,
                                'BranchCode'        => $txt_branch_code,
                                'AccountNumber'     => $gl_account_number,
                                'GLSaldoYears'      => date('Y'),
                                'PLStatus'          => 1,
                                'TransStatus'       => 2
                            );
                            //$result_insert = $this->m_compaccountgl->insert($branch_pl_account);	
                        }
                        $arrayAccountNumber[]= $gl_account_number;          
                    }
                    //---------------------------------------------------------------------------------------------------//

                    $dataSend['admin_branch'] = array(
                                        'EmployeeCode'          => "admb-" . $txt_branch_code,
                                        'BranchCode'            => $txt_branch_code,
                                        'DepartmentCode'        => $company_code.'-'.'HO'.'-'.'JKT'.'-'.'006',
                                        'JobTitleCode'          => "ADMIN",
                                        'EmployeeName'          => "Admin Branch",
                                        'EmployeeCity'          => $cmb_city,
                                        'EmployeeState'         => $cmb_state,
                                        'EmployeeCountry'       => $cmb_country,
                                        'HireDate'              => date('Y-m-d'),
                                        'TransStatus'           => 1,
                                        'LastUser'              => $this->session->userdata("username")
                                    );

                    //Insert User Admin into Employee Table
                    //$result_insert = $this->m_employee->insert($admin_branch);
                    //---------------------------------------------------------------------------------------------------//

                    $dataSend['data_user'] = array(
                                    'GroupID'               => 1,
                                    'EmployeeCode'          => "admb-" . $txt_branch_code,
                                    'EmployeePassword' 		=> $password,
                                    'AdminAuthority' 		=> 0,
                                    'LastUser' 				=> $this->session->userdata("username")
                                );

                    //Insert User Login into tbluser Table
                    //$result_insert = $this->m_changepassword->insert($data_user);
                    //---------------------------------------------------------------------------------------------------//

                    $dataSend['data_item'] = array(
                                    'BranchCode'    => $txt_branch_code,
                                    'ItemCode' 		=> 'ITM-MGRS',
                                    'LastUser' 		=> $this->session->userdata("username")
                                );

                    //Insert ITM-MGRS-001 into Inventories Table
                    //$result_insert = $this->m_inventories->insert($data_item);
                    //-------------------------------------------------------------------------------------------------//
                    $rstDataSend = $this->m_branchinfo->insert_array_data_send($dataSend);
                    if($rstDataSend){
                        $result['status']   = true;
                        $result['message'] = "Admin Branch Telah dibuat dengan User Name : admb-" . $txt_branch_code . " dan Password : " . $password;
                    }
                    else{
                        $result['status']   = false;
                        $result['message']  = get_notification('insert',0);
                    }
                }
            }
            else{
                throw new Exception('Company P/L Account tidak ditemukan, silahkan ke menu "Setup >> Preference >> P/L Account"');
            }

            echo json_encode($result);
        }catch (Exception $e){   
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }
    function insert_LAMA(){
        $check_pl_status = $this->m_compaccountgl->check_pl_status();
        
        if($check_pl_status){        
            $company_code           = strtoupper($this->session->userdata('company'));
        
            $txt_branch_code        = strtoupper($this->input->post('txt_branch_code'));
            $txt_branch_name        = strtoupper($this->input->post('txt_branch_name'));
            $txt_address            = strtoupper($this->input->post('txt_address'));
            $cmb_city               = $this->input->post('cmb_city');
            $cmb_state              = $this->input->post('cmb_state');
            $cmb_country            = $this->input->post('cmb_country');
            $password               = rand(000000,999999);

            $check_existing_data = $this->m_branchinfo->check_exsisting_data($txt_branch_code);

            if($check_existing_data){
                $result['status']       = false;
                $result['message']	= msg_already_used($txt_branch_code);
            }
            else {
                $this->db->trans_begin();

                $data = array(
                            'CompanyCode'       => $company_code,
                            'BranchCode'        => $txt_branch_code,
                            'BranchName'        => $txt_branch_name,
                            'BranchAddress'     => $txt_address,
                            'BranchCity'        => $cmb_city,
                            'BranchState'       => $cmb_state,
                            'BranchCountry'     => $cmb_country,
                            'CustomerStatus'    => 0,
                            'BranchStatus'      => 1,
                            'TransStatus'       => 1,
                            'LastUser'          => $this->session->userdata('user')
                        );
                
                //Insert Branch Info
                $result_insert = $this->m_branchinfo->insert($data);
                //------------------------------------------------------------------------------------------//

                $hasil 			= $this->m_compaccountgl->get_comp_pl_account('');
				$akun_number_1 	= '';
				
                foreach($hasil as $branch_pl_row) {
                    $gl_account_number   = $branch_pl_row->AccountNumber;
                    //Insert Branch P/L Account
                    $branch_pl_account = array(
                                            'CompanyCode'       => $company_code,
                                            'BranchCode'        => $txt_branch_code,
                                            'AccountNumber'     => $gl_account_number,
                                            'GLSaldoYears'      => date('Y'),
                                            'PLStatus'          => 1,
											'TransStatus'       => 2
                                            );

                    //Insert Branch P/L Account (jika akun sudah ada maka tidak akan diproses)
					if($akun_number_1 != $gl_account_number){
						$result_insert = $this->m_compaccountgl->insert($branch_pl_account);	
					}
					$akun_number_1 = $gl_account_number;
                }
                //---------------------------------------------------------------------------------------------------//

                $admin_branch = array(
                                    'EmployeeCode'          => "admb-" . $txt_branch_code,
                                    'BranchCode'            => $txt_branch_code,
                                    'DepartmentCode'        => $company_code.'-'.'HO'.'-'.'JKT'.'-'.'006',
                                    'JobTitleCode'          => "ADMIN",
                                    'EmployeeName'          => "Admin Branch",
                                    'EmployeeCity'          => $cmb_city,
                                    'EmployeeState'         => $cmb_state,
                                    'EmployeeCountry'       => $cmb_country,
                                    'HireDate'              => date('Y-m-d'),
                                    'TransStatus'           => 1,
                                    'LastUser'              => $this->session->userdata("username")
                                );

                //Insert User Admin into Employee Table
                $result_insert = $this->m_employee->insert($admin_branch);
                //---------------------------------------------------------------------------------------------------//
                
                $data_user = array(
                                'GroupID'               => 1,
                                'EmployeeCode'          => "admb-" . $txt_branch_code,
                                'EmployeePassword' 		=> $password,
                                'AdminAuthority' 		=> 0,
                                'LastUser' 				=> $this->session->userdata("username")
                            );

                //Insert User Login into tbluser Table
                $result_insert = $this->m_changepassword->insert($data_user);
                //---------------------------------------------------------------------------------------------------//

                $data_item = array(
                                'BranchCode'    => $txt_branch_code,
                                'ItemCode' 		=> 'ITM-MGRS',
                                'LastUser' 		=> $this->session->userdata("username")
                            );

                //Insert ITM-MGRS-001 into Inventories Table
                $result_insert = $this->m_inventories->insert($data_item);
                //-------------------------------------------------------------------------------------------------//
                
				if($this->db->trans_status() == FALSE){
                    $this->db->trans_rollback();
                    $result['status']   = false;
                    $result['message']  = get_notification('insert',0);
                }
                else{
                    $this->db->trans_commit();
                    $result['status']   = true;
                    $result['message'] = "Admin Branch Telah dibuat dengan User Name : admb-" . $txt_branch_code . " dan Password : " . $password;
                }
            }
        }
        else{
            $result['status']   = false;
            $result['message']  = 'Company P/L Account tidak ditemukan, silahkan ke menu "Setup >> Preference >> P/L Account"';            
        }

        echo json_encode($result);
    }
	
    public function edit(){
        if ($this->session->userdata("login") == TRUE) { 
            $group_menu             = $this->session->userdata('group_menu');
            $arr_group_id           = $this->m_menu->get_menu_by_group_edit($group_menu, $this->menu_id);
            if(!empty($arr_group_id)){
				$data['available_menu'] = array_unique($arr_group_id);
				if(!in_array($this->menu_id, $data['available_menu'])) { 
					redirect(base_url() . 'error', 'refresh');	
				}
				else{
					$data['menu_label']         = $this->m_menu->get_menulabel($this->menu_id);
					$data['menu_link']          = $this->m_menu->get_menulink($this->menu_id);
					$group_menu 				= $this->session->userdata('group_menu');
					//panggil model hak akses untuk autoriti
					$data['group_user'] 		= $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					$branch_code                = str_replace($data['menu_link'].'/edit/',"",$this->uri->uri_string());
			
					$data['detail']             = $this->m_branchinfo->get_detail($branch_code);
			
					$data['company']            = $this->m_branchinfo->get_company_session($this->session->userdata('company'));
					$data['region']             = $this->m_branchinfo->get_region();
					$data['city']               = $this->m_branchinfo->get_city();
					$data['state']              = $this->m_branchinfo->get_state();
					$data['country']            = $this->m_branchinfo->get_country();
			
					$this->load->view('v_header');
					$this->load->view('setup/branch/v_edit_branch',$data);	
					$this->load->view('v_footer');	
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    function update(){
        try{
            $txt_branch_code        = $this->input->post('txt_branch_code');
            $txt_address            = $this->input->post('txt_address');
            $cmb_state              = $this->input->post('cmb_state');
            $cmb_country            = $this->input->post('cmb_country');
            $dataSend               = [];
            $dataSend['branch_code']= $txt_branch_code;
            
            $dataSend['data'] = array(
                'BranchAddress'     => strtoupper($txt_address),
                'BranchState'       => $cmb_state,
                'BranchCountry'     => $cmb_country,
                'LastUser'          => $this->session->userdata('user')
            ); 

            //$this->db->trans_begin();
            //$this->m_branchinfo->update($data, $txt_branch_code);
            $rstDataSend = $this->m_branchinfo->update_array_data_send($dataSend);
            if($rstDataSend){
                $result['status']   = true;
                $result['message']	= get_notification('update', 1);
            }
            else{
                $result['status']   = false;
                $result['message']  = get_notification('update',0);
            }
            echo json_encode($result);
        }catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }
	
    function get_status_transaksi(){
        $BranchCode		= $this->input->post('number');
        $all_account_hutang     = $this->m_branchinfo->all_account_hutang();
        $all_account_piutang	= $this->m_branchinfo->all_account_piutang();
        $branch_trans_number	= $this->m_branchinfo->get_trans_status_by_code($BranchCode);
        $get_number		= $this->m_branchinfo->get_all_by_no($BranchCode,$all_account_hutang,$all_account_piutang);
    
        foreach($branch_trans_number as $branch_trans_status){
            $trans_status[] = $branch_trans_status->TransStatus;
        }

        foreach($get_number as $row){
            $balance[]      = $row->balance;
        }

        $data = array(
            'trans_status'  => $trans_status,
            'balance'       => $balance
        );
        echo json_encode($data);
    }

    public function suspend_data(){
        try {
            $id         = $this->input->post('id');
            $dataSend   = [];
            $dataSend['BranchCode'] = $id;
            $dataSend['data']   = array(
                'TransStatus'       => 3,
                'LastUser'		=> $this->session->userdata('user')
            ); 

            $rstDataSend = $this->m_branchinfo->suspend_array_data_send($dataSend);

            if($rstDataSend){
                $result['status'] 	= true;
                $result['message']	= get_notification('suspend',1);
            }else{                
                $result['status'] 	= false;
                $result['message']	= get_notification('suspend',0);
            }
            echo json_encode($result);            
        } catch (Exception $e) {    
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }
	
    function to_preview(){
		$CompanyCode 					= $this->uri->segment(4);
		$BranchCode 					= $this->uri->segment(5);
        // set data
        $data['company_code']   = $CompanyCode;
		$data['branch_code']   = $BranchCode;
		
        $sess_branch_status	= $this->session->userdata('branch_status');
        $data['list'] 		= $this->m_branchinfo->get_all_print($CompanyCode,$BranchCode,$sess_branch_status);

        $this->load->view('v_header');
        $this->load->view('setup/branch/v_print_branch', $data);	
        $this->load->view('v_footer');	
    }
	
	//Function Menampilkan Data Pada Datagrid
	 public function ajax(){
		$page	= ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
		$rows	= ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;
		
		$hasil = array();
		/*===========rows*page tidak boleh melebihi dari jumlah data======= */
		
		/*===========================declar post by find================================================*/
        $Name	= ($this->input->post('BranchName')) ? $this->input->post('BranchName') : '';
		$Addres	= ($this->input->post('BranchAddress')) ? $this->input->post('BranchAddress') : '';
		
		$BranchCode		= ($this->input->post('TransNumber')) ? $this->input->post('TransNumber') : '';
		$TransStatus	= ($this->input->post('TransStatus')) ? $this->input->post('TransStatus') : '';
		/*========================================end==================================================*/
		/*========================jika kondisi tidak sama dengan kosong di find=========================*/
		if($BranchCode != ""){
			$this->db->where('BranchCode', $BranchCode);
		}
		else{
			$this->db->where('BranchCode', $this->session->userdata('branch'));
		}
		
		if($Name != ""){$this->db->like('BranchName', $Name);}
		if($Addres != ""){$this->db->like('BranchAddress', $Addres);}
		if($TransStatus!=''){ 
			$this->db->where_in('TransStatus', $TransStatus);
		}
		else{
			/*
				default adalah 2,6. Finished dan Need Approval
			*/
			$this->db->where_in('TransStatus',array(0,1)); 
		}
		
		/*==========================end=================================================================*/
		
		$count_data = $this->db->count_all_results('am_branch');
		
		$offset 	= $count_data - ($rows * $page);
		if($offset > 0){
			$rows = $rows;
		}
		else if($offset < 0){
			$rows = $count_data - ($rows*($page-1));
		}
		/*========================end=======================================*/
		$result = $this->m_branchinfo->get_branch_info();
		for($i=0; $i<=($rows-1); $i++){
			$TransStatus = get_status_master($result[$i]->TransStatus);

            $hasil[] = array(
					'CompanyName' 		=> $result[$i]->CompanyName,
                    'TransNumber' 		=> $result[$i]->BranchCode,
					'BranchName' 		=> $result[$i]->BranchName,
                    'BranchAddress'     => $result[$i]->BranchAddress,
                    'CityName'      	=> $result[$i]->CityName,
                    'StateName'      	=> $result[$i]->StateName,
                    'TransStatus'       => $TransStatus
            ); 
		}
		
		if($hasil == ""){
			$result = array();
			echo json_encode($result);
		}
		else{
			$result = array();
			$result['total'] = $count_data;
			$result['rows'] = $hasil;
			echo json_encode($result);
		}
    }
	
    	    
    public function trans_rollback($modus) {
        $this->db->trans_rollback();
        $result['status']   = false;
        $result['message']  = get_notification_transaksi($this->name, $modus, 0);
        
        echo json_encode($result);
        die();
    }    
}