<?php 
include("../config.php");
if(!empty($_POST)){
	$product            = $_POST['product'];

	if($_POST["id"] != ''){
	    $invoice_no  = mysqli_real_escape_string($conn, $_POST['invoice_no']);
		$financial_year = $financial_years;
	}else{
		$financial_year = $financial_years;

		$invoice_no  = mysqli_real_escape_string($conn, $financial_year .'/'. strtoupper($prifix) . '/' . str_pad(($_POST['invoice_no']), 4, '0', STR_PAD_LEFT));
	}
	
	$vendor_id 			= mysqli_real_escape_string($conn, $_POST['vendor_id']);
	$bill_date 			= mysqli_real_escape_string($conn, date('Y-m-d', strtotime($_POST['bill_date'])));
	$total_amnt 		= mysqli_real_escape_string($conn, $_POST['total_amnt']);
	$net_amt 			= mysqli_real_escape_string($conn, $_POST['net_amnt']);
	$gross_amt 			= mysqli_real_escape_string($conn, $_POST['gross_amnt']);
	$other_add          = mysqli_real_escape_string($conn, $_POST['other_add']);
	$other_less         = mysqli_real_escape_string($conn, $_POST['other_less']);
	$remarks         	= mysqli_real_escape_string($conn, $_POST['remarks']);
	
	if(!empty($_POST['sgst_per'])){
		$sgst_per  = mysqli_real_escape_string($conn, $_POST['sgst_per']);
	}else{
		$sgst_per  = '';
	}

	if(!empty($_POST['sgst_amount'])){
    	$sgst_amount = mysqli_real_escape_string($conn, $_POST['sgst_amount']);
	}else{
	    $sgst_amount = '';
	}

	if(!empty($_POST['cgst_per'])){
    	$cgst_per = mysqli_real_escape_string($conn, $_POST['cgst_per']);
	}else{
	    $cgst_per = '';
	}

	if(!empty($_POST['cgst_amount'])){
    	$cgst_amount = mysqli_real_escape_string($conn, $_POST['cgst_amount']);
	}else{
	    $cgst_amount = '';
	}

	if(!empty($_POST['igst_per'])){
    	$igst_per = mysqli_real_escape_string($conn, $_POST['igst_per']);
	}else{
	    $igst_per = '';
	}

	if(!empty($_POST['igst_amount'])){
    	$igst_amount = mysqli_real_escape_string($conn, $_POST['igst_amount']);
	}else{
	    $igst_amount = '';
	}

	$company_id         = $_SESSION['company_id'];
  	$branch_id          = $_SESSION['branch_id'];
	$created_id         = mysqli_real_escape_string($conn, $_SESSION['user_detail']['id']);
	$created_datetime    = risFormatDate($_POST['bill_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'));
	$master_accounts    = combine(getAllRecords('act_master'), 'id', 'act_code');

	if($_POST["id"] != ''){
		// UPDATE
		$temp_bill = "SELECT * FROM billing WHERE invoice_no = '".$invoice_no."' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
		$temp_bill_res = mysqli_query($conn,$temp_bill);
		$lr_no 		  = array();
		while ($temp_bill_row = mysqli_fetch_assoc($temp_bill_res)) {
			$lr_no[] = "'".$temp_bill_row['lr_no']."'";
		}
		$temp_data = implode(',', $lr_no);

		$original_data = array();
		foreach ($product as $key => $a) {
			$original_data[] = "'".$a['lr_no']."'"; 
		}
		$original_entry = implode(',', $original_data);
		$get_data       = array_diff($lr_no,$original_data);
		

		$update_lr = "UPDATE `lr_mst` SET `billing_status`='N' WHERE `lr_no` IN (" . implode(',', $get_data) . ") AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
		$lr_res = mysqli_query($conn,$update_lr);

		//DELETE ALL ENTRY 
		$bill 			= "DELETE FROM billing  WHERE invoice_no = '".$invoice_no."' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
	    $bill_res 		= mysqli_query($conn,$bill);

	    $bill_de 		= "DELETE FROM billing_details  WHERE bill_no = '".$invoice_no."' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
	    $bill_de_res 	= mysqli_query($conn,$bill_de);

	    $gl 			= "DELETE FROM general_ledger  WHERE voucher_no = '".$invoice_no."' AND `flag` = 'S' AND branch_id = '".$_SESSION['branch_id']."' AND 
	         company_id = '".$_SESSION['company_id']."'";
	    $gl_de_res 	= mysqli_query($conn,$gl);

	    $gl 			= "DELETE FROM general_ledger  WHERE voucher_no = '".$invoice_no."' AND `flag` = 'G' AND `mark` = 'S' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
	    $gl_de_res 	= mysqli_query($conn,$gl);

	    $gl_res 		= mysqli_query($conn,$gl);
 		
 		$tra 			= "DELETE FROM trans  WHERE voucher_no = '".$invoice_no."' AND `flag` = 'BILLING' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
	    $tra_res 		= mysqli_query($conn,$tra);

	    $trans_de 	    = "DELETE FROM trans_details  WHERE voucher_no = '".$invoice_no."' AND `flag` = 'BILLING' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
	    $result 		= mysqli_query($conn,$trans_de);

	    // INSERT NEW DATA

	    $vendor 		= "SELECT * FROM `vendor_master` WHERE `id` = '".$vendor_id."'";
		$ven_res 		= mysqli_query($conn,$vendor);
		$ven_row 		= mysqli_fetch_array($ven_res);
		
		$act_msetr  	= "SELECT * FROM `act_master` WHERE `ac_name` = '".$ven_row['name']."'";
      	$act_ma_res 	= mysqli_query($conn,$act_msetr);
      	$act_ma_row 	= mysqli_fetch_array($act_ma_res);
      	$vendor_code 	= $act_ma_row['act_code'];
		
		$remark_string = $remarks;
		$responses = [];
		foreach ($product as $product) {
			if( isset($product['lr_no']) && !empty($product['lr_no']) ) {
				$type               = 'bill_add';
				$user_id            = $_SESSION['user_detail']['id'];
				$data               = serialize($_POST);

			    $remark_string = $remark_string ." LR No. ".$product['lr_no']." Date. ".$product['lr_date'];

				$insert = "INSERT INTO `billing`(`invoice_no`, `vendor_id`, `bill_date`, `series_code`, `lr_no`, `lr_date`, `lr_from`, `lr_to`, `lr_weight`, `lr_rate`, `lr_amount`, `other_charges`, `remark`, `total_amnt`, `net_amt`, `gross_amt`, `remarks`, `sgst_per`, `sgst_amount`, `cgst_per`, `cgst_amount`, `igst_per`, `igst_amount`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`,`hsn_code`) VALUES ('".$invoice_no."','".$vendor_id."','".$bill_date."','".$financial_year."','".$product['lr_no']."','".$product['lr_date']."','".$product['lr_from']."','".$product['lr_to']."','".$product['lr_weight']."','".$product['lr_rate']."','".$product['lr_amount']."','".$product['other_charges']."','".$product['remark']."','".$total_amnt."','".$net_amt."','".$gross_amt."','".$remarks."','".$sgst_per."','".$sgst_amount."','".$cgst_per."','".$cgst_amount."','".$igst_per."','".$igst_amount."','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."','".$product['hsn_code']."')";
				$result = mysqli_query($conn,$insert);
				if ($result) {
                    $responses[] = ["status" => "success", "message" => "Record inserted successfully for Lr number: " . $product['lr_no'], "bill_no" => $invoice_no];
                } else {
                    $responses[] = ["status" => "error", "message" => "Error inserting record for bill number: " . $product['bill_no'], "bill_no" => $invoice_no];
                }

				$g_amnt = $total_amnt + $product['other_charges'];
			}else {
            $responses[] = ["status" => "error", "message" => "Lr value not provided for LR number: " . $product['lr_no'], "bill_no" => $invoice_no];
    }
			//update lr_mst 
			$lr 	= "UPDATE `lr_mst` SET `billing_status`='Y' WHERE `lr_no`='".$product['lr_no']."' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
			$lr_res = mysqli_query($conn,$lr);
		}
		echo json_encode($responses);
		// FRIGHT CHARGES
		$ad          = "SELECT * FROM account_control WHERE descr = 'BILL'";
    	$ad_res      = mysqli_query($conn,$ad);
    	$ad_rows     = mysqli_fetch_assoc($ad_res);
    	$fright_code = @$master_accounts[$ad_rows['account_group']];

	    $lr = "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 ('".$invoice_no."','".$bill_date."','S','".$fright_code."','".$vendor_code."','".$gross_amt."','".$remark_string."','','','".$net_amt."','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
    	$lr_res = mysqli_query($conn,$lr);

		// ADDITION
	    $adds = $_POST['add'];
	    if(count($adds) > 0) {
	      foreach ($adds as $add_key => $add) {
	        if($add['tax_mst_id'] > 0 && $add['amount'] > 0 ) {
	          $lhc_details = "INSERT INTO `billing_details`(`bill_no`, `type`, `key`, `tax_mst_id`, `amount`, `branch_id`, `company_id`) VALUES ('".$invoice_no."','add','". $add_key ."','".$add['tax_mst_id']."','".$add['amount']."','".$_SESSION['branch_id']."','".$_SESSION['company_id']."')";
	          $lhc_del_res = mysqli_query($conn,$lhc_details);

	          // GENERAL LEDGER
	          $get_tax       = "SELECT * FROM `tax_mst` WHERE `id` = '".$add['tax_mst_id']."'";
	          $get_tax_res   = mysqli_query($conn,$get_tax);
	          $get_tax_row   = mysqli_fetch_array($get_tax_res);
	          $ac_id         = $get_tax_row['account_group'];

	          $acc_name      = "SELECT * FROM `act_master` WHERE `id` = '".$ac_id."'";
	          $acc_name_res  = mysqli_query($conn,$acc_name);
	          $acc_name_row  = mysqli_fetch_array($acc_name_res);
	                
	          $add_two = "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 ('".$invoice_no."','".$bill_date."','G','".$acc_name_row['act_code']."','".$vendor_code."','".$add['amount']."','".$remark_string."','','S','0','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
	          $add_one_res = mysqli_query($conn,$add_two);

			}
	      }
	    }

	    // SGST,CGST,IGST
	    if( isset($sgst_per) && !empty($sgst_per) && $sgst_per > 0 ) {	
			$master_accounts       = combine(getAllRecords('act_master'), 'id', 'act_code');
			$account       = "SELECT * FROM account_control WHERE descr = 'SGST'";
			$account_res   = mysqli_query($conn,$account);
			$account_rows  = mysqli_fetch_assoc($account_res);
			$sgst_code     = @$master_accounts[$account_rows['account_group']];

			$sgst = "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 ('".$invoice_no."','".$bill_date."','G','".$sgst_code."','".$vendor_code."','".$sgst_amount."','".$remark_string."','','S','0','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
	        $sgst_result = mysqli_query($conn,$sgst);
	    }

	    if( isset($cgst_per) && !empty($cgst_per) && $cgst_per > 0 ) {	
			$master_accounts       = combine(getAllRecords('act_master'), 'id', 'act_code');
			$account       = "SELECT * FROM account_control WHERE descr = 'CGST'";
			$account_res   = mysqli_query($conn,$account);
			$account_rows  = mysqli_fetch_assoc($account_res);
			$cgst_code     = @$master_accounts[$account_rows['account_group']];

			$cgst = "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 ('".$invoice_no."','".$bill_date."','G','".$cgst_code."','".$vendor_code."','".$cgst_amount."','".$remark_string."','','S','0','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
	        $cgst_result = mysqli_query($conn,$cgst);
	    }

	    if( isset($igst_per) && !empty($igst_per) && $igst_per > 0 ) {	
			$master_accounts       = combine(getAllRecords('act_master'), 'id', 'act_code');
			$account       = "SELECT * FROM account_control WHERE descr = 'IGST'";
			$account_res   = mysqli_query($conn,$account);
			$account_rows  = mysqli_fetch_assoc($account_res);
			$igst_code     = @$master_accounts[$account_rows['account_group']];

			$igst = "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 ('".$invoice_no."','".$bill_date."','G','".$igst_code."','".$vendor_code."','".$igst_amount."','".$remark_string."','','S','0','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
	        $igst_result = mysqli_query($conn,$igst);
	    }

	    // DEDUCTION
	    $subs = $_POST['sub'];
	    if(count($subs) > 0) {
	      foreach ($subs as $sub_key => $sub) {
	        if($sub['tax_mst_id'] > 0 && $sub['amount'] > 0 ) {
	          	$lhc_details = "INSERT INTO `billing_details`(`bill_no`, `type`, `key`, `tax_mst_id`, `amount`, `branch_id`, `company_id`) VALUES ('".$invoice_no."','sub','". $sub_key ."','".$sub['tax_mst_id']."','".$sub['amount']."','".$_SESSION['branch_id']."','".$_SESSION['company_id']."')";
	          	$lhc_del_res = mysqli_query($conn,$lhc_details);	
	          	$tax     	 = "select * from tax_mst where id = '".$sub['tax_mst_id']."'";
	  			$tax_res 	 = mysqli_query($conn,$tax);
	          	$tax_row 	 = mysqli_fetch_array($tax_res);
	          	$sub_id  	 = $tax_row['account_group'];

	          	$act_tds     = "select * from act_master WHERE `id` = '".$sub_id."'";
            	$act_tds_res = mysqli_query($conn,$act_tds);
            	$act_tds_row = mysqli_fetch_array($act_tds_res);

            	$tds_am = "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 ('".$invoice_no."','".$bill_date."','S','".$vendor_code."','".$act_tds_row['act_code']."','".$sub['amount']."','".$remark_string."','','','".$sub['amount']."','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
            	$tds_am_res = mysqli_query($conn,$tds_am);
	          
	        }
	      }
	    }

	   $trans = "INSERT INTO `trans`(`voucher_no`, `voucher_date`, `act_code`, `amount`, `adjust`, `balance`, `discount`, `tds`, `other_add`, `other_less`, `flag`, `mark`, `branch_id`, `company_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$invoice_no."','".$bill_date."','".$vendor_code."','".$net_amt."','','".$net_amt."','','','".$other_add."','".$other_less."','BILLING','','".$branch_id."','".$company_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
    	$trans_res = mysqli_query($conn,$trans);

    	//TRANS LAST ID
          
    	$last_id = mysqli_insert_id($conn);
    	$trans_det = "INSERT INTO `trans_details`(`voucher_no`, `trans_id`, `adjust`, `flag`, `balance`, `discount`, `tds`, `other_add`, `other_less`,`branch_id`, `company_id`) VALUES ('".$invoice_no."','".$last_id."','','BILLING','".$net_amt."','','','".$other_add."','".$other_less."','".$branch_id."','".$company_id."')";
    	$trans_det_res = mysqli_query($conn,$trans_det);
	}else{
		$vendor 		= "SELECT * FROM `vendor_master` WHERE `id` = '".$vendor_id."'";
		$ven_res 		= mysqli_query($conn,$vendor);
		$ven_row 		= mysqli_fetch_array($ven_res);
		
		$act_msetr  	= "SELECT * FROM `act_master` WHERE `ac_name` = '".$ven_row['name']."'";
      	$act_ma_res 	= mysqli_query($conn,$act_msetr);
      	$act_ma_row 	= mysqli_fetch_array($act_ma_res);
      	$vendor_code 	= $act_ma_row['act_code'];
		
		$remark_string = $remarks;
		$responses = [];
		foreach ($product as $product) {
			if( isset($product['lr_no']) && !empty($product['lr_no']) ) {
				$type               = 'bill_update';
				$user_id            = $_SESSION['user_detail']['id'];
				$data               = serialize($_POST);

			    $remark_string = $remark_string ." LR No. ".$product['lr_no']." Date. ".risformatdate($product['lr_date']);

				$insert = "INSERT INTO `billing`(`invoice_no`, `vendor_id`, `bill_date`, `series_code`, `lr_no`, `lr_date`, `lr_from`, `lr_to`, `lr_weight`, `lr_rate`, `lr_amount`, `other_charges`, `remark`, `total_amnt`, `net_amt`, `gross_amt`, `remarks`, `sgst_per`, `sgst_amount`, `cgst_per`, `cgst_amount`, `igst_per`, `igst_amount`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`,`hsn_code`) VALUES ('".$invoice_no."','".$vendor_id."','".$bill_date."','".$financial_year."','".$product['lr_no']."','".$product['lr_date']."','".$product['lr_from']."','".$product['lr_to']."','".$product['lr_weight']."','".$product['lr_rate']."','".$product['lr_amount']."','".$product['other_charges']."','".$product['remark']."','".$total_amnt."','".$net_amt."','".$gross_amt."','".$remarks."','".$sgst_per."','".$sgst_amount."','".$cgst_per."','".$cgst_amount."','".$igst_per."','".$igst_amount."','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."','".$product['hsn_code']."')";
				$result = mysqli_query($conn,$insert);
				
        		if ($result) {
                    $responses[] = ["status" => "success", "message" => "Record inserted successfully for Lr number: " . $product['lr_no'], "bill_no" => $invoice_no];
                } else {
                    $responses[] = ["status" => "error", "message" => "Error inserting record for bill number: " . $product['bill_no'], "bill_no" => $invoice_no];
                }
				$g_amnt = $total_amnt + $product['other_charges'];

				//update lr_mst 
				$lr 	= "UPDATE `lr_mst` SET `billing_status`='Y' WHERE `lr_no`='".$product['lr_no']."' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
				$lr_res = mysqli_query($conn,$lr);

			}else {
            $responses[] = ["status" => "error", "message" => "Lr value not provided for LR number: " . $product['lr_no'], "bill_no" => $invoice_no];
    }
		}
		echo json_encode($responses);
		
		// FRIGHT CHARGES
	    $ad          = "SELECT * FROM account_control WHERE descr = 'BILL'";
    	$ad_res      = mysqli_query($conn,$ad);
    	$ad_rows     = mysqli_fetch_assoc($ad_res);
    	$fright_code = @$master_accounts[$ad_rows['account_group']];

    	$lr = "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 ('".$invoice_no."','".$bill_date."','S','".$fright_code."','".$vendor_code."','".$gross_amt."','".$remark_string."','','','".$net_amt."','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
    	$lr_res = mysqli_query($conn,$lr);
    	
		// ADDITION
	    $adds = $_POST['add'];
	    if(count($adds) > 0) {
	      foreach ($adds as $add_key => $add) {
	        if($add['tax_mst_id'] > 0 && $add['amount'] > 0 ) {
	          $lhc_details = "INSERT INTO `billing_details`(`bill_no`, `type`, `key`, `tax_mst_id`, `amount`, `branch_id`, `company_id`) VALUES ('".$invoice_no."','add','". $add_key ."','".$add['tax_mst_id']."','".$add['amount']."','".$_SESSION['branch_id']."','".$_SESSION['company_id']."')";
	          $lhc_del_res = mysqli_query($conn,$lhc_details);

	          // GENERAL LEDGER
	          $get_tax       = "SELECT * FROM `tax_mst` WHERE `id` = '".$add['tax_mst_id']."'";
	          $get_tax_res   = mysqli_query($conn,$get_tax);
	          $get_tax_row   = mysqli_fetch_array($get_tax_res);
	          $ac_id         = $get_tax_row['account_group'];

	          $acc_name      = "SELECT * FROM `act_master` WHERE `id` = '".$ac_id."'";
	          $acc_name_res  = mysqli_query($conn,$acc_name);
	          $acc_name_row  = mysqli_fetch_array($acc_name_res);
	                
	          $add_two = "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 ('".$invoice_no."','".$bill_date."','G','".$acc_name_row['act_code']."','".$vendor_code."','".$add['amount']."','".$remark_string."','','S','0','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
	          $add_one_res = mysqli_query($conn,$add_two);

			}
	      }
	    }

	    // SGST,CGST,IGST
	    if( isset($sgst_per) && !empty($sgst_per) && $sgst_per > 0 ) {	
			$master_accounts       = combine(getAllRecords('act_master'), 'id', 'act_code');
			$account       = "SELECT * FROM account_control WHERE descr = 'SGST'";
			$account_res   = mysqli_query($conn,$account);
			$account_rows  = mysqli_fetch_assoc($account_res);
			$sgst_code     = @$master_accounts[$account_rows['account_group']];

			$sgst = "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 ('".$invoice_no."','".$bill_date."','G','".$sgst_code."','".$vendor_code."','".$sgst_amount."','".$remark_string."','','S','0','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
	        $sgst_result = mysqli_query($conn,$sgst);
	    }

	    if( isset($cgst_per) && !empty($cgst_per) && $cgst_per > 0 ) {	
			$master_accounts       = combine(getAllRecords('act_master'), 'id', 'act_code');
			$account       = "SELECT * FROM account_control WHERE descr = 'CGST'";
			$account_res   = mysqli_query($conn,$account);
			$account_rows  = mysqli_fetch_assoc($account_res);
			$cgst_code     = @$master_accounts[$account_rows['account_group']];

			$cgst = "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 ('".$invoice_no."','".$bill_date."','G','".$cgst_code."','".$vendor_code."','".$cgst_amount."','".$remark_string."','','S','0','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
	        $cgst_result = mysqli_query($conn,$cgst);
	    }

	    if( isset($igst_per) && !empty($igst_per) && $igst_per > 0 ) {	
			$master_accounts       = combine(getAllRecords('act_master'), 'id', 'act_code');
			$account       = "SELECT * FROM account_control WHERE descr = 'IGST'";
			$account_res   = mysqli_query($conn,$account);
			$account_rows  = mysqli_fetch_assoc($account_res);
			$igst_code     = @$master_accounts[$account_rows['account_group']];

			$igst = "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 ('".$invoice_no."','".$bill_date."','G','".$igst_code."','".$vendor_code."','".$igst_amount."','".$remark_string."','','S','0','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
	        $igst_result = mysqli_query($conn,$igst);
	    }

	    // DEDUCTION
	    $subs = $_POST['sub'];
	    if(count($subs) > 0) {
	      foreach ($subs as $sub_key => $sub) {
	        if($sub['tax_mst_id'] > 0 && $sub['amount'] > 0 ) {
	          	$lhc_details = "INSERT INTO `billing_details`(`bill_no`, `type`, `key`, `tax_mst_id`, `amount`, `branch_id`, `company_id`) VALUES ('".$invoice_no."','sub','". $sub_key ."','".$sub['tax_mst_id']."','".$sub['amount']."','".$_SESSION['branch_id']."','".$_SESSION['company_id']."')";
	          	$lhc_del_res = mysqli_query($conn,$lhc_details);	
	          	$tax     	 = "select * from tax_mst where id = '".$sub['tax_mst_id']."'";
	  			$tax_res 	 = mysqli_query($conn,$tax);
	          	$tax_row 	 = mysqli_fetch_array($tax_res);
	          	$sub_id  	 = $tax_row['account_group'];

	          	$act_tds     = "select * from act_master WHERE `id` = '".$sub_id."'";
            	$act_tds_res = mysqli_query($conn,$act_tds);
            	$act_tds_row = mysqli_fetch_array($act_tds_res);

            	$tds_am = "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 ('".$invoice_no."','".$bill_date."',
            		'S','".$vendor_code."','".$act_tds_row['act_code']."','".$sub['amount']."','".$remark_string."','','','".$sub['amount']."','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
            	$tds_am_res = mysqli_query($conn,$tds_am);
	          
	        }
	      }
	    }

    	$trans = "INSERT INTO `trans`(`voucher_no`, `voucher_date`, `act_code`, `amount`, `adjust`, `balance`, `discount`, `tds`, `other_add`, `other_less`, `flag`, `mark`, `branch_id`, `company_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$invoice_no."','".$bill_date."','".$vendor_code."','".$net_amt."','','".$net_amt."','','','".$other_add."','".$other_less."','BILLING','','".$branch_id."','".$company_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
    	$trans_res = mysqli_query($conn,$trans);

    	//TRANS LAST ID
          
    	$last_id = mysqli_insert_id($conn);
    	$trans_det = "INSERT INTO `trans_details`(`voucher_no`, `trans_id`, `adjust`, `flag`, `balance`, `discount`, `tds`, `other_add`, `other_less`, `branch_id`, `company_id`) VALUES ('".$invoice_no."','".$last_id."','','BILLING','".$net_amt."','','','".$other_add."','".$other_less."','".$branch_id."','".$company_id."')";
    	$trans_det_res = mysqli_query($conn,$trans_det);

		$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=bill/list.php') );die();
}else{
	echo json_encode( array('response' => 2, 'msg' => 'Opps', 'alert' => 1, 'redirect' => 'index.php?page=bill/add.php') );die();
}  
?>