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

class Report_profit extends CI_Controller {
	protected $table;

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

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

		$datetime1 = $azapp->add_datetime();
		$datetime1->set_id("transaction_date_1");
		$datetime1->set_name("transaction_date_1");
		$datetime1->set_value(Date("d-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"));
		$datetime2->set_format("DD-MM-YYYY");
		$datetime2->add_class("con-element-top-filter");
		$datetime2 = $datetime2->render();
		
		$data_filter["datetime1"] = $datetime1;
		$data_filter["datetime2"] = $datetime2;

		
		$v_filter = $this->load->view("report_profit/v_top_filter", $data_filter, true);

		$column = array('#', azlang('Date'), azlang('Nota'), azlang('Product Name'), azlang('Sell Total'),azlang('Modal Total'), azlang('Profit Total'));
		$crud->set_column($column);
		$crud->set_th_class("no-sort, , ,no-sort, ,");	

		$crud->set_id("report_profit");
		$crud->set_default_url(true);
		$crud->set_form('form');
		$crud->set_single_filter(false);
		$crud->set_btn_add(false);

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

		$azapp->add_js_ready("
			jQuery('body').on('click', '.btn-export-excel', function() {
				var check_found = jQuery('table#report_profit').find('tbody tr td.dataTables_empty').length;
				if (check_found == 1) {
					bootbox.alert({
	                    title: 'Error',
	                    message: 'Data kosong, pastikan data tampil pada tabel di bawah.'
	                });
				}
				else {
					var form_filter = jQuery('.form-top-filter-report_profit form');
					form_filter.attr('action', app_url+'report_profit/export_excel');
					form_filter.attr('target', '_blank');
					form_filter.submit();
				}
			});

			jQuery('body').on('click', '.btn-print-report', function() {
				var check_found = jQuery('table#report_profit').find('tbody tr td.dataTables_empty').length;
				if (check_found == 1) {
					bootbox.alert({
	                    title: 'Error',
	                    message: 'Data kosong, pastikan data tampil pada tabel di bawah.'
	                });
				}
				else {
					var form_filter = jQuery('.form-top-filter-report_profit form');
					form_filter.attr('action', app_url+'report_profit/print_data');
					form_filter.attr('target', '_blank');
					form_filter.submit();
				}
			});

			jQuery('#container_txt_total').appendTo('.btn-top-table');
		");

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

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

		$data_header['title'] = azlang('REPORT');
		$data_header['subtitle'] = 'LAPORAN LABA/RUGI';
		$azapp->set_data_header($data_header);

		echo $azapp->render();
	}

	public function get() {
		$this->load->library("AZAppCRUD");
		$crud = $this->azappcrud;
		$crud->add_join("user", "left");
		$crud->add_join('customer', 'left');
    	$crud->set_table("transaction_group");
    	$crud->add_where("transaction_group.status != 'PROCESS'");
		$crud->set_select("transaction_group.idtransaction_group, '' as xxx, '' as zzz, DATE_FORMAT(transaction_group.transaction_date, '%d-%m-%Y  %H:%i:%s') as transaction_date, '' as aaa, transaction_group.code");
    	$crud->set_select_table("transaction_group.idtransaction_group, transaction_group.transaction_date, transaction_group.code, xxx, zzz, bbb, aaa");

    	$crud->set_sorting('transaction_group.transaction_date, transaction_group.code, transaction_group.total_sell_price');
    	$crud->set_id("transaction_list");
    	$crud->set_custom_style("custom_style");
    	$crud->set_select_align(",,, right, right, right");
    	$crud->set_select_number("3, 4, 5, 6");
    	$crud->set_order_by("transaction_group.transaction_date desc");
    	
    	parse_str($_SERVER['QUERY_STRING'], $str);
    	// $top_filter = $_REQUEST['topfilter'];
    	$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);
    	$code = $arr_filter['code'];

    	$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($code) > 0) {
    		$this->db->like('code', $code);
    	}
    	$this->db->join('transaction_group', 'transaction.idtransaction_group = transaction_group.idtransaction_group');
    	$this->db->select("sum((ifnull(transaction.sell_price,0) - ifnull(transaction.modal_price,0)) * transaction.qty) as total, sum(transaction.final_price) as total_sell, sum(ifnull(transaction.modal_price,0) * transaction.qty) as total_modal");
    	$data_transaction = $this->db->get('transaction');
    	$total = $data_transaction->row()->total;
    	$sell_total = $data_transaction->row()->total_sell;
    	$modal_total = $data_transaction->row()->total_modal;

    	$ttotal = azlang('Sell Total').' '.az_thousand_separator($sell_total);
    	$ttotal .= '<br>'.azlang('Modal Total').' '.az_thousand_separator($modal_total);
    	$ttotal .= '<br>'.azlang('Profit Total').' '.az_thousand_separator($total);

    	$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);
	}

	public function custom_style($column, $value, $data) {
		$idtransaction_group = azarr($data, "idtransaction_group");
		if ($column == 'xxx' || $column == 'zzz' || $column == 'aaa' || $column == 'bbb') {
			$this->db->select('product_category.name as product_category_name, transaction.sell_price, transaction.modal_price, product.name as product_name, qty, final_price');
			$this->db->where("idtransaction_group", $idtransaction_group);
			$this->db->join("product", "product.idproduct = transaction.idproduct");
			$this->db->join('product_category', 'product_category.idproduct_category = product.idproduct_category', 'left');
			$rdata = $this->db->get("transaction");
			$div = "<table class='full-width' style='font-size:12px;pointer-events:none;'>";
			$total_profit = 0;
			$total_sell = 0;
			$total_modal = 0;
			foreach ($rdata->result() as $value) {
				$profit_price = $value->sell_price - $value->modal_price;
				$profit_price = $profit_price * $value->qty;
				$total_profit += $profit_price;

				$normal_price = $value->sell_price * $value->qty;
				$total_sell += $normal_price;
				$total_modal += $value->modal_price * $value->qty;

				$div .= "<tr>";
				$div .= "<td style='width:10px;padding-bottom:3px;border-bottom:1px solid #ccc;'><label class='label label-info'>".$value->qty."</label></td>";
				$div .= "<td style='padding-left:5px;border-bottom:1px solid #ccc;'>".$value->product_name." (".$value->product_category_name.")</td>";
				$div .= "<td style='padding-left:15px;text-align:right;border-bottom:1px solid #ccc;'>".az_thousand_separator($normal_price).' - '.az_thousand_separator($value->modal_price * $value->qty).' = '.az_thousand_separator($profit_price)."</td>";
				$div .= "</tr>";
			}
			$div .= "</table>";

			if ($column == 'xxx') {
				return $div;
			}
			else if ($column == 'zzz') {
				return az_thousand_separator($total_sell);
			}
			else if ($column == 'bbb') {
				return az_thousand_separator($total_modal);
			}
			else {
				return az_thousand_separator($total_profit);
			}
		}

		return "<div style='font-size:12px;'>".$value."</div>";
	}


	public function print_data() {
		$post = $this->input->post();
		if (count($post) == 0) {
			redirect(app_url().'report_profit','refresh');
		}
	
		$return = $this->get_rdata($post);

		if (count($return) > 0) {
			$this->load->view("report_profit/v_print", $return);
		}
		else {
			redirect(app_url().'report_profit','refresh');
		}
	}

	function get_rdata($post) {
		$transaction_date_1 = azarr($post, 'transaction_date_1');
		$transaction_date_2 = azarr($post, 'transaction_date_2');
		$transaction_date_1_db = Date('Y-m-d 00:00:00', strtotime($transaction_date_1));
		$transaction_date_2_db = Date('Y-m-d 23:59:59', strtotime($transaction_date_2));
		$idcustomer = azarr($post, 'idcustomer');
		$code = azarr($post, 'transaction_group_code');
		$iduser = azarr($post, 'iduser');
		$this->db->select('transaction_group.*, customer.*, customer.name as customer_name, user.username as cashier_name');
		
		$this->db->where("transaction_date >= ", $transaction_date_1_db);
		$this->db->where("transaction_date <= ", $transaction_date_2_db);
		$this->db->where('status', 'OK');
		if (strlen($idcustomer) > 0) {
			$this->db->where('transaction_group.idcustomer', $idcustomer);
		}
		if (strlen($code) > 0) {
			$this->db->where('transaction_group.code', $code);
		}
		if (strlen($iduser) > 0) {
			$this->db->where('iduser', $iduser);
		}
		$this->db->join('customer', 'customer.idcustomer = transaction_group.idcustomer', 'left');
		$this->db->join("user", "user.iduser = transaction_group.iduser", "left");
		$rdata = $this->db->get("transaction_group");		

		$return_new = array();
		
		$return = array();
		foreach ($rdata->result() as $key => $value) {
			$this->db->select('transaction.*, transaction.description as tdescription, product.*, product_category.name as category_name');
			$this->db->join("product", "product.idproduct = transaction.idproduct");
			$this->db->where("idtransaction_group", $value->idtransaction_group);
			$this->db->join('product_category', 'product_category.idproduct_category = product.idproduct_category', 'left');
			$transaction = $this->db->get("transaction");

			$return['code'] = $value->code;
			$return['transaction_date'] = $value->transaction_date;
			$return['total_sell_price'] = $value->total_sell_price;
			$return['total_discount'] = $value->total_discount;
			$return['total_final_price'] = $value->total_final_price;
			$return['customer_name'] = $value->customer_name;
			$return['cashier_name'] = $value->cashier_name;


			$product = array();
			$total_profit = 0;
			$total_sell = 0;
			$total_modal = 0;
			foreach ($transaction->result() as $tkey => $tvalue) {
				$profit_price = $tvalue->sell_price - $tvalue->modal_price;
				$profit_price = $profit_price * $tvalue->qty;
				$total_profit += $profit_price;

				$normal_price = $tvalue->sell_price * $tvalue->qty;
				$total_sell += $normal_price;
				$total_modal += $tvalue->modal_price * $tvalue->qty;


				$new_product = array();
				$new_product['name'] = $tvalue->name.'('.$tvalue->category_name.')';
				$new_product['qty'] = $tvalue->qty;
				// $new_product['final_price'] = $tvalue->final_price;
				$new_product['modal'] = $tvalue->modal_price * $tvalue->qty;
				$new_product['final_price'] = number_format($normal_price, 0, 2, '.').' - '.number_format($tvalue->modal_price * $tvalue->qty, 0, ',', '.').' = '.number_format($profit_price, 0, 2, '.');
				$product[] = $new_product;
			}
			$return['product'] = $product;
			$return['profit_total'] = $total_profit;
			$return['total_modal'] = $total_modal;
			$return_new[] = $return;
		}
		$return_date = '';
		if ($rdata->num_rows() > 0) {
			$return_date['transaction_date_1'] = $transaction_date_1;
			$return_date['transaction_date_2'] = $transaction_date_2;

			$return = array('data' => $return_new);
			$return = array_merge($return, $return_date);
		}

		return $return;
	}

}