<?php 
include("../config.php");
if(!empty($_POST)){
	$product            = $_POST['product'];
	
	if($_POST["id"] != ''){
		$code  = mysqli_real_escape_string($conn, $_POST['code']);
	}else{
		$code  = mysqli_real_escape_string($conn, $_POST['code']);
        $checkpoint = mysqli_query($conn,"SELECT code FROM  general_purchase_new WHERE code = '".$code."'");
        if(mysqli_num_rows($checkpoint) > 0) {
            $code   = GeneralPurchase_new($conn);
        }

	}
	$bill_no 			= mysqli_real_escape_string($conn, $_POST['bill_no']);
	$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   = 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'));
	$master_accounts    = combine(getAllRecords('act_master'), 'id', 'act_code');
	if($_POST["id"] != ''){
		$type          = 'general_purchase_updated';
		$user_id       = $_SESSION['user_detail']['id'];
		$data          = serialize($_POST);

		$config['attachment']['gp_folder_path']     = '../assets/upload/general_purchase_img/';
		$config['attachment']['valid_types']        = array('pdf', 'doc', 'docx',  'png',  'jpg', 'jpeg');
		$config['attachment']['file_size']          = 1000000000000000000000000000; //
    
		if($_POST['old_gp_img'] != ''){
			if($_FILES["gp_img"]["name"] != ''){
				$gp_front_image = '';
				if($_FILES["gp_img"]["name"] != ''){
					$gp_front_file_extension = pathinfo($_FILES["gp_img"]["name"], PATHINFO_EXTENSION);
					if (!in_array($gp_front_file_extension, $config['attachment']['valid_types'])) {
						echo json_encode( array('response' => 2, 'msg' => 'The file type is not allowed to upload. Please try again !!', 'alert' => 1));
								die();
					}else if ($config['attachment']['file_size'] < $_FILES["gp_img"]["size"]) {
						echo json_encode( array('response' => 2, 'msg' => 'The file is to big to upload. !!', 'alert' => 1));
							die();
					}
					$gp_img             = rand(1,99999).'.'.basename($_FILES['gp_img']['name']);
					$gp_front_upload_file_path= $config['attachment']['gp_folder_path'] . $gp_img;
					@move_uploaded_file($_FILES["gp_img"]["tmp_name"], $gp_front_upload_file_path);
					$gp_front_image = $gp_img;
				}
			}else{
				$gp_img  = $_POST['old_gp_img'];    
			}
		}else{
			$gp_front_image = '';
			if($_FILES["gp_img"]["name"] != ''){
				$gp_front_file_extension = pathinfo($_FILES["gp_img"]["name"], PATHINFO_EXTENSION);
				if (!in_array($gp_front_file_extension, $config['attachment']['valid_types'])) {
					echo json_encode( array('response' => 2, 'msg' => 'The file type is not allowed to upload. Please try again !!', 'alert' => 1));
							die();
				}else if ($config['attachment']['file_size'] < $_FILES["gp_img"]["size"]) {
					echo json_encode( array('response' => 2, 'msg' => 'The file is to big to upload. !!', 'alert' => 1));
						die();
				}
				$gp_img             = rand(1,99999).'.'.basename($_FILES['gp_img']['name']);
				$gp_front_upload_file_path= $config['attachment']['gp_folder_path'] . $gp_img;
				@move_uploaded_file($_FILES["gp_img"]["tmp_name"], $gp_front_upload_file_path);
				$gp_front_image = $gp_img;
			}
		}

		// UPDATE
		$bill = mysqli_query($conn, "DELETE FROM `general_purchase_new` WHERE `id` = '".$_POST['id']."' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'");

		$bill_detail = mysqli_query($conn, "DELETE FROM `general_purchase_details_new` WHERE `gs_id` = '".$_POST['id']."'");

		//GENERAL PURCHASE TAX
 		$gst = mysqli_query($conn, "DELETE FROM `general_purchase_tax_history_new` WHERE `gs_id` = '".$_POST['id']."' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'");
        
	    $gl = "DELETE FROM general_ledger  WHERE voucher_no = '".$bill_no."' AND `flag` = 'GP' and mark  = 'GENERAL PURCHASE' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
	    $gl_res = mysqli_query($conn,$gl);
 		
	    $glk = "DELETE FROM general_ledger  WHERE voucher_no = '".$bill_no."' AND `flag` = 'G' and mark  = 'GP' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
	    $gl_resk = mysqli_query($conn,$glk);

 		$tra = "DELETE FROM trans  WHERE voucher_no = '".$bill_no."' AND `flag` = 'GENERAL PURCHASE' 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 = '".$bill_no."' AND `flag` = 'GENERAL PURCHASE' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'";
	    $result = mysqli_query($conn,$trans_de);

	    //$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 	= $vendor_id;

		
		$query = mysqli_query($conn, "INSERT INTO `general_purchase_new`(`code`, `bill_no`, `bill_date`, `vendor_id`, `sgst_per`, `sgst_amount`, `cgst_per`, `cgst_amount`, `igst_per`, `igst_amount`, `total_amnt`, `net_amt`, `gross_amt`, `remark`,`gp_img`,`branch_id`, `company_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$code."','".$bill_no."','".$bill_date."','".$vendor_id."','".$sgst_per."','".$sgst_amount."','".$cgst_per."','".$cgst_amount."','".$igst_per."','".$igst_amount."','".$total_amnt."','".$net_amt."','".$gross_amt."','".$remarks."','".$gp_img."','".$branch_id."','".$company_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')");
		$gs_id = mysqli_insert_id($conn);
		
		foreach ($product as $product) {

			if( isset($product['qty']) && !empty($product['qty']) ) {
				
				$insert = mysqli_query($conn, "INSERT INTO `general_purchase_details_new`(`gs_id`, `bill_no`, `description`, `hsn`, `unit`, `qty`, `rate`, `amount`, `remark`) VALUES ('".$gs_id."','".$bill_no."','".$product['description']."','".$product['hsn']."','".$product['unit']."','".$product['qty']."','".$product['rate']."','".$product['amount']."','".$product['remark']."')");
					$demo_product = $product['remark'];
			}
		}
		
		// FRIGHT CHARGES
	    $ad          = "SELECT * FROM account_control WHERE descr = 'GENERAL PURCHASE'";
    	$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 ('".$bill_no."','".$bill_date."','GP','".$vendor_code."','".$fright_code."','".$total_amnt."','".$demo_product."','','GENERAL PURCHASE','".$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 ) {
	          $addition = "INSERT INTO `general_purchase_tax_history_new`(`gs_id`, `bill_no`, `type`, `key`, `tax_mst_id`, `amount`, `branch_id`, `company_id`) VALUES ('".$gs_id."','".$bill_no."','add','". $add_key ."','".$add['tax_mst_id']."','".$add['amount']."','".$_SESSION['branch_id']."','".$_SESSION['company_id']."')";
	          $addition_result = mysqli_query($conn,$addition);

	          // 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 ('".$bill_no."','".$bill_date."','G','".$vendor_code."','".$acc_name_row['act_code']."','".$add['amount']."','".$product['remark']."','','GP','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 ('".$bill_no."','".$bill_date."','G','".$vendor_code."','".$sgst_code."','".$sgst_amount."','".$product['remark']."','','GP','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 ('".$bill_no."','".$bill_date."','G','".$vendor_code."','".$cgst_code."','".$cgst_amount."','".$product['remark']."','','GP','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 ('".$bill_no."','".$bill_date."','G','".$vendor_code."','".$igst_code."','".$igst_amount."','".$product['remark']."','','GP','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 `general_purchase_tax_history_new`(`gs_id`, `bill_no`, `type`, `key`, `tax_mst_id`, `amount`, `branch_id`, `company_id`) VALUES ('".$gs_id."','".$bill_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 ('".$bill_no."','".$bill_date."','G','".$act_tds_row['act_code']."','".$vendor_code."','".$sub['amount']."','".$product['remark']."','','GP','0','".$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 ('".$bill_no."','".$bill_date."','".$vendor_code."','".$net_amt."','','".$net_amt."','','','".$other_add."','".$other_less."','GENERAL PURCHASE','','".$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 ('".$bill_no."','".$last_id."','','GENERAL PURCHASE','".$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);

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

		//$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 	= $vendor_id;

		   //-------------------image section-----------------
		$config['attachment']['gp_folder_path']     = '../assets/upload/general_purchase_img/';
		$config['attachment']['valid_types']        = array('pdf', 'doc', 'docx',  'png',  'jpg', 'jpeg');
		$config['attachment']['file_size']          = 1000000000000000000000000000; //
    
		if($_POST['old_gp_img'] != ''){
			if($_FILES["gp_img"]["name"] != ''){
				$gp_front_image = '';
				if($_FILES["gp_img"]["name"] != ''){
					$gp_front_file_extension = pathinfo($_FILES["gp_img"]["name"], PATHINFO_EXTENSION);
					if (!in_array($gp_front_file_extension, $config['attachment']['valid_types'])) {
						echo json_encode( array('response' => 2, 'msg' => 'The file type is not allowed to upload. Please try again !!', 'alert' => 1));
								die();
					}else if ($config['attachment']['file_size'] < $_FILES["gp_img"]["size"]) {
						echo json_encode( array('response' => 2, 'msg' => 'The file is to big to upload. !!', 'alert' => 1));
							die();
					}
					$gp_img             = rand(1,99999).'.'.basename($_FILES['gp_img']['name']);
					$gp_front_upload_file_path= $config['attachment']['gp_folder_path'] . $gp_img;
					@move_uploaded_file($_FILES["gp_img"]["tmp_name"], $gp_front_upload_file_path);
					$gp_front_image = $gp_img;
				}
			}else{
				$gp_img  = $_POST['old_gp_img'];    
			}
		}else{
			$gp_front_image = '';
			if($_FILES["gp_img"]["name"] != ''){
				$gp_front_file_extension = pathinfo($_FILES["gp_img"]["name"], PATHINFO_EXTENSION);
				if (!in_array($gp_front_file_extension, $config['attachment']['valid_types'])) {
					echo json_encode( array('response' => 2, 'msg' => 'The file type is not allowed to upload. Please try again !!', 'alert' => 1));
							die();
				}else if ($config['attachment']['file_size'] < $_FILES["gp_img"]["size"]) {
					echo json_encode( array('response' => 2, 'msg' => 'The file is to big to upload. !!', 'alert' => 1));
						die();
				}
				$gp_img             = rand(1,99999).'.'.basename($_FILES['gp_img']['name']);
				$gp_front_upload_file_path= $config['attachment']['gp_folder_path'] . $gp_img;
				@move_uploaded_file($_FILES["gp_img"]["tmp_name"], $gp_front_upload_file_path);
				$gp_front_image = $gp_img;
			}
		}
    
    //-------------------image section-----------------
		
		$query = mysqli_query($conn, "INSERT INTO `general_purchase_new`(`code`, `bill_no`, `bill_date`, `vendor_id`, `sgst_per`, `sgst_amount`, `cgst_per`, `cgst_amount`, `igst_per`, `igst_amount`, `total_amnt`, `net_amt`, `gross_amt`, `remark`, `gp_img`, `branch_id`, `company_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$code."','".$bill_no."','".$bill_date."','".$vendor_id."','".$sgst_per."','".$sgst_amount."','".$cgst_per."','".$cgst_amount."','".$igst_per."','".$igst_amount."','".$total_amnt."','".$net_amt."','".$gross_amt."','".$remarks."','".$gp_img."','".$branch_id."','".$company_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')");
		$gs_id = mysqli_insert_id($conn);
		
		foreach ($product as $product) {

			if( isset($product['qty']) && !empty($product['qty']) ) {
			$insert = mysqli_query($conn, "INSERT INTO `general_purchase_details_new`(`gs_id`, `bill_no`, `description`, `hsn`, `unit`, `qty`, `rate`, `amount`, `remark`) VALUES ('".$gs_id."','".$bill_no."','".$product['description']."','".$product['hsn']."','".$product['unit']."','".$product['qty']."','".$product['rate']."','".$product['amount']."','".$product['remark']."')");

			}
		}
		
		// FRIGHT CHARGES
	    $ad          = "SELECT * FROM account_control WHERE descr = 'GENERAL PURCHASE'";
    	$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 ('".$bill_no."','".$bill_date."','GP','".$vendor_code."','".$fright_code."','".$total_amnt."','".$product['remark']."','','GENERAL PURCHASE','".$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 ) {
	          $addition = "INSERT INTO `general_purchase_tax_history_new`(`gs_id`, `bill_no`, `type`, `key`, `tax_mst_id`, `amount`, `branch_id`, `company_id`) VALUES ('".$gs_id."','".$bill_no."','add','". $add_key ."','".$add['tax_mst_id']."','".$add['amount']."','".$_SESSION['branch_id']."','".$_SESSION['company_id']."')";
	          $addition_result = mysqli_query($conn,$addition);

	          // 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 ('".$bill_no."','".$bill_date."','G','".$vendor_code."','".$acc_name_row['act_code']."','".$add['amount']."','".$product['remark']."','','GP','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 ('".$bill_no."','".$bill_date."','G','".$vendor_code."','".$sgst_code."','".$sgst_amount."','".$product['remark']."','','GP','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 ('".$bill_no."','".$bill_date."','G','".$vendor_code."','".$cgst_code."','".$cgst_amount."','".$product['remark']."','','GP','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 ('".$bill_no."','".$bill_date."','G','".$vendor_code."','".$igst_code."','".$igst_amount."','".$product['remark']."','','GP','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 `general_purchase_tax_history_new`(`gs_id`, `bill_no`, `type`, `key`, `tax_mst_id`, `amount`, `branch_id`, `company_id`) VALUES ('".$gs_id."','".$bill_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 ('".$bill_no."','".$bill_date."','G','".$act_tds_row['act_code']."','".$vendor_code."','".$sub['amount']."','".$product['remark']."','','GP','0','".$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 ('".$bill_no."','".$bill_date."','".$vendor_code."','".$net_amt."','','".$net_amt."','','','".$other_add."','".$other_less."','GENERAL PURCHASE','','".$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 ('".$bill_no."','".$last_id."','','GENERAL PURCHASE','".$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=general_purchase/list.php') );die();
}else{
	echo json_encode( array('response' => 2, 'msg' => 'Opps', 'alert' => 1, 'redirect' => 'index.php?page=general_purchase/new_add.php') );die();
}  
?>