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

class Sales_transaction extends CI_Controller {
	public function __construct() {
        parent::__construct();

        $this->load->helper('az_auth');
        az_check_auth('transactions');
        $this->table = 'transaction_group';
        $this->controller = 'sales_transaction';
        $this->load->helper('az_crud');
        $this->load->helper('az_config');
    }

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

    	$crud = $app->add_crud();

		$crud->set_column(array('#', azlang('Outlet'), azlang('Status'), azlang('Invoice Code'),  azlang('Customer'), azlang('Date'), 'Tgl Selesai', 'Hal Pembayaran', azlang('Total'), 'Posisi Stok', azlang('Action')));
		$crud->set_id($this->controller);
		$crud->set_default_url(true);
		$crud->set_single_filter(false);
		// $crud->set_width(',,,,,,,,,,230px');

		$datetime1 = $app->add_datetime();
		$datetime1->set_id("date_1");
		$datetime1->set_name("date_1");
		$datetime1->set_value(Date("d-m-Y", strtotime('-7 day')));
		$datetime1->set_format("DD-MM-YYYY");
		if ($this->session->userdata('role_name') == 'cashier') {
			$datetime1->set_min_date(Date('Y-m-d', strtotime('-7 day')));
		}
		$datetime1->add_class("con-element-top-filter");
		$datetime1 = $datetime1->render();

		$datetime2 = $app->add_datetime();
		$datetime2->set_id("date_2");
		$datetime2->set_name("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();

		$btn = "<button class='btn btn-default' type='button' id='btn_print_report'><i class='fa fa-print'></i> ".azlang('Print')."</button>";
		// $crud->set_top_filter_btn($btn);


        $outlet = az_select_outlet('outlet', 'transaction_group');

        $data['datetime1'] = $datetime1;
        $data['datetime2'] = $datetime2;
        $data['outlet'] = $outlet;

        $callback = "jQuery('#txt_total_price').text(json.total);";
		$crud->set_callback_table_complete($callback);

        $v_filter = $this->load->view("sales_transaction/v_sales_transaction_top_filter", $data, true);

        if (!aznav('role_add_transaction')) {
        	// $crud->set_btn_add(false);
        }

        if (aznav('role_export_transaction')) {
			$btn = "&nbsp;<button class='btn btn-success btn-export-excel' type='button'><i class='fa fa-file-excel-o'></i> Export</button>";
			$crud->set_top_filter_btn($btn);
        }

        $crud->set_top_filter($v_filter);
		$crud = $crud->render();
		$app->add_content($crud);	

		$idrole = $this->session->userdata('idrole');
		if ($idrole != '2') {
			$app->add_content("<div id='txt_total_price' style='text-align:right;font-size:20px;'>Total Rp 0</div>");			
		}

		$btn_modal = array(
			'print-qr-baju' => "<i class='fa fa-print'></i> Cetak QR Baju",
			'print-marker' => "<i class='fa fa-print'></i> Cetak Marker",
			'print-marker-old' => "<i class='fa fa-print'></i> Cetak Marker Lama",
			'print-marker-point' => "<i class='fa fa-print'></i> Cetak Marker Point",
			'print-invoice' => "<i class='fa fa-print'></i> Cetak Bill Pelanggan",
			'print-invoice-old' => "<i class='fa fa-print'></i> Cetak Bill Pelanggan (Lama)",
			'print-invoice-production' => "<i class='fa fa-print'></i> Cetak Bill Produksi",
		);

		$modal_detail = $app->add_modal();
		$modal_detail->set_id('detail');
		$modal_detail->set_modal_title(azlang('Detail'));
		$modal_detail->set_modal('');
		$modal_detail->set_action_modal($btn_modal);
		$app->add_content($modal_detail->render());

		$pay_date = $app->add_datetime();
		$pay_date->set_id("pay_date");
		$pay_date->set_name("pay_date");
		$pay_date->add_class('x-focus');
		$pay_date = $pay_date->render();
		$data_process['pay_date'] = $pay_date;
		$v_modal_process = $this->load->view('sales_transaction/v_modal_process', $data_process, true);

		$modal_process = $app->add_modal();
		$modal_process->set_id('process');
		$modal_process->set_modal_title(azlang('Process'));
		$modal_process->set_modal($v_modal_process);
		$modal_process->set_action_modal($btn_modal);
		$modal_process->set_action_modal(array('process' => azlang('Save')));
		$app->add_content($modal_process->render());

		$this->load->helper('az_core');
		$js = az_add_js('sales_transaction/vjs_list_sales_transaction');
		$app->add_js($js);

    	$data_header['title'] = 'History Transaksi';
		$data_header['breadcrumb'] = array('transactions', 'sales_transaction');
		$app->set_data_header($data_header);
    	echo $app->render();
    }

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

		$idrole = $this->session->userdata('idrole');

		if ($idrole == '2') {
			$crud->add_where('transaction_group_status != "SELESAI"');
		}

		$crud->set_select("idtransaction_group, outlet_name, dstb_status, code, customer_name, date_format(date, '%d-%m-%Y %H:%i:%s') as date, date_format(duedate, '%d-%m-%Y %H:%i:%s') as duedate, payment_status, grand_total_final, stock_position");
		$crud->set_select_table("idtransaction_group, outlet_name, dstb_status, code, customer_name, date, duedate, payment_status, grand_total_final, stock_position");
		$crud->set_sorting('outlet_name, dstb_status, code, customer_name, date, duedate, payment_status, grand_total_final, stock_position');
		$crud->set_id($this->controller);
		$sess_idoutlet = $this->session->userdata('idoutlet');
		if (strlen($sess_idoutlet) > 0) {
			$crud->add_where('transaction_group.idoutlet = '. $sess_idoutlet);
		}
		$crud->set_group_by('transaction_group.idtransaction_group');
		$crud->add_join('customer', 'left');
		$crud->add_join('outlet');
		$crud->set_select_align(',,,,,,,right');
		$crud->set_select_decimal('7');
		$crud->add_where("transaction_group.status > 0");
		$crud->set_table($this->table);
		$crud->set_order_by("transaction_group.created desc");
		$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['date']);
    	$start_date = azarr($xdate, 0);
    	$end_date = azarr($xdate, 1);
    	$idoutlet = azarr($arr_filter, 'transaction_group.idoutlet');
    	$status = $arr_filter['dstb_status'];
    	$process_status = $arr_filter['process_status'];
    	$filter_code = $arr_filter['transaction_group.code'];
    	
    	$idcustomer = $arr_filter['transaction_group.idcustomer'];
    	$xstatus = explode('~aztpwh~', $status);
    	$xprocess_status = explode('~aztpwh~', $process_status);
    	$xcustomer = explode('~aztpwh~', $idcustomer);


    	if ($idrole == '2') {
			$crud->add_where('transaction_group_status != "SELESAI"');
		}

    	$this->db->where('date(date) >=', Date('Y-m-d', strtotime($start_date)));
    	$this->db->where('date(date) <=', Date('Y-m-d', strtotime($end_date)));
    	if (strlen($idoutlet) > 0) {
    		$this->db->where('transaction_group.idoutlet', $idoutlet);
    	}
    	if (strlen($filter_code) > 0) {
    		$this->db->like('transaction_group.code', $filter_code);
    	}
    	if (strlen($sess_idoutlet) > 0) {
    		$this->db->where('transaction_group.idoutlet', $sess_idoutlet);
    	}
    	// if (strlen($idcustomer) > 0) {
    	// 	$this->db->where('transaction_group.idcustomer', $idcustomer);
    	// }
    	if (count($xcustomer) > 1) {
    		if (strlen(azarr($xcustomer, 1)) > 0) {
    			$this->db->where('transaction_group.idcustomer', azarr($xcustomer, 1));
    		}
    	}
    	if (count($xstatus) > 1) {
    		if (strlen(azarr($xstatus, 1)) > 0) {
    			$this->db->where('dstb_status', azarr($xstatus, 1));
    		}
    	}
    	if (count($xprocess_status) > 1) {
    		if (strlen(azarr($xprocess_status, 1)) > 0) {
    			$this->db->where('process_status', azarr($xprocess_status, 1));
    		}
    	}
    	$this->db->select("sum(grand_total_final) as total");
    	$this->db->where('transaction_group.status', 1);
    	$data_transaction = $this->db->get('transaction_group');
    	$total = $data_transaction->row()->total;

    	$this->load->helper('az_core');
    	$total = azlang('Total').': Rp '.az_thousand_separator_decimal($total);

    	if ($idrole == '2') { 
    		$total = '';
    	}

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

		echo json_encode($arr_return);
	}

	function custom_style($key, $value, $data) {
		if ($key == 'dstb_status') {
			switch ($value) {
				case 'DIJEMPUT':
					$lbl = 'info';
					break;
				case 'DIPROSES':
					$lbl = 'primary';
					break;
				case 'DIANTAR':
					$lbl = 'warning';
					break;
				case 'END PROCESS':
					$lbl = 'success';
					break;				
				default:
					$lbl = 'default';
					break;
			}
			return "<label class='label label-".$lbl."'>".azlang($value)."</label>";
		}

		$idtransaction_group = azarr($data, 'idtransaction_group');
		if ($key == 'action') {
			$code = azarr($data, 'code');
			$btn = "<button data-code='".$code."' class='btn btn-info btn-detail btn-xs' type='button'><i class='fa fa-file-o'></i> ".azlang('Detail')."</button>";


			$btn_edit = '<button class="btn btn-default btn-xs btn-edit-sales_transaction" data_id="'.$idtransaction_group.'"><span class="glyphicon glyphicon-pencil"></span> '.azlang('Edit').'</button>';

			$btn_process = "";
			if (aznav('role_process_transaction')) {
				// $btn_process = '<button class="btn btn-warning btn-xs btn-process-sales_transaction" data_id="'.$idtransaction_group.'"><span class="glyphicon glyphicon-refresh"></span> '.azlang('Process').'</button>';
			}
			if (!aznav('role_edit_transaction')) {
			}
			$btn_edit = '';
			$btn_delete = '<button class="btn btn-danger btn-xs btn-delete-sales_transaction" data_id="'.$idtransaction_group.'"><span class="glyphicon glyphicon-remove"></span> '.azlang('Delete').'</button>';
			if (!aznav('role_delete_transaction')) {
				$btn_delete = '';
			}

			return $btn.$btn_process.$btn_edit.$btn_delete;
		}
		return $value;
	}

	function add() {
		if (!aznav('role_add_transaction')) {
			// redirect(app_url());
		}
		$this->edit();
	}

    function edit($id = '') {
    	if (strlen($id) > 0) {
    		if (!aznav('role_edit_transaction')) {
				// redirect(app_url());
			}
    	}
		$this->load->helper('az_core');
		$this->load->library('AZApp');
		$app = $this->azapp;

		$date = $app->add_datetime();
		$date->set_id('date');
		$date->set_value(Date('d-m-Y H:i:s'));
		$date->set_name('date');
		$data['date'] = $date->render();

		$cfg_due = az_get_config('duedate');
		$due = Date('d-m-Y', strtotime('+ '.$cfg_due.' day')).' 17:00:00';

		$duedate = $app->add_datetime();
		$duedate->set_id('duedate');
		$duedate->set_name('duedate');
		$duedate->set_value($due);
		$data['duedate'] = $duedate->render();

		$pay_date = $app->add_datetime();
		$pay_date->set_id("pay_date");
		$pay_date->set_name("pay_date");
		$pay_date->add_class('x-focus');
		$pay_date = $pay_date->render();
		$data['pay_date'] = $pay_date;

		$this->load->library('Laundry');
		$v_modal = $this->laundry->get_product();
		$modal = $app->add_modal();
		$modal->set_id('product');
		$modal->set_modal_title(azlang('Product'));
		$modal->set_modal("<div class='table-responsive'>".$v_modal."</div>");
		$modal = $modal->render();

		$app->add_content($modal);

		$this->db->where('status', 1);
		$data['customer_category'] = $this->db->get('customer_category');

		$date = $app->add_datetime();
		$date->set_id('birthday');
		$date->set_name('birthday');
		$date->set_format('DD-MM-YYYY');
		$data['birthday'] = $date->render();

		$v_customer = $this->load->view('sales_transaction/v_customer', $data, true);
		$modal_customer = $app->add_modal();
		$modal_customer->set_id('customer');
		$modal_customer->set_action_modal(array('save_customer' => azlang('Save')));
		$modal_customer->set_modal_title(azlang('Add Customer'));
		$modal_customer->set_modal($v_customer);
		$modal_customer = $modal_customer->render();

		$app->add_content($modal_customer);

		$this->db->where('status', 1);
		$this->db->order_by('field(payment_type_name, "CASH")');
		$pdata['payment_type'] = $this->db->get('payment_type');

		$v_payment = $this->load->view('sales_transaction/v_payment', $pdata, true);
		$modal_payment = $app->add_modal();
		$modal_payment->set_id('payment');
		$modal_payment->set_action_modal(array('save-payment' => 'Simpan', 'save-payment-print' => 'Simpan dan Cetak'));
		$modal_payment->set_modal_title('Pembayaran');
		$modal_payment->set_modal($v_payment);
		$modal_payment = $modal_payment->render();

		$app->add_content($modal_payment);

		$this->db->where('status', 1);
		$data_tmp['colour'] = $this->db->get('colour');

		$this->db->where('status', 1);
		$data_tmp['hue'] = $this->db->get('hue');

		$this->db->where('status', 1);
		$data_tmp['spot'] = $this->db->get('spot');

		$this->db->where('status', 1);
		$data_tmp_add['additional_cost'] = $this->db->get('additional_cost');

		$data['tmp_transaction'] = $this->load->view('sales_transaction/v_tmp_transaction', $data_tmp, true);
		$data['tmp_additional_cost'] = $this->load->view('sales_transaction/v_tmp_additional_cost', $data_tmp_add, true);

		$v_item = $this->load->view('sales_transaction/v_item', $data_tmp, true);
		$modal = $app->add_modal();
		$modal->set_id('create_item');
		$modal->set_action_modal(array('save_item' => 'Simpan'));
		$modal->set_modal_title('Buat Barang Baru');
		$modal->set_modal($v_item);
		$modal = $modal->render();

		$app->add_content($modal);

		$view = $this->load->view('sales_transaction/v_sales_transaction', $data, true);
		$app->add_content($view);

		$js = az_add_js('sales_transaction/vjs_sales_transaction');
		$app->add_js($js);

		$app->add_content("<div class='container-scanner hide'><button class='btn btn-danger btn-sm btn-close-scanner' type='button'>".azlang('Close')."</button><br><video class='scanner' id='scanner'></video></div>");
		$js = az_add_js('sales_transaction/vjs_scanner');
		$app->add_js($js);

		$title = azlang('Add Sales Transaction');
		if (strlen($id) > 0) {
			$title = azlang('Edit Sales Transaction');
		}

		$data_header['title'] = $title;
		$data_header['breadcrumb'] = array('transaction', 'sales_transaction');
		$app->set_data_header($data_header);
		echo $app->render();
	}

	public function save($type = ''){
		$data = array();
		$data_post = $this->input->post();
		$idpost = azarr($data_post, 'id'.$this->table);
		$data['sMessage'] = '';
		$this->load->library('form_validation');

		$this->form_validation->set_rules('idoutlet', azlang('Outlet'), 'required|trim|max_length[200]');
		$this->form_validation->set_rules('idcustomer', azlang('Customer'), 'required|trim|max_length[200]');

		$payment_status = $this->input->post('payment_status');
		$idpayment = $this->input->post("idpayment");
		if ($payment_status == 'CASH') {
			$this->form_validation->set_rules('idpayment', 'Jenis Pembayaran', 'required|trim|max_length[200]');
			if ($idpayment == '1') {
				$this->form_validation->set_rules('total_pay', 'Jumlah Uang', 'required|trim|max_length[200]');				
			}
		}
		else if ($payment_status == 'PANJAR') {
			$this->form_validation->set_rules('idpayment', 'Jenis Pembayaran', 'required|trim|max_length[200]');
			$this->form_validation->set_rules('total_panjar', 'Jumlah Panjar', 'required|trim|max_length[200]');
			if ($idpayment == '1') {
				$this->form_validation->set_rules('total_pay', 'Jumlah Uang', 'required|trim|max_length[200]');				
			}
		}



		$err_code = 0;
		$err_message = '';
		$invoice = '';

		$total_pay = $this->input->post('total_pay');
		$total_panjar = $this->input->post('total_panjar');

		$idproduct = $this->input->post('idproduct');
		$trx_note = $this->input->post('trx_note');
		$add_cost = $this->input->post('add_cost');
		$price = $this->input->post('price');
		$total = $this->input->post('total');

		if($this->form_validation->run() == FALSE){
			$err_code++;
			$err_message = validation_errors();
		}

		$total_pcs = 0;
		if ($err_code == 0) {
			foreach ((array) $idproduct as $key => $value) {
				if (strlen($value) == 0) {
					$err_code++;
					$err_message = 'Harap lengkapi data transaksi';
				}
				else {
					$total_pcs++;
				}
			}
		}

		if ($err_code == 0) {
			$this->db->trans_begin();

			$idtransaction = $this->input->post('idtransaction');
			$qty = 1;

			$detail_description = $this->input->post('detail_description');
			$detail_qty = $this->input->post('detail_qty');
			$detail_idtransaction_detail = $this->input->post('idtransaction_detail');
			
			$info_discount = az_crud_number($this->input->post('info_discount'));
			$info_discount_percent = az_crud_number($this->input->post('info_discount_percent'));
			$info_add_cost = az_crud_number($this->input->post('info_add_cost'));
			$info_tax = az_crud_number($this->input->post('info_tax'));
			$info_tax_percent = az_crud_number($this->input->post('info_tax_percent'));

			$info_grand_total = az_crud_number($this->input->post('info_grand_total'));
			$info_total_final = az_crud_number($this->input->post('info_total_final'));

			$idcustomer = $this->input->post('idcustomer');
			$idoutlet = $this->input->post('idoutlet');
			if (strlen($this->session->userdata('idoutlet')) > 0) {
				$idoutlet = $this->session->userdata('idoutlet');
			}
			
			$data_save = array(
				'idoutlet' => $idoutlet,
				'idcustomer' => $idcustomer,
				'duedate' => az_crud_date($this->input->post('duedate')),
				'pay_date' => Date('Y-m-d H:i:s'),
				'note' => $this->input->post('info_note'),
				'iduser' => $this->session->userdata('iduser'),
				'grand_total' => $info_grand_total,
				'grand_discount' => $info_discount,
				'grand_discount_percent' => $info_discount_percent,
				'grand_add_cost' => $info_add_cost,
				// 'grand_tax' => $info_tax,
				// 'grand_tax_percent' => $info_tax_percent,
				'grand_total_final' => $info_total_final,
				'transaction_group_status' => 'Baru',
				'payment_status' => $this->input->post('payment_status'),
				'idpayment_type' =>  NULL,
				'total_pay' => 0,
				'total_panjar' => 0,
				'total_pcs' => $total_pcs,
				'add_cost_note' => $this->input->post('add_cost_note')
			);


			if ($payment_status == 'CASH' || $payment_status == 'PANJAR') {
				$data_save['total_pay'] = az_crud_number($total_pay);
				$data_save['total_panjar'] = az_crud_number($total_panjar);
				$data_save['idpayment_type'] = $this->input->post('idpayment');
			}

			if ($idpayment != '1') {
				$the_total = $info_total_final;
				if ($payment_status == 'PANJAR') {
					$the_total = az_crud_number($total_panjar);
				}
				$data_save['total_pay'] = $the_total;
			}
			


			if (strlen($idpost) == 0) {
				$data_code = $this->generate_code($idoutlet);
				$invoice = azarr($data_code, 'code');
				$code_num = azarr($data_code, 'code_num');

				$data_save['code'] = $invoice;
				$data_save['code_num'] = $code_num;
				$data_save['date'] = Date('Y-m-d H:i:s');
			}
			else {
				$this->db->where('idtransaction_group', $idpost);
				$invoice = $this->db->get('transaction_group')->row()->code;
			}

			$response_save = az_crud_save($idpost, $this->table, $data_save);
			$err_code = azarr($response_save, 'err_code');
			$err_message = azarr($response_save, 'err_message');
			$insert_id = azarr($response_save, 'insert_id');

			

			if ($err_code == 0) {
				foreach ((array)$idproduct as $key => $value) {
					if (strlen($value) == 0) {
						continue;
					}

					$idspot = '';
					$p_idspot = $this->input->post('idspot_'.$key);
					if (count($p_idspot) > 0) {
						$idspot = implode(',', $p_idspot);						
					}

					$idhue = '';
					$p_idhue = $this->input->post('idhue_'.$key);
					if (count($p_idhue) > 0) {
						$idhue = implode(',', $p_idhue);						
					}

					$idcolour = '';
					$p_idcolour = $this->input->post('idcolour_'.$key);
					if (count($p_idcolour) > 0) {
						$idcolour = implode(',', $p_idcolour);						
					}

					//update item
					$arr_new_item = array(
						'idhue' => $idhue,
						'idcolour' => $idcolour
					);
					
					az_crud_save($value, 'item', $arr_new_item);

					$this->db->where('iditem', $value);
					$this->db->join('product', 'item.idproduct = product.idproduct');
					$db_item = $this->db->get("item");

					$arr_transaction = array(
						'idtransaction_group' => $insert_id, 
						'iditem' => $value, 
						'qty' => 1, 
						'price' => az_crud_number(azarr($price, $key)), 
						'add_cost' => az_crud_number(azarr($add_cost, $key)), 
						'total' => az_crud_number(azarr($total, $key)),
						'idspot' => $idspot,
						'trx_note' => azarr($trx_note, $key),
						'point_a' => $db_item->row()->point_a,
						'point_b' => $db_item->row()->point_b,
						'point_c' => $db_item->row()->point_c,
						'point_d' => $db_item->row()->point_d,
					);
					$response_save = az_crud_save(azarr($idtransaction, $key), 'transaction', $arr_transaction);
					$err_code = azarr($response_save, 'err_code');
					$err_message = azarr($response_save, 'err_message');
					$idtransaction = azarr($response_save, 'insert_id');

					$idadditional_item = $this->input->post('idadditional_item_'.$key);
					$add_cost_price = $this->input->post('add_cost_price_'.$key);

					foreach ((array) $idadditional_item as $add_key => $add_value) {
						if (strlen($add_value) == 0) {
							continue;
						}
						$arr_add = array(
							'idtransaction' => $idtransaction,
							'idadditional_cost' => $add_value,
							'additional_price' => az_crud_number(azarr($add_cost_price, $add_key))
						);

						az_crud_save('', 'transaction_additional_cost', $arr_add);						
					}
					
				}
			}

			// if ($err_code == 0) {
			// 	$x_remove_tr = $this->input->post('x_transaction');
			// 	$x_data = explode(',', $x_remove_tr);
			// 	foreach ($x_data as $key => $value) {
			// 		if (strlen($value) > 0) {
			// 			$this->db->where('idtransaction', $value);
			// 			$this->db->delete('transaction');
			// 		}
			// 	}

			// 	$x_remove_tr = $this->input->post('x_transaction_detail');
			// 	$x_data = explode(',', $x_remove_tr);
			// 	foreach ($x_data as $key => $value) {
			// 		if (strlen($value) > 0) {
			// 			$this->db->where('idtransaction_detail', $value);
			// 			$this->db->delete('transaction_detail');
			// 		}
			// 	}
			// }
		}

		if ($this->db->trans_status() === FALSE || $err_code > 0) {
		    $this->db->trans_rollback();
		}
		else {
		    $this->db->trans_commit();
		}
		
		$invoice = urlencode($invoice);
		$data["err_message"] = $err_message;
		$data["err_code"] = $err_code;
		$data['invoice'] = $invoice;
		echo json_encode($data);
	}

	function generate_code($idoutlet) {
		$this->load->helper('az_core');

		$this->db->where('idoutlet', $idoutlet);
		$inv = $this->db->get('outlet')->row()->outlet_code;

		$code_num = 1;
		$this->db->where("idoutlet", $idoutlet);
		$this->db->order_by('code_num desc');
		$last = $this->db->get("transaction_group", 1);
		
		if ($last->num_rows() > 0) {
			$code_num = $last->row()->code_num;
			$code_num = $code_num + 1;
		}
		$db_num = sprintf('%05d', $code_num);
		
		$transaction_group_code = 'BILL'.$inv.'-'.$db_num;

		$return = array(
			'code' => $transaction_group_code,
			'code_num' => $code_num
		);

		return $return;
	}

	function invoice() {
		$this->load->library('Laundry');
		$code = $this->input->get('c');
		$type = $this->input->get('t');
		$code = urldecode($code);
		$return = $this->laundry->invoice($code);
		$err_code = azarr($return, 'err_code');
		if ($err_code == 0) {
			$this->load->helper('az_config');
			if ($type == 'small') {
				$this->load->view('sales_transaction/v_invoice_small', $return);
			}
			else {
				$this->load->view('sales_transaction/v_invoice', $return);
			}
		}
		else {
			redirect(app_url());
		}
	}

	function get_edit() {
		$err_code = 0;
		$err_message = "";
		$data_group = array();
		$data_transaction = array();
		$data_detail = array();

		$idoutlet = $this->session->userdata('idoutlet');

		$id = $this->input->post('id');
		$this->db->select('*, transaction_group.idoutlet, outlet_name as ajax_idoutlet, transaction_group.idcustomer, customer_name as ajax_idcustomer, grand_total as info_total, grand_add_cost as info_add_cost, grand_discount as info_discount, grand_discount_percent as info_discount_percent, grand_tax as info_tax, grand_tax_percent as info_tax_percent, grand_total_final as info_total_final, note as info_note');
		$this->db->join('outlet', 'transaction_group.idoutlet = outlet.idoutlet');
		$this->db->join('customer', 'transaction_group.idcustomer = customer.idcustomer');
		$this->db->where('idtransaction_group', $id);
		$this->db->where('transaction_group.status', 1);
		if (strlen($idoutlet) > 0) {
			$this->db->where('transaction_group.idoutlet', $idoutlet);
		}
		$data = $this->db->get('transaction_group');

		if ($data->num_rows() == 0) {
			$err_code++;
			$err_message = 'Data not found';
		}

		if ($err_code == 0) {
			$data_group = azarr($data->result_array(), 0);
			$this->db->select('*, product_type, product_name');
			$this->db->join('product', 'transaction.idproduct = product.idproduct');
			$this->db->where('idtransaction_group', $id);
			$this->db->where('transaction.status', 1);
			$data_transaction = $this->db->get('transaction')->result_array();

			$data_transaction_lang = array();
			foreach ($data_transaction as $key => $value) {
				$arr_val = array();
				foreach ($value as $vkey => $vvalue) {
					if ($vkey == 'product_type') {
						$arr_val[$vkey] = azlang($vvalue);
					}
					else {
						$arr_val[$vkey] = $vvalue;
					}
				}
				$data_transaction_lang[$key] = $arr_val;
			}

			$this->db->where('idtransaction_group', $id);
			$this->db->where('transaction_detail.status', 1);
			$data_detail = $this->db->get('transaction_detail')->result_array();
		}

		$return = array(
			'err_code' => $err_code,
			'err_message' => $err_message,
			'data' => $data_group,
			'data_transaction' => $data_transaction_lang,
			'data_detail' => $data_detail
		);

		echo json_encode($return);
	}

	function get_invoice() {
		$this->load->helper('az_core');
		$code = $this->input->post('code');
		$this->load->library('Laundry');
		$data = $this->laundry->invoice($code);

		$err_code = azarr($data, 'err_code');
		$err_message = azarr($data, 'err_message');

		$this->load->helper('az_config');
		$view = $this->load->view('sales_transaction/v_invoice', $data, true);

		$is_hide_btn = false;
		$trx_date = azarr($data, 'data');
		$trx_date = azarr($trx_date, 'date');
		$trx_date = Date('Y-m-d', strtotime($trx_date));
		$two_day_ago = Date('Y-m-d', strtotime('-2 days', strtotime(Date('Y-m-d'))));

		if (strtotime($trx_date) <= strtotime($two_day_ago)) {
			if ($this->session->userdata('role_name') == 'cashier') {
				$is_hide_btn = true;
			}
		}
		

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

		echo json_encode($return);
	}

	function print_report() {
		$date_1 = $this->input->post('date_1');
		$date_2 = $this->input->post('date_2');
		$idoutlet = $this->input->post('idoutlet');
		$status = $this->input->post('status');
		$idcustomer = $this->input->post('idcustomer');
		$pay = $this->input->post('pay');

		$data['date_1'] = $date_1;
		$data['date_2'] = $date_2;

		$this->db->where('transaction_group.status', 1);
		$this->db->where('date >= ', Date('Y-m-d', strtotime($date_1)).' 00:00:00');
		$this->db->where('date <= ', Date('Y-m-d', strtotime($date_2)).' 23:59:59');
		if (strlen($idoutlet) > 0) {
			$this->db->where('transaction_group.idoutlet', $idoutlet);
		}
		if (strlen($idcustomer) > 0) {
			$this->db->where('transaction_group.idcustomer', $idcustomer);
		}
		if (strlen($status) > 0) {
			$this->db->where('transaction_group_status', $status);
		}
		if (strlen($pay) > 0) {
			$this->db->where('pay', $pay);
		}
		$this->db->join('outlet', 'transaction_group.idoutlet = outlet.idoutlet');
		$this->db->join('customer', 'transaction_group.idcustomer = customer.idcustomer', 'left');
		$data['data'] = $this->db->get('transaction_group');
		$this->load->view('sales_transaction/v_print_sales_transaction', $data);
	}

	public function delete() {
		$id = $this->input->post('id');
		az_crud_delete($this->table, $id);
	}

	public function save_customer(){
		$data = array();
		$data_post = $this->input->post();
		$idpost = azarr($data_post, 'idcustomer');
		$data['sMessage'] = '';
		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('', '');

		$idoutlet = $this->session->userdata('idoutlet');
		if (strlen($idoutlet) == 0) {
			$this->form_validation->set_rules('idcsoutlet', azlang('Outlet'), 'required|trim');
			$idoutlet = azarr($data_post, 'idcsoutlet');
		}
		$this->form_validation->set_rules('customer_name', azlang('Customer Name'), 'required|trim|max_length[200]');
		$this->form_validation->set_rules('idcustomer_category', 'Kategori Pelanggan', 'required|trim|max_length[200]');

		$err_code = 0;
		$err_message = '';

		if($this->form_validation->run() == TRUE){
			$data_save = array(
				'idoutlet' => $idoutlet,
				'idcustomer_category' => 11, //reguler
				'customer_name' => $this->input->post('customer_name'),
				'address' => $this->input->post('address'),
				'email' => $this->input->post('email'),
				'phone' => $this->input->post('phone'),
				'birthday' => az_crud_date($this->input->post('birthday'), 'Y-m-d'),
			);

			if (strlen($idpost) == 0) {
				$data_code = az_generate_customer_code($idoutlet);

				$code = azarr($data_code, 'customer_code');
				$code_number = azarr($data_code, 'customer_code_num');
				$data_save['customer_code'] = $code;
				$data_save['customer_code_num'] = $code_number;
			}

			$response_save = az_crud_save($idpost, 'customer', $data_save);
			$err_code = azarr($response_save, 'err_code');
			$err_message = azarr($response_save, 'err_message');
			$insert_id = azarr($response_save, 'insert_id');


			$data["idcustomer"] = $insert_id;
			$data["customer_name"] = $this->input->post('customer_name');
		}
		else {
			$err_code++;
			$err_message = validation_errors();
		}

		$data["sMessage"] = $err_message;
		echo json_encode($data);
	}

	function process() {
		$idtransaction_group = $this->input->post('idtransaction_group');
		$pay = $this->input->post('pay');
		$pay_date = $this->input->post('pay_date');
		$transaction_group_status = $this->input->post('transaction_group_status');
		$err_code = 0;
		$err_message = '';

		if ($pay == 'PAID') {
			if (strlen($pay_date) == 0) {
				$err_code++;
				$err_message = azlang("Pay Date Required");
			}
		}

		if ($err_code == 0) {
			$arr_data = array(
				'pay' => $pay,
				'pay_date' => az_crud_date($pay_date),
				'transaction_group_status' => $transaction_group_status
			);

			if ($pay == 'NOT PAID YET') {
				$arr_data['pay_date'] = NULL;
			}

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

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

		echo json_encode($return);
	}

	function get_detail() {
		$id = $this->input->post('id');
		$this->db->select('pay, date_format(pay_date, "%d-%m-%Y %H:%i:%s") as pay_date, transaction_group_status');
		$this->db->where('idtransaction_group', $id);
		$data = $this->db->get('transaction_group')->result_array();

		echo json_encode($data[0]);
	}

	function get_customer_detail() {
		$id = $this->input->post('id');

		$this->db->where('idcustomer', $id);
		$this->db->join('customer_category', 'customer.idcustomer_category = customer_category.idcustomer_category');
		$data = $this->db->get('customer');

		$phone = '';
		$address = '';
		$category = '';
		if ($data->num_rows() > 0) {
			$phone = $data->row()->phone;
			$address = $data->row()->address;
			$category =  $data->row()->customer_category_name;
		}

		$return = array(
			'phone' => $phone,
			'address' => $address,
			'category' => $category
		);
		echo json_encode($return);
	}

	function get_additional_price() {
		$this->load->helper('az_core');
		$id = $this->input->post('id');
		$price = '';
		$this->db->where('idadditional_cost', $id);
		$data = $this->db->get('additional_cost');

		if ($data->num_rows() > 0) {
			$price = $data->row()->price;
		}

		$return = array(
			'price' => az_thousand_separator_decimal($price)
		);
		echo json_encode($return);
	}

	function choose_product() {
		$id = $this->input->post('id');
		$this->db->where('item_code', $id);
		$this->db->join('customer', 'item.idcustomer = customer.idcustomer');
		$this->db->join('product', 'item.idproduct = product.idproduct');
		$data = $this->db->get('item');

		$idproduct = '';
		$price = '';
		$name = '';
		$idcolour = '';
		$idhue = '';
		$idspot = '';
		$trx_note = '';
		$idcustomer = '';
		$customer_name = '';

		if ($data->num_rows() > 0) {
			$idproduct = $data->row()->iditem;
			$price = $data->row()->sell_price;
			$name = $data->row()->item_code.' - '.$data->row()->product_name;
			$idcolour = $data->row()->idcolour;
			$idhue = $data->row()->idhue;
			$idspot = $data->row()->idspot_item;
			$trx_note = $data->row()->trx_note_item;
			$idhue = $data->row()->idhue;
			$idcustomer = $data->row()->idcustomer;
			$customer_name = $data->row()->customer_code.' - '.$data->row()->customer_name;
		}

		$return = array(
			'idproduct' =>$idproduct,
			'price' => $price,
			'name' => $name,
			'idcolour' => $idcolour,
			'idhue' => $idhue,
			'idspot' => $idspot,
			'trx_note' => $trx_note,
			'idcustomer' => $idcustomer,
			'customer_name' => $customer_name
		);
		echo json_encode($return);
	}

	function print_bill($id, $type = '') {
		if ($type != 'trx_print') {
			$id = az_decode_url($id);			
		}
		if (strlen($id) == 0) {
			show_404();
		}

		$this->load->helper('az_core');
		$this->load->library('Laundry');
		$data = $this->laundry->invoice('x', $id);

		$data['type'] = $type;
		
		if ($type == '') {
			$this->load->view('sales_transaction/v_bill', $data);
		}
		else if ($type == 'old') {
			$this->load->view('sales_transaction/v_bill', $data);
		}
		else if ($type == 'trx_print') {
			$data = $this->laundry->invoice($id);
			$this->load->view('sales_transaction/v_bill', $data);
		}
		else if ($type == 'qr_baju') {
			$data = $this->laundry->invoice('x', $id);		

			$this->load->view('sales_transaction/v_qr_baju', $data);
		}
		else if ($type == 'marker') {
			$data = $this->laundry->invoice('x', $id);		
			$this->load->view('sales_transaction/v_marker', $data);
		}
		else if ($type == 'marker_old') {
			$data = $this->laundry->invoice('x', $id);		
			$this->load->view('sales_transaction/v_marker_old', $data);
		}
		else if ($type == 'marker_point') {
			$data = $this->laundry->invoice('x', $id);		
			$this->load->view('sales_transaction/v_marker_point', $data);
		}
		else {
			$this->load->view('sales_transaction/v_bill_production', $data);
		}
	}

	function create_item() {
		$data = array();
		$data_post = $this->input->post();
		
		$this->load->library('form_validation');
		// $this->form_validation->set_error_delimiters('', '');

		$idoutlet = $this->input->post('idnoutlet');
		$sess_idoutlet = $this->session->userdata('idoutlet');
		if (strlen($sess_idoutlet) == 0) {
			$this->form_validation->set_rules('idnoutlet', azlang('Outlet'), 'required|trim|max_length[200]');
		}
		else {
			$idoutlet = $sess_idoutlet;
		}

		$this->form_validation->set_rules('idnproduct_type', 'Jenis Barang', 'required|trim|max_length[200]');
		$this->form_validation->set_rules('idncustomer', 'Pelanggan', 'required|trim|max_length[200]');
		$this->form_validation->set_rules('idcolour[]', 'Warna', 'required|trim|max_length[200]');
		$this->form_validation->set_rules('idhue[]', 'Corak', 'required|trim|max_length[200]');

		$err_code = 0;
		$err_message = '';
		$code = '';

		if($this->form_validation->run() == FALSE){
			$err_code++;
			$err_message = validation_errors();
		}

		if ($err_code == 0) {
			$idcolour = implode(',', $this->input->post('idcolour'));
			$idhue = implode(',', $this->input->post('idhue'));
			$idspot = $this->input->post('idspot');
			if (count($idspot) > 0) {
				$idspot = implode(',', $this->input->post('idspot'));
			}
			$trx_note = $this->input->post("trx_note");

			$data_save = array(
				'idproduct' => $this->input->post('idnproduct_type'),
				'idcustomer' => $this->input->post('idncustomer'),
				'idcolour' => $idcolour,
				'idhue' => $idhue,
				'idspot_item' => $idspot,
				'trx_note_item' => $trx_note,
			);

			$this->load->helper('az_laundry');
			$data_code = az_generate_item_code($idoutlet);

			$code = azarr($data_code, 'item_code');
			$code_number = azarr($data_code, 'item_code_num');
			$data_save['item_code'] = $code;
			$data_save['item_code_num'] = $code_number;	

			$response_save = az_crud_save('', 'item', $data_save);
			$err_code = azarr($response_save, 'err_code');
			$err_message = azarr($response_save, 'err_message');
			$insert_id = azarr($response_save, 'insert_id');
		}

		$return = array(
			'err_code' => $err_code,
			'err_message' => $err_message,
			'code' => $code
		);
		echo json_encode($return);
	}

	function export_excel() {
		$date_1 = $this->input->post('date_1');
		$date_2 = $this->input->post('date_2');
		$idoutlet = $this->input->post('idoutlet');
		$status = $this->input->post('status');
		$idcustomer = $this->input->post('idcustomer');
		$filter_code = $this->input->post('filter_code');
		$process_status = $this->input->post('process_status');
		

		$data['date_1'] = $date_1;
		$data['date_2'] = $date_2;

		$this->db->where('transaction_group.status', 1);
		$this->db->where('date >= ', Date('Y-m-d', strtotime($date_1)).' 00:00:00');
		$this->db->where('date <= ', Date('Y-m-d', strtotime($date_2)).' 23:59:59');
		if (strlen($idoutlet) > 0) {
			$this->db->where('transaction_group.idoutlet', $idoutlet);
		}
		if (strlen($idcustomer) > 0) {
			$this->db->where('transaction_group.idcustomer', $idcustomer);
		}
		if (strlen($status) > 0) {
			$this->db->where('dstb_status', $status);
		}
		if (strlen($process_status) > 0) {
			$this->db->where('process_status', $process_status);
		}
		if (strlen($filter_code) > 0) {
			$this->db->like('code', $filter_code);
		}
		$this->db->join('outlet', 'transaction_group.idoutlet = outlet.idoutlet');
		$this->db->join('customer', 'transaction_group.idcustomer = customer.idcustomer', 'left');
		$this->db->join('payment_type', 'transaction_group.idpayment_type = payment_type.idpayment_type', 'left');
		$this->db->join('payment_type payment_type_finish', 'transaction_group.idpayment_type_finish = payment_type_finish.idpayment_type', 'left');
		$this->db->select('*, payment_type.payment_type_name, payment_type_finish.payment_type_name as payment_type_name_finish');
		$data['data'] = $this->db->get('transaction_group');
		
		$this->load->library('AZApp');
		$azapp = $this->azapp;
		$azapp->add_phpexcel();
		$phpexcel = PHPExcel_IOFactory::load(APPPATH . "assets/excel/sales_transaction.xlsx");
		$sheet0 = $phpexcel->setActiveSheetIndex(0);

		$i = 0;
		$start_row = 5;

		$styleArray11 = array(
		  'borders' => array(
			'allborders' => array(
			'style' => PHPExcel_Style_Border::BORDER_THIN
			)
		  )
		);
		
		$this->load->helper('az_core');
		$sheet0->setCellValue("A2", "Periode: ".$date_1.' s/d '.$date_2);
		

		$the_total = 0;
		foreach ($data['data']->result() as $key => $value) {
			$this->db->where('idtransaction_group', $value->idtransaction_group);
			$this->db->join('dstb_process', 'dstb_process_detail.iddstb_process = dstb_process.iddstb_process');
			$this->db->join('user cashier', 'dstb_process.idcashier = cashier.iduser');
			$this->db->join('user driver', 'dstb_process.iddriver = driver.iduser');
			$this->db->select('dstb_code, dstb_date, cashier.name as cashier_name, driver.name as driver_name, dstb_note');
			$dstb_process = $this->db->get('dstb_process_detail');
			$dstb_process_code = '';
			$dstb_process_date = '';
			$dstb_process_cashier = '';
			$dstb_process_driver = '';
			$dstb_process_note = '';
			if ($dstb_process->num_rows() > 0) {
				$dstb_process_code = $dstb_process->row()->dstb_code;
				$dstb_process_date = $dstb_process->row()->dstb_date;
				$dstb_process_cashier = $dstb_process->row()->cashier_name;
				$dstb_process_driver = $dstb_process->row()->driver_name;
				$dstb_process_note = $dstb_process->row()->dstb_note;
			}

			$this->db->where('idtransaction_group', $value->idtransaction_group);
			$this->db->join('dstb_clean', 'dstb_clean_detail.iddstb_clean = dstb_clean.iddstb_clean');
			$this->db->join('user cashier', 'dstb_clean.idcashier = cashier.iduser');
			$this->db->join('user driver', 'dstb_clean.iddriver = driver.iduser');
			$this->db->select('dstb_code, dstb_date, cashier.name as cashier_name, driver.name as driver_name, dstb_note');
			$dstb_clean = $this->db->get('dstb_clean_detail');
			$dstb_clean_code = '';
			$dstb_clean_date = '';
			$dstb_clean_cashier = '';
			$dstb_clean_driver = '';
			$dstb_clean_note = '';
			if ($dstb_clean->num_rows() > 0) {
				$dstb_clean_code = $dstb_clean->row()->dstb_code;
				$dstb_clean_date = $dstb_clean->row()->dstb_date;
				$dstb_clean_cashier = $dstb_clean->row()->cashier_name;
				$dstb_clean_driver = $dstb_clean->row()->driver_name;
				$dstb_clean_note = $dstb_clean->row()->dstb_note;
			}

			$sheet0->setCellValue("A".($start_row + $i), ($i+1));
			$sheet0->setCellValue("B".($start_row + $i), $value->code);
			$sheet0->setCellValue("AC".($start_row + $i), $value->customer_code);
			$sheet0->setCellValue("D".($start_row + $i), $value->dstb_status);
			$sheet0->setCellValue("E".($start_row + $i), $value->customer_name);
			$sheet0->setCellValue("F".($start_row + $i), $value->phone);
			$sheet0->setCellValue("G".($start_row + $i), $value->address);
			$sheet0->setCellValue("AD".($start_row + $i), $value->note);
			$sheet0->setCellValue("I".($start_row + $i), $value->total_pcs);
			$sheet0->setCellValue("J".($start_row + $i), $value->grand_discount);
			$sheet0->setCellValue("K".($start_row + $i), $value->grand_add_cost);
			$sheet0->setCellValue("L".($start_row + $i), $value->grand_total);
			$sheet0->setCellValue("M".($start_row + $i), $value->payment_status);
			$sheet0->setCellValue("N".($start_row + $i), $value->total_panjar);
			$sheet0->setCellValue("O".($start_row + $i), $value->payment_type_name);
			$sheet0->setCellValue("P".($start_row + $i), $value->pickup_date);

			$sheet0->setCellValue("Q".($start_row + $i), $value->outlet_name);
			$sheet0->setCellValue("R".($start_row + $i), $dstb_process_code);
			$sheet0->setCellValue("S".($start_row + $i), $dstb_process_date);
			$sheet0->setCellValue("T".($start_row + $i), $dstb_process_cashier);
			$sheet0->setCellValue("U".($start_row + $i), $dstb_process_driver);
			$sheet0->setCellValue("V".($start_row + $i), $dstb_process_note);
			$sheet0->setCellValue("W".($start_row + $i), $dstb_clean_code);
			$sheet0->setCellValue("X".($start_row + $i), $dstb_clean_date);
			$sheet0->setCellValue("Y".($start_row + $i), $dstb_clean_cashier);
			$sheet0->setCellValue("Z".($start_row + $i), $dstb_clean_driver);
			$sheet0->setCellValue("AA".($start_row + $i), $dstb_clean_note);
			$sheet0->setCellValue("AB".($start_row + $i), Date('d-m-Y'));
			$sheet0->setCellValue("C".($start_row + $i), $value->date);
			$sheet0->setCellValue("H".($start_row + $i), $value->duedate);
			$i++;
		}

		// $sheet0->setCellValue("I".($start_row + $i), $the_total);

		$sheet0->getStyle("A".$start_row.":AB".($start_row + $i - 1))->applyFromArray($styleArray11);
		//write file and download
		$filename='Transaksi.xls'; 
		header('Content-Type: application/vnd.ms-excel'); 
		header('Content-Disposition: attachment;filename="'.$filename.'"'); 
		header('Cache-Control: max-age=0'); 
		$objWriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');  
		$objWriter->save('php://output');
	}
}