<?php 
/*
Fungsi : Controller untuk petty cash operational
*/

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

class Cabang_po_credit extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	
/*-------------Inisialisasi variabel--------------*/ 
	
	//Menu ID utk keperluan otorisasi
	
	var $menu_post_po_finance  = 106;
	

/*-------------Inisialisasi variabel--------------*/ 	

/*------------Fungsi lokal------------------------*/
	
//Cek valid amount
public function valid_amount($amount)
{
	if($amount > $this->fungsi->get_pc_bal_op($this->session->userdata('idcab')))
	{
		//$this->form_validation->set_message('valid_amount', 'Error, petty cash operational balances is insufficient');
		return FALSE;
	}
	else
	{
		
		return TRUE;
	}
	
}

/*------------Fungsi local------------------------*/	
	function __construct()
	{
		parent::__construct();
		
		$this->load->model('branch/branch_model', '', TRUE);
		$this->load->model('finance/fin_model', '', TRUE);
		$this->load->model('admin/admin_model', '', TRUE);
		$this->fungsi->check_login();
	}
	
	
	public function index()
	{	
		$this->post_po_fin();		
	}
//Cancel rembuirsement
function cancel_rmb()
{
	
	//Check otorisasi
	$this->fungsi->trans_auth($this->session->userdata('view'));
	
	//Otorisasi menu
	$this->fungsi->menu_auth($this->menu_post_to_finance);
	
	/* Setting Parameter Untuk Paging */
		$uri_segment = 4;
		$offset =    $this->uri->segment($uri_segment);
		
		$rmb = $this->branch_model->get_rmb_header_pending($this->session->userdata('idcab'),$this->config->item('paging_limit'), $offset)->result();
		$num_rows = $this->branch_model->get_rmb_header_pending_count($this->session->userdata('idcab'));
		
		$config['base_url'] = site_url('branch/branch_bpkk/cancel_rmb/');
	
		if ($num_rows > 0) // Jika query menghasilkan data
		{
					// Membuat pagination			
					$config['total_rows'] = $num_rows;
					$config['per_page'] = $this->config->item('paging_limit');
					$config['uri_segment'] = $uri_segment;
					$this->pagination->initialize($config);
					$data['pagination'] = $this->pagination->create_links();
					$i = 0 + $offset;
					
					$tmpl = array( 'table_open'    => '<table border="0" cellpadding="1" cellspacing="1" id="list">',
								  'row_alt_start'  => '<tr class="zebra">',
								  'row_alt_end'    => '</tr>'
								  );
					$this->table->set_template($tmpl);
		
					// Set heading untuk tabel
					$this->table->set_empty("&nbsp;");
					$this->table->set_heading('No. RMB', 'Branch','Total Amount','Add by','Add date','Options');
					
					$atts = array(
              'width'      => '100',
              'height'     => '100',
              'scrollbars' => 'yes',
              'status'     => 'yes',
              'resizable'  => 'yes',
              'screenx'    => '0',
              'screeny'    => '0'
            );
					
					foreach ($rmb  as $rmbs)
					{	
						$this->table->add_row($rmbs->normbform, $rmbs->cabname , $this->fungsi->format_idr($rmbs->total), $rmbs->addby, $rmbs->adddate,anchor('branch/branch_bpkk/cancel_rmb_prev/'.$rmbs->idcab.'/'.$rmbs->normb.'/'.$rmbs->year,'Cancel',array('class' => 'delete')).' '.anchor_popup('branch/branch_bpkk/print_rmb_popup/'.$rmbs->idcab.'/'.$rmbs->normb.'/'.$rmbs->year,'Print',array('class' => 'print',$atts),$atts));	
					}
					
					$data['table'] = $this->table->generate();
		}		
		else
		{
			
			$data['message'] = 'No data';
			
		}
		
		$data['menu_path'] = 'BRANCH > BPKK > CANCEL REMBURSEMENT';
		$this->load->view('branch/branch_cancel_rmb', $data);
	
}

//Cetak rembuirsement popup
function print_rmb_popup()
{
	
	//Check otorisasi
	$this->fungsi->trans_auth($this->session->userdata('view'));	
	
	//Get data RMB HEADER by ID CAB, No. RMB & year
	$query_rmb_header = $this->branch_model->get_rmbheader_byidcabnoyear($this->uri->segment(4),$this->uri->segment(5),$this->uri->segment(6));
	foreach ($query_rmb_header->result() as $row_rmb_header)
		{
			$data['txt_normbform'] = $row_rmb_header->normbform;
			$data['txt_adddate'] = date("d.m.Y",   strtotime($row_rmb_header->adddate));	
			$data['txt_addby'] = $row_rmb_header->addby;
			if($row_rmb_header->chdate == '0000-00-00 00:00:00')
			{
				$data['txt_chdate'] = '';	
			}
			else
			{
				$data['txt_chdate'] = date("d.m.Y",   strtotime($row_rmb_header->chdate));	
			}
			
			$data['tables']='';
			$query_bpkk_header = $this->fin_model->get_detail_bpkk_header($this->uri->segment(4),$this->uri->segment(5),$this->uri->segment(6));
			foreach ($query_bpkk_header->result() as $row_bpkk_header)
			{
						$data['tables'].='<tr>
										  <td width="622" align="left">'.$row_bpkk_header->nobpkkform.'</td>
										  <td width="230" align="right">'.$this->fungsi->format_idr($row_bpkk_header->total).'</td>
											</tr>';
			}
			
			
			$data['txt_total'] = $row_rmb_header->total;
			$data['txt_terbilang'] = $this->fungsi->terbilang($row_rmb_header->total).' RUPIAH';
		}
		
	$this->load->view('popup/popup_rmb', $data);
}

function cancel_rmb_prev()
{
	//Check otorisasi
	$this->fungsi->trans_auth($this->session->userdata('cancel'));
	
	//Get data RMB HEADER by ID CAB, No. RMB & year
	$query_rmb_header = $this->branch_model->get_rmbheader_byidcabnoyear($this->uri->segment(4),$this->uri->segment(5),$this->uri->segment(6));
	foreach ($query_rmb_header->result() as $row_rmb_header)
		{
			$data['txt_normbform'] = $row_rmb_header->normbform;
			$data['txt_adddate'] = date("d.m.Y",   strtotime($row_rmb_header->adddate));	
			$data['txt_addby'] = $row_rmb_header->addby;
			if($row_rmb_header->chdate == '0000-00-00 00:00:00')
			{
				$data['txt_chdate'] = '';	
			}
			else
			{
				$data['txt_chdate'] = date("d.m.Y",   strtotime($row_rmb_header->chdate));	
			}
			
			$data['txt_total'] = $row_rmb_header->total;
			$data['txt_terbilang'] = $this->fungsi->terbilang($row_rmb_header->total).' RUPIAH';
		}
		
			//Get BPKK Header
	$query_bpkk_header = $this->fin_model->get_detail_bpkk_header($row_rmb_header->idcab,$row_rmb_header->normb, $row_rmb_header->year);
	$data['tables'] = '';
	$totalbpkk = 0;
	$bg=0;
	foreach ($query_bpkk_header->result() as $row_bpkk_header)
		{	
		$totalbpkk = $row_bpkk_header->total + $totalbpkk;
			if($bg==0)
					{
					$data['tables'].="<tr style=background-color:#;>";
					$bg++;
					}
					else
					{
					$data['tables'].="<tr style=background-color:#eeeeee;>";
					$bg--;
					}
					$data['tables'] .= '
										  <td align="center">'.$row_bpkk_header->nobpkkform.'<input type="hidden" name="item[]" id="item[]"  value="'.$row_bpkk_header->idcab.'|'.$row_bpkk_header->nobpkk.'|'.$row_bpkk_header->year.'"/></td>
										  <td align="right">'.$this->fungsi->format_idr($row_bpkk_header->total).'</td>
										  <td align="center">'.anchor_popup('branch/branch_bpkk/print_bpkk_popup/'.$row_bpkk_header->idcab.'/'.$row_bpkk_header->nobpkk.'/'.$row_bpkk_header->year,'Preview',array('class' => 'print')).'</td>
										</tr>';
		}
	$data['totalbpkk'] = $totalbpkk;
		
		$data['menu_path'] = 'BRANCH > BPKK > CANCEL REIMBURSEMENT';
		$data['link'] = array('link_back' => anchor('branch/branch_bpkk/cancel_rmb','Back', array('class' => 'back')));
		$data['form_action']= site_url('branch/branch_bpkk/cancel_rmb_proc/'.$this->uri->segment(4).'/'.$this->uri->segment(5).'/'.$this->uri->segment(6));
		$this->load->view('branch/branch_cancel_rmb_form', $data);	
	
}

function cancel_rmb_proc()
{
	/* Set validasi */
		$config = array(
               array(
                     'field'   => 'txt_desc',
                     'label'   => 'Cancel Reason',
                     'rules'   => 'required'
                  )
            );
		$this->form_validation->set_rules($config); 
		
	if ($this->form_validation->run() == TRUE)
			{
				
				foreach($this->input->post('item') as $val)
				{
				
				$rmb = explode("|", $val);
				//Update BPKK Header
				$bpkkheader = array( 'status'	 => 0,
									'chby'		 => $this->session->userdata('uid'),
									'chdate' 	 => date( 'Y-m-d H:i:s'),
								);
				$this->branch_model->update_bpkkheader($rmb[0],$rmb[1],$rmb[2],$bpkkheader);
			}
			
				$rmbheader = array( 
								'status' => 1,
								'canby' => $this->session->userdata('uid'),
								'candate' => date( 'Y-m-d H:i:s'),
								'candesc' => $this->input->post('txt_desc'),
								);
								
				$this->branch_model->update_rmbheader($this->uri->segment(4),$this->uri->segment(5),$this->uri->segment(6),$rmbheader);		
				
				$this->session->set_flashdata('message_ok', 'Data cancelled');
	  			redirect('branch/branch_bpkk/print_bpkk/');						
			}
	else
			{
				$this->cancel_rmb_prev();
				
			}
	
}
//Posting BPKK to finance
function post_po_fin()
{
	$data['prev'] = 0;
	//Check otorisasi
	$this->fungsi->trans_auth($this->session->userdata('view'));
	
	//Otorisasi menu
	$this->fungsi->menu_auth($this->menu_post_po_finance);
	
	/* Setting Parameter Untuk Paging */
		$uri_segment = 4;
		$offset =    $this->uri->segment($uri_segment);
		
		$bpkk = $this->branch_model->get_list_bpkk($this->session->userdata('idcab'),$this->config->item('paging_limit'), $offset)->result();
		$num_rows = $this->branch_model->get_list_bpkk_count($this->session->userdata('idcab'));
		
		$config['base_url'] = site_url('branch/branch_bpkk/post_po_fin/');
	
		if ($num_rows > 0) // Jika query menghasilkan data
		{
					// Membuat pagination			
					$config['total_rows'] = $num_rows;
					$config['per_page'] = $this->config->item('paging_limit');
					$config['uri_segment'] = $uri_segment;
					$this->pagination->initialize($config);
					$data['pagination'] = $this->pagination->create_links();
					$i = 0 + $offset;
					
					$tmpl = array( 'table_open'    => '<table border="0" cellpadding="1" cellspacing="1" id="list">',
								  'row_alt_start'  => '<tr class="zebra">',
								  'row_alt_end'    => '</tr>'
								  );
					$this->table->set_template($tmpl);
		
					// Set heading untuk tabel
					$this->table->set_empty("&nbsp;");
					$this->table->set_heading('<input type="checkbox" onclick="toggleChecked(this.checked)">','No. BPKK', 'Branch','Type','Total Amount','Add by','Add date','Options');
					
					$atts = array(
              'width'      => '100',
              'height'     => '100',
              'scrollbars' => 'yes',
              'status'     => 'yes',
              'resizable'  => 'yes',
              'screenx'    => '0',
              'screeny'    => '0'
            );
					
					foreach ($bpkk  as $bpkks)
					{	
						$this->table->add_row('<input type="checkbox" name="checkbox[]" id="checkbox[]" class="checkbox"  value="'.$bpkks->idcab.'|'.$bpkks->nobpkk.'|'.$bpkks->year.'|'.$bpkks->idpcoprtyp.'"/>',$bpkks->nobpkkform, $bpkks->cabname , $bpkks->desc,$this->fungsi->format_idr($bpkks->total), $bpkks->addby, $bpkks->adddate,anchor_popup('branch/branch_bpkk/print_bpkk_popup/'.$bpkks->idcab.'/'.$bpkks->nobpkk.'/'.$bpkks->year,'Preview',array('class' => 'print',$atts),$atts));	
					}
					
					$data['table'] = $this->table->generate();
		}		
		else
		{
			
			$data['message'] = 'No data';
			
		}
		
		$data['menu_path'] = 'BRANCH > OIL PURCHASE > CREATE PO CREDIT GLOBAL';
		$data['form_action']= site_url('branch/branch_bpkk/post_to_fin_prev');
		$this->load->view('branch/branch_po_global', $data);
}

function post_to_fin_prev()
{
	$data['prev'] = 1;
	$config = array(
               array(
                     'field'   => 'checkbox[]',
                     'label'   => 'Data BPKK',
                     'rules'   => 'required'
                  )
            );
		$this->form_validation->set_rules($config); 
		
	if ($this->form_validation->run() == TRUE)
			{	
				$data['tables'] = '';
				$total = 0;
				$bg=0;
				$count_oa = 0;
				$count_op = 0;
				foreach($this->input->post('checkbox') as $val)
				{	
					$bpkk = explode("|", $val);
					
					if($bpkk[3] == 2)
					{
						$count_oa = $count_oa + 1;
					}
					else
					{
						$count_op = $count_op + 1;
					}
					
					
					$bpkks = $this->branch_model->get_bpkkheader_byidcabnoyear($bpkk[0],$bpkk[1],$bpkk[2])->result();
					foreach ($bpkks as $bpkkss);
					$cab = $this->admin_model->get_cab_detail($bpkk[0])->result();
					foreach ($cab as $cabs);
					$total = $total + $bpkkss->total;
					if($bg==0)
					{
					$data['tables'].="<tr style=background-color:#;>";
					$bg++;
					}
					else
					{
					$data['tables'].="<tr style=background-color:#eeeeee;>";
					$bg--;
					}
					$data['tables'] .= '
										  <td align="center">'.$bpkkss->nobpkkform.'<input type="hidden" name="item[]" id="item[]"  value="'.$bpkkss->idcab.'|'.$bpkkss->nobpkk.'|'.$bpkkss->year.'"/></td>
										  <td align="center">'.$cabs->cabname.'</td>
										  <td align="right">'.$this->fungsi->format_idr($bpkkss->total).'</td>
										  <td align="center">'.anchor_popup('branch/branch_bpkk/print_bpkk_popup/'.$bpkkss->idcab.'/'.$bpkkss->nobpkk.'/'.$bpkkss->year,'Preview',array('class' => 'print')).'</td>
										</tr>';
					//echo $bpkkss->idcab.' '.$bpkkss->nobpkk;
					//echo '<br>';
					//get_bpkkheader_byidcabnoyear
					//echo $pieces[0].','.$pieces[1]
				}
				//echo $count_oa;
				//echo $count_op;
				if($count_oa >= 1 && $count_op >= 1 )
			{
				$data['submit'] ='<font color="#FF0000"><b>Only 1 Ongkos angkut item permitted to create rembuirsement!</b></font>';	
			}
			else
			{
				$data['submit'] = '<input type="submit" name="button2" id="button2" value="Submit" class="button" />';
			}
			
			if($count_op > 5)
				{
					$data['submit'] ='<font color="#FF0000"><b>BPPK items restricted to 5 items only!</b></font>';	
				}
				
				$data['total'] = $total;
				$data['menu_path'] = 'BRANCH > BPKK > POSTING TO FINANCE > PREVIEW DATA';
				$data['form_action']= site_url('branch/branch_bpkk/post_to_fin_proc/');
				$this->load->view('branch/branch_bpkk_posttofin', $data);
			}
	else
			{
				
				$this->post_to_fin();
			}
}

function post_to_fin_proc()
{
	
	/*Get RMB counter*/
	$count = array();
	$count = $this->fungsi->get_no_count($this->session->userdata('idcab'), 'RMB');
	$normbform = $count[0];
	$normb = $count[1];
	
	/*Insert RMB Header*/
	$rmbheader = array( 		'idcab'		=> $this->session->userdata('idcab'),
								'normbform' => $normbform,
								'normb'	 	=> $normb,
								'year'		 => date('Y'),
								'total' 	 =>  $this->input->post('total'),
								'addby'		 => $this->session->userdata('uid'),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								);
	/*Insert RMB Detail*/
	$rmbdetail = array();
	
	foreach($this->input->post('item') as $val)
			{
				
				$rmb = explode("|", $val);
				$rmbdetail[] = array( 			'idcab'	 => $this->session->userdata('idcab'),
												'normb'	 	=> $normb,
												'nobpkk'	 => $rmb[1],
												'year'	 => $rmb[2],
												);
				//Update BPKK Header
				$bpkkheader = array( 'status'		=> 2,
									'chby'		 => $this->session->userdata('uid'),
									'chdate' 	 => date( 'Y-m-d H:i:s'),
								);
				$this->branch_model->update_bpkkheader($this->session->userdata('idcab'), $rmb[1], $rmb[2], $bpkkheader);
			}
		
		
		$this->branch_model->add_rmb_header($rmbheader);	
		$this->branch_model->add_rmb_detail($rmbdetail);	
					
		//Email notification to finance
		
		$this->session->set_flashdata('message_ok', 'Data saved, No. Rembuirse : '.$normbform);
		redirect('branch/branch_bpkk/post_to_fin');
}

}