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

class Credit extends CI_Controller {
	protected $table;

	public function __construct() {
        parent::__construct();
        $this->table = "transaction_group";
        $this->load->helper("array");
        $this->load->helper("az_core");
        $this->load->helper('az_security');
        $this->load->helper('az_azkasir');
        az_check_login();
    }

	public function index(){
		$this->load->library('AZApp');
		$azapp = $this->azapp;
        $crud = $azapp->add_crud();

		$column = array('#', azlang('Date'), azlang('Code'), azlang('Description'), azlang('Total'), azlang('Customer'), 'Status', azlang('Action'));
		$crud->set_column($column);
		$crud->set_id('credit');
		$crud->set_url('app_url+"credit/get"');
		$crud->set_url_edit('app_url+"credit/edit"');
		$crud->set_url_delete('app_url+"credit/delete"');
		$crud->set_url_save('app_url+"credit/save"');
		$crud->set_form('form');
		$crud->set_single_filter(false);

		$datetime1 = $azapp->add_datetime();
		$datetime1->set_id("transaction_date_1");
		$datetime1->set_name("transaction_date_1");
		$datetime1->set_value('01-'.Date("m-Y"));
		$datetime1->set_format("DD-MM-YYYY");
		$datetime1->add_class("con-element-top-filter");
		$datetime1 = $datetime1->render();

		$datetime2 = $azapp->add_datetime();
		$datetime2->set_id("transaction_date_2");
		$datetime2->set_name("transaction_date_2");
		$datetime2->set_value(Date("d-m-Y",  strtotime("last day of this month")));
		$datetime2->set_format("DD-MM-YYYY");
		$datetime2->add_class("con-element-top-filter");
		$datetime2 = $datetime2->render();

		$data_top_filter['date1'] = $datetime1;
		$data_top_filter['date2'] = $datetime2;

		$js = az_add_js('credit/vjs_credit');
		$azapp->add_js($js);


		$crud->set_callback_table_complete("
			jQuery('.total-sum').html(json.total);
		");

		$top_filter = $this->load->view('credit/v_top_filter', $data_top_filter, true);
		$crud->set_top_filter($top_filter);

		$crud->set_btn_add(false);
		
		$v_view = $crud->render();
		$azapp->add_content($v_view);

		$modal = $azapp->add_modal();
		$modal->set_id('payment');
		$modal->set_modal_title('Pembayaran');
		$modal->set_modal("<div class='box-payment'></div>");
		$modal->set_action_modal(array('save-payment' => 'Simpan Pembayaran'));
		$azapp->add_content($modal->render());

		$azapp->add_content("<div id='container_txt_total'><div class='total-sum' style='margin-top:-32px;float:right;font-size:18px;text-align:right'></div></div>");

		$azapp->add_js_ready("jQuery('#container_txt_total').appendTo('.btn-top-table');");

		$data_header['title'] = azlang('TRANSACTION');
		$data_header['subtitle'] = 'PIUTANG';
		$azapp->set_data_header($data_header);

		echo $azapp->render();
	}

	public function get() {
		$this->load->library('AZApp');
		$azapp = $this->azapp;
        $crud = $azapp->add_crud();

    	$crud->set_select('idtransaction_group, transaction_date, code, "" as description, total_final_price, customer.name as customer_name, payment_status');
    	$crud->set_select_table('idtransaction_group, transaction_date, code, description, total_final_price, customer_name, payment_status');
    	$crud->set_order_by("transaction_date desc");
    	$crud->set_table($this->table);
    	$crud->add_where('payment_type = "credit"');
    	$crud->add_join('customer', 'left');
    	$crud->set_sorting("transaction_date, code, description, total_final_price, customer_name, payment_status");
    	$crud->set_id('credit');
    	$crud->set_select_decimal('3');
    	$crud->set_select_align(',,,right');
    	$crud->set_custom_style('custom_style');

		 //echo $crud->get_table();
		//$top_filter = $_REQUEST['topfilter'];
	parse_str($_SERVER['QUERY_STRING'], $str);
        $top_filter = azarr($str, 'topfilter');
    	$arr_filter = array();
    	foreach ($top_filter as $key => $value) {
    		$decode = $this->encrypt->decode($key);
    		$arr_filter[$decode] = $value;
    	}

    	$xdate = explode('~az~', $arr_filter['transaction_date']);
    	$start_date = azarr($xdate, 0);
    	$end_date = azarr($xdate, 1);
    	$payment_status = azarr(explode('~aztpwh~', $arr_filter['payment_status']), 1);

    	$this->db->where('date(transaction_date) >=', Date('Y-m-d', strtotime($start_date)));
    	$this->db->where('date(transaction_date) <=', Date('Y-m-d', strtotime($end_date)));
    	if (strlen($payment_status) > 0) {
    		$this->db->where('payment_status', $payment_status);
    	}
    	$this->db->where('payment_type', 'credit');
    	$this->db->select("coalesce(sum(total_final_price), 0) as total");
    	$data_transaction = $this->db->get('transaction_group');
    	$total = $data_transaction->row()->total;

    	$this->db->where('date(transaction_date) >=', Date('Y-m-d', strtotime($start_date)));
    	$this->db->where('date(transaction_date) <=', Date('Y-m-d', strtotime($end_date)));
    	if (strlen($payment_status) > 0) {
    		$this->db->where('payment_status', $payment_status);
    	}
    	$this->db->select('idtransaction_group');
    	$tg = $this->db->get('transaction_group');

    	$arr_tg = array();
    	foreach ($tg->result() as $key => $value) {
    		$arr_tg[] = $value->idtransaction_group;
    	}

    	$total_bayar = 0;
    	if (count($arr_tg) > 0) {
    		$itg = implode(',', $arr_tg);
    		$total_bayar = $this->db->query('select coalesce(sum(installment_payment), 0) as total from credit_payment where idtransaction_group in ('.$itg.')')->row()->total;


    		// $this->db->where_in('idtransaction_group', $arr_tg);
    		// $this->db->select('coalesce(sum(installment_payment), 0) as total');
    		// $total_bayar = $this->db->get('credit_payment')->row()->total;
    	}

    	$belum = $total - $total_bayar;

    	$ttotal = 'Total Piutang: Rp '.az_thousand_separator($total);
    	$ttotal .= '<br>Total Piutang SUDAH DI BAYAR: Rp '.az_thousand_separator($total_bayar);
    	$ttotal .= '<br>Total Piutang BELUM DI BAYAR: Rp '.az_thousand_separator($belum);

    	$table = $crud->get_table();
    	$table = json_decode($table, true);
    	$arr_total = array('total' => $ttotal);
    	$arr_return = array_merge($table, $arr_total);

		echo json_encode($arr_return);
	}

	function custom_style($key, $value, $data) {
		$id = azarr($data, 'idtransaction_group');
		if ($key == 'description') {
			$this->db->select('product.name, qty, transaction.sell_price');
			$this->db->where('idtransaction_group', $id);
			$this->db->join('product', 'transaction.idproduct = product.idproduct');
			$the = $this->db->get('transaction');

			$txt = '';
			foreach ($the->result() as $key => $value) {
				$txt .= '<table width="100%">';
				$txt .= '	<tr>';
				$txt .= '		<td>'.$value->name.' ['.az_thousand_separator($value->qty).']</td>';
				$txt .= '		<td align="right">'.az_thousand_separator_decimal($value->sell_price).'</td>';
				$txt .= '	</tr>';
				$txt .= '</table>';
			}
			return $txt;
		}
		if ($key == 'payment_status') {
			$lbl = 'warning';
			if ($value == 'LUNAS') {
				$lbl = 'success';
			}

			return "<label class='label label-".$lbl."'>".$value."</label>";
		}

		if ($key == 'action') {
			$btn = '<button class="btn btn-xs btn-info btn-payment" type="button" data-id="'.$id.'">Pembayaran</button>';
			$btn .= '&nbsp;<a href="'.app_url().'credit/print_data/'.az_encode_url($id).'" target="_blank"><button class="btn btn-default btn-print-pay btn-xs" type="button">Cetak</button></a>';
			return $btn;
		}
		
		return $value;
	}

	function get_payment() {
		$id = $this->input->post("id");

		$this->db->where("idtransaction_group", $id);
		$this->db->join('customer', 'transaction_group.idcustomer = customer.idcustomer', 'left');
		$db = $this->db->get('transaction_group');

		$this->db->where('idtransaction_group', $id);
		$payment = $this->db->get('credit_payment');

		$arr_data = array(
			'date' => $db->row()->transaction_date,
			'customer' => $db->row()->name,
			'code' => $db->row()->code,
			'total' => $db->row()->total_final_price,
			'idtransaction_group' => $db->row()->idtransaction_group,
			'payment_status' => $db->row()->payment_status,
			'payment' => $payment
		);

		$rdata['data'] = $arr_data;
		$view = $this->load->view('credit/v_modal', $rdata, true);

		$data = $view;
		$return = array(
			'data' => $data
		);
		echo json_encode($return);
	}

	function pay() {
		$payment_status = $this->input->post("payment_status");
		$installment_payment_date = $this->input->post('installment_payment_date');
		$installment_payment = $this->input->post('installment_payment');
		$idtransaction_group = $this->input->post("idtransaction_group");
		$idcredit_payment = $this->input->post("idcredit_payment");

		$this->load->helper('az_crud');

		$this->db->select('idcredit_payment');
		$this->db->where('idtransaction_group', $idtransaction_group);
		$check = $this->db->get('credit_payment');

		$err_code = 0;
		$err_message = '';

		$total_pay = 0;
		foreach ((array) $installment_payment as $key => $value) {
			$pay = az_crud_number($value);
			$total_pay += $pay;
		}

		$this->db->where("idtransaction_group", $idtransaction_group);
		$trx = $this->db->get('transaction_group');
		if ($trx->num_rows() > 0) {
			$total_credit = $trx->row()->total_final_price;
			if ($total_pay > $total_credit) {
				$err_code++;
				$err_message = 'Jumlah pembayaran melebihi nilai transaksi';
			}
		}

		if ($err_code == 0) {
			$is_delete = array();
			foreach ($check->result() as $key => $value) {
				$del = true;
				foreach ((array) $idcredit_payment as $post_key => $post_value) {
					if ($value->idcredit_payment == $post_value) {
						$del = false;
					}
				}

				if ($del) {
					$is_delete[] = $value->idcredit_payment;
				}
			}

			if (count($is_delete) > 0) {
				$this->db->where_in('idcredit_payment', $is_delete);
				$this->db->delete('credit_payment');
			}
			

			foreach ((array) $installment_payment_date as $key => $value) {
				$arr_pay = array(
					'idtransaction_group' => $idtransaction_group,
					'installment_payment_date' => az_crud_date(azarr($installment_payment_date, $key)),
					'installment_payment' => az_crud_number(azarr($installment_payment, $key))
				);

				az_crud_save(azarr($idcredit_payment, $key), 'credit_payment', $arr_pay);
			}

			$payment_status = 'BELUM LUNAS';
			if ($total_pay == $total_credit) {
				$payment_status = 'LUNAS';
			}

			$stat = array(
				'payment_status' => $payment_status
			);

			$this->db->where('idtransaction_group', $idtransaction_group);
			$this->db->update('transaction_group', $stat);			
		}

		$return = array(
			'err_code' => $err_code,
			'err_message' => $err_message
		);

		echo json_encode($return);

	}

	function print_data($id) {
		$id = az_decode_url($id);

		$err_code = 0;
		$err_message = '';

		if (strlen($id) == 0) {
			$err_code++;
			$err_message = 'ID kosong';
		}

		if ($err_code == 0) {
			$this->db->where("idtransaction_group", $id);
			$this->db->join('customer', 'transaction_group.idcustomer = customer.idcustomer');
			$db = $this->db->get('transaction_group');

			$this->db->where('idtransaction_group', $id);
			$payment = $this->db->get('credit_payment');

			$this->db->where('idtransaction_group', $id);
			$payment = $this->db->get('credit_payment');

			$total_pay = 0;
			foreach ($payment->result() as $key => $value) {
				$total_pay += $value->installment_payment;
			}

			$lack = $db->row()->total_final_price - $total_pay;

			$arr_data = array(
				'date' => $db->row()->transaction_date,
				'customer' => $db->row()->name,
				'code' => $db->row()->code,
				'total' => $db->row()->total_final_price,
				'idtransaction_group' => $db->row()->idtransaction_group,
				'payment_status' => $db->row()->payment_status,
				'payment' => $payment,
				'total_pay' => $total_pay,
				'lack' => $lack
			);

			$rdata['data'] = $arr_data;
			$this->load->view('credit/v_print', $rdata);
		}
	}
	
}
