<?php 
include("../config.php");
if(!empty($_POST)){
	
	$voucher_no 		= mysqli_real_escape_string($conn, $_POST['voucher_no']);
	$b_date 			= mysqli_real_escape_string($conn, date('Y-m-d', strtotime($_POST['b_date'])));
	$bank 				= mysqli_real_escape_string($conn, $_POST['bank']);
	$account_name 		= mysqli_real_escape_string($conn, $_POST['account_name']);
	$amount 			= mysqli_real_escape_string($conn, $_POST['amount']);
	$narration          = mysqli_real_escape_string($conn, $_POST['narration']);
	$company_id         = $_SESSION['company_id'];
  	$branch_id          = $_SESSION['branch_id'];
  	$lr_no       		= mysqli_real_escape_string($conn, implode(",", $_POST['lr_no']));
	$lr_nos				= $_POST['lr_no'];
	$lr_no_list			= "'" . implode("', '", $lr_nos) . "'";
	$created_id         = mysqli_real_escape_string($conn, $_SESSION['user_detail']['id']);
	$created_datetime   = mysqli_real_escape_string($conn, date('Y-m-d H:i:s'));
	$updated_id         = mysqli_real_escape_string($conn, $_SESSION['user_detail']['id']);
	$updated_datetime   = mysqli_real_escape_string($conn, date('Y-m-d H:i:s'));
	
	// COMMON
	$party      = "SELECT * FROM `act_master` WHERE `id` = '".$account_name."'";
    $party_res  = mysqli_query($conn,$party);
    $party_row  = mysqli_fetch_array($party_res);
    $code 		= $party_row['act_code'];

    $banks      = "SELECT * FROM `act_master` WHERE `id` = '".$bank."'";
    $banks_res  = mysqli_query($conn,$banks);
    $banks_row  = mysqli_fetch_array($banks_res);
    $b_code     = $banks_row['act_code'];
	
	if($_POST["id"] != ''){
		// UPDATE
		$type               = 'bank_receipt_update';
		$user_id            = $_SESSION['user_detail']['id'];
		$data               = serialize($_POST);

		$pd 		= "DELETE FROM `payment` WHERE voucher_no = '".$voucher_no."' AND company_id = '".$_SESSION['company_id']."' AND branch_id = '".$_SESSION['branch_id']."'";
		$pd_res 	= mysqli_query($conn,$pd);

		$gld 		= "DELETE FROM `general_ledger` WHERE voucher_no = '".$voucher_no."' AND company_id = '".$_SESSION['company_id']."' AND branch_id = '".$_SESSION['branch_id']."'";
		$gld_res 	= mysqli_query($conn,$gld);

		$insert = "INSERT INTO `payment`(`voucher_no`, `b_date`, `bank`, `account_name`, `amount`, `narration`, `lr_no`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`, `flag`) VALUES ('".$voucher_no."','".$b_date."','".$bank."','".$code."','".$amount."','".$narration."','".$lr_no."','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."','BP')";


		$results = mysqli_query($conn,$insert);
		

		//GENERAL LEDGER ENTRY

		$gl = "INSERT INTO `general_ledger`(`voucher_no`, `voucher_date`, `flag`, `credit_account`, `debit_account`, `amount`, `remark`, `checked`, `mark`, `net_amount`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$voucher_no."','".$b_date."','BANK PAYMENT','".$b_code."','".$code."','".$amount."','".$narration."','','','".$amount."','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
        $gl_res = mysqli_query($conn,$gl);

		$lr_exp_delete 				= "DELETE FROM `lr_expenses` WHERE voucher_no = '".$voucher_no."' AND company_id = '".$_SESSION['company_id']."' AND branch_id = '".$_SESSION['branch_id']."'";
		$lr_exp_delete_res 			= mysqli_query($conn,$lr_exp_delete);

		//$query = "SELECT lr_no, total_amnt, lr_amount, invoice_no, other_charges,detention FROM billing where lr_no IN ($lr_no_list)";

        $query = ("SELECT case when billing.lr_no IS NULL then lr_mst.lr_no else billing.lr_no end as 
        	       lr_no, case when billing.total_amnt IS NULL then lr_mst.freight else billing.
        	       total_amnt end as total_amnt, case when billing.lr_amount IS NULL then lr_mst.freight 
        	       else billing.lr_amount end as lr_amount, case when billing.invoice_no IS NULL then 
        	       lr_mst.lr_no else billing.invoice_no end as invoice_no, case when billing.
        	       other_charges IS NULL then 0 else billing.other_charges end as other_charges
                   FROM lr_mst LEFT OUTER JOIN billing ON lr_mst.lr_no = billing.lr_no where lr_mst.
        	       lr_no IN ($lr_no_list)");
		$result = mysqli_query($conn, $query);

		$lr_final_amount_val = 0;
		$lr_row = array();
		$lr_no_val = array();
		while ($row = mysqli_fetch_assoc($result)) {
			$sum_query = "SELECT SUM(amount) as total_other_amount FROM `billing_details` WHERE bill_no = '".$row['invoice_no']."'";
			$result_sum = mysqli_query($conn, $sum_query);
			$row_sum = mysqli_fetch_assoc($result_sum);
	
			$extra_row_amount  = $row_sum['total_other_amount'];
			$lr_no_val[] = $row['lr_no'];
			$lr_no = $row['lr_no'];

			$total_amnt = $row['total_amnt'];
			$lr_amount = $row['lr_amount'];
			$other_charges = $row['other_charges'];

			$sum_of_lr_and_other = $lr_amount + $other_charges;
	
			if ($sum_of_lr_and_other != 0) {
				$percentage = ($sum_of_lr_and_other*100)/$total_amnt;
			} else {
				$percentage = 0;
			}
	
			$extra_row_amount_get = ($extra_row_amount*$percentage)/100;
			$lr_final_amount = $extra_row_amount_get + $sum_of_lr_and_other;
			$lr_row[] = $lr_final_amount;
			$lr_final_amount_val += $lr_final_amount;
		}
			foreach ($lr_row as $index => $lr_value) {
				$lr_no_escaped = $lr_no_val[$index];
					if ($lr_final_amount_val != 0) {
						$percentage = ($lr_value / $lr_final_amount_val) * 100;
						$insert_amount_val = ($amount*$percentage)/100;
					} else {
					}
				$lr_exp_ins = "INSERT INTO `lr_expenses`(`voucher_no`, `flag`, `amount`, `lr_no`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`)
								   VALUES ('".$voucher_no."', 'B', '".$insert_amount_val."', '".$lr_no_escaped."', '".$company_id."', '".$branch_id."', '".$created_id."', '".$created_datetime."', '".$updated_id."', '".$updated_datetime."')";
					$lr_exp_ins_res = mysqli_query($conn, $lr_exp_ins);
			 }



		$activiti = "INSERT INTO `activities`(`type`, `user_id`, `data`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$type."','".$user_id."','".$data."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
		$acttivity_res = mysqli_query($conn,$activiti);	

	}else{
		$type               = 'bank_receipt_add';
		$user_id            = $_SESSION['user_detail']['id'];
		$data               = serialize($_POST);

		$insert = "INSERT INTO `payment`(`voucher_no`, `b_date`, `bank`, `account_name`, `amount`, `narration`, `lr_no`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`, `flag`) VALUES ('".$voucher_no."','".$b_date."','".$bank."','".$code."','".$amount."','".$narration."','".$lr_no."','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."','BP')";
		$results = mysqli_query($conn,$insert);
		

		//GENERAL LEDGER ENTRY

		$gl = "INSERT INTO `general_ledger`(`voucher_no`, `voucher_date`, `flag`, `credit_account`, `debit_account`, `amount`, `remark`, `checked`, `mark`, `net_amount`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$voucher_no."','".$b_date."','BANK PAYMENT','".$b_code."','".$code."','".$amount."','".$narration."','','','".$amount."','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
        $gl_res = mysqli_query($conn,$gl);
        $query = ("SELECT case when billing.lr_no IS NULL then lr_mst.lr_no else billing.lr_no end as 
        	       lr_no, case when billing.total_amnt IS NULL then lr_mst.freight else billing.
        	       total_amnt end as total_amnt, case when billing.lr_amount IS NULL then lr_mst.freight 
        	       else billing.lr_amount end as lr_amount, case when billing.invoice_no IS NULL then 
        	       lr_mst.lr_no else billing.invoice_no end as invoice_no, case when billing.
        	       other_charges IS NULL then 0 else billing.other_charges end as other_charges
                   FROM lr_mst LEFT OUTER JOIN billing ON lr_mst.lr_no = billing.lr_no where lr_mst.
        	       lr_no IN ($lr_no_list)");
		$result = mysqli_query($conn, $query);

		$lr_final_amount_val = 0;
		$lr_row = array();
		$lr_no_val = array();
		while ($row = mysqli_fetch_assoc($result)) {
			$sum_query = "SELECT SUM(amount) as total_other_amount FROM `billing_details` WHERE bill_no = '".$row['invoice_no']."'";
			$result_sum = mysqli_query($conn, $sum_query);
			$row_sum = mysqli_fetch_assoc($result_sum);
	
			$extra_row_amount  = $row_sum['total_other_amount'];
			$lr_no_val[] = $row['lr_no'];
			$lr_no = $row['lr_no'];

			$total_amnt = $row['total_amnt'];
			$lr_amount = $row['lr_amount'];
			$other_charges = $row['other_charges'];

			$sum_of_lr_and_other = $lr_amount + $other_charges;
	
			if ($sum_of_lr_and_other != 0) {
				$percentage = ($sum_of_lr_and_other*100)/$total_amnt;
			} else {
				$percentage = 0;
			}
	
			$extra_row_amount_get = ($extra_row_amount*$percentage)/100;
			$lr_final_amount = $extra_row_amount_get + $sum_of_lr_and_other;
			$lr_row[] = $lr_final_amount;
			$lr_final_amount_val += $lr_final_amount;
		}
			foreach ($lr_row as $index => $lr_value) {
				$lr_no_escaped = $lr_no_val[$index];
					if ($lr_final_amount_val != 0) {
						$percentage = ($lr_value / $lr_final_amount_val) * 100;
						$insert_amount_val = ($amount*$percentage)/100;
					} else {
					}
				$lr_exp_ins = "INSERT INTO `lr_expenses`(`voucher_no`, `flag`, `amount`, `lr_no`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`)
								   VALUES ('".$voucher_no."', 'B', '".$insert_amount_val."', '".$lr_no_escaped."', '".$company_id."', '".$branch_id."', '".$created_id."', '".$created_datetime."', '".$updated_id."', '".$updated_datetime."')";
					$lr_exp_ins_res = mysqli_query($conn, $lr_exp_ins);
			 }
		$activiti = "INSERT INTO `activities`(`type`, `user_id`, `data`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$type."','".$user_id."','".$data."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
		$acttivity_res = mysqli_query($conn,$activiti);	
	}
	
	echo json_encode( array('response' => 1, 'msg' => 'DATA SAVED SUCCESSFULLY', 'alert' => 1, 'redirect' => 'index.php?page=bank_payment/list.php') );die();
}else{
	echo json_encode( array('response' => 2, 'msg' => 'Opps', 'alert' => 1, 'redirect' => 'index.php?page=bank_payment/add.php') );die();
}  
?>