<?php 
include 'session.php';

extract($_REQUEST);
$act=$action;
$txt_bill_date_db = date('Y-m-d', strtotime($_POST['txt_bill_date']));
$txt_return_date_db = date('Y-m-d', strtotime($_POST['txt_return_date']));


// $company_name= $_POST['company_name'];
// $company_without_dots = str_replace('.', '', $company_name);

// $comp= substr($company_without_dots, 0, 2);

// $invoice_id =$comp.' '. '-'.' '.$_POST['txt_bill_no'] ;
// $invoice_id;
// exit;
switch($act)
{
	case 'insert':		
        

    //    echo $overall_product_id;
	   $overall_product_ids = implode(",",$overall_product_id);
	   $overall_product_descs = implode(",",$overall_product_desc);
	   $overall_product_purchase = implode(",",$overall_product_purchase);
	   $overall_product_sales = implode(",",$overall_product_sales);
	   $overall_product_discount = implode(",",$overall_product_discount);
	   $overall_product_discount_amt = implode(",",$overall_product_discount_amt);
	   $overall_product_tot_amt = implode(",",$overall_product_tot_amt);
	//    exit;
		//Transaction sales main details insert
		$str_insert_main="insert into t_return_entry_main(cgst_total, sgst_total, igst_total, notes,actu_bill_no,invoice_id, s_bill_date, return_date, financial_id, company_id, cus_id, total_sale_amount, discount_per, after_discount_amt, cgst_per, sgst_per, igst_per, tot_tax_amt, final_sale_amt,debit_notes, comments , IsActive, UserId, createddate )values('".$txt_cgst_total."', '".$txt_sgst_total."', '".$txt_igst_total."', '".$txt_notes."','".$txt_bill_no."','".$invoice_id."','".$txt_bill_date_db."','".$txt_return_date_db."', '".$financial_id."', '".$sel_company."', '".$txt_customer_id."', '".$txt_tot_sale_amt."', '".$overall_discount_per."', '".$overall_discount_amt."', '".$txt_cgst."', '".$txt_sgst."', '".$txt_igst."', '".$txt_tax_amt."', '".$txt_final_sale_amt."','".$txt_return_notes."','".$txt_comments."', '1', '".$_SESSION["UserId"]."', NOW())";
		
		// $sales_return = "UPDATE t_sales_entry_details set status = '2' where s_bill_no = '".$txt_bill_no."' and financial_id = '".$financial_id."'  ";

		$rslt = $db->insert($str_insert_main);	
		$Last_insert_id=$db->insert_id;
		

		// echo $sales_return ="update t_sales_entry_details set IsActive = '2' where actu_bill_no = '".$txt_bill_no."' and financial_id = '".$financial_id."' and company_id = '".$sel_company."' ";

		//Transaction sales details insert [product or category details insert]
		if (isset($Last_insert_id) && !empty($Last_insert_id)) {
			$product_ids_array = explode(",", $overall_product_ids); 
			$product_descs_array = explode(",", $overall_product_descs); 
			$product_purchase_array = explode(",", $overall_product_purchase); 
			$product_sales_array = explode(",", $overall_product_sales); 
			$product_discount_array = explode(",", $overall_product_discount); 
			$product_discount_amt_array = explode(",", $overall_product_discount_amt); 
			$product_amt_array = explode(",", $overall_product_tot_amt); 

			
			$pdt_cnt = count($product_ids_array); // Get the count of product IDs
			
			for ($i = 0; $i < $pdt_cnt; $i++) {
				$current_product_id = $product_ids_array[$i]; // Get the current product ID
				$current_product_desc = $product_descs_array[$i]; 
				$current_product_purchase = $product_purchase_array[$i]; 
				$current_product_sales = $product_sales_array[$i]; 
				$current_product_disc = $product_discount_array[$i]; 
				$current_product_disc_amt = $product_discount_amt_array[$i]; 
				$current_product_amt = $product_amt_array[$i]; 
				// echo $current_product_id;

				if (isset($current_product_id) && !empty($current_product_id)) 
				{
					
				$str_insert_det="INSERT INTO t_return_entry_details(r_bill_no, pdt_sku, saree_desc, pdt_img, purchase_price, sale_price, pdt_discount_percent, pdt_discount_amt, tot_amount, IsActive, UserId, financial_id, createddate) values('".$Last_insert_id."', '".$current_product_id."', '".$current_product_desc."', '', '".$current_product_purchase."', '".$current_product_sales."', '".$current_product_disc."',  '".$current_product_disc_amt."', '".$current_product_amt."', '1', '".$_SESSION["UserId"]."', '".$_SESSION["Financial_id"]."', NOW())";
				// exit;								
				$query4 = "UPDATE t_purchase_entry_details SET stock_status = '0' WHERE pdt_sku = '$current_product_id' AND IsActive = '1' ";
				$db->query($query4);

					$db->insert($str_insert_det);	
					
				}
				
			}
			
			//payment details add
			$rslt_payment = $db->insert("INSERT INTO t_return_payment(r_bill_no, tot_payment_amt, tot_paid_amt, due_amt, financial_id, IsActive, UserId, createddate)values('".$Last_insert_id."', '".$txt_final_sale_amt."', '0.00', '".$txt_final_sale_amt."', '".$_SESSION["Financial_id"]."', '1', '".$_SESSION["UserId"]."', NOW())");
		
		}

		
		$transaction_details = "INSERT INTO `transaction_details`( `date`, `bill_no`, `particulars`,  `debit`, `financial_id`, `company_id`, `cus_id`, `createddate`, `modifieddate`, `UserId`, `IsActive`)	VALUES ('".$txt_return_date_db."', '".$txt_bill_no."', ' Return', '".$txt_final_sale_amt."', '".$financial_id."', '".$sel_company."', '".$txt_customer_id."', NOW(), NOW(), '".$_SESSION["UserId"]."', '1')";

		// echo $transaction_details;
		$rslt = $db->insert($transaction_details);

		


		$balance = " SELECT * FROM total_balance where financial_id = '".$_SESSION["Financial_id"]."' AND company_id = '".$sel_company."' AND cus_id = '".$sel_customer."' ";

$balance_result = $db->get_row($balance);
if ($balance_result) 
{
	$newDebitAmount = (float)$txt_final_sale_amt;

	$balance_update = "UPDATE total_balance SET debit = debit + '".$newDebitAmount."', modifieddate = NOW(),  UserId = '".$_SESSION["UserId"]."'  WHERE financial_id = '".$_SESSION["Financial_id"]."' AND company_id = '".$sel_company."' AND cus_id = '".$sel_customer."' ";

}
else {
	$newDebitAmount = (float)$txt_final_sale_amt;

	$balance_update = "INSERT INTO total_balance(financial_id, company_id, cus_id, credit, debit, createddate, modifieddate, IsActive, UserId  ) VALUES ('".$_SESSION["Financial_id"]."', '".$sel_company."', '".$sel_customer."', '0.00','".$newDebitAmount."', NOW(), NOW(), '1', '".$_SESSION["UserId"]."'   ) ";
}
$rslt = $db->insert($balance_update);	


$return_bill = "SELECT * FROM t_return_entry_main WHERE actu_bill_no = '".$txt_bill_no."'  ";
$return_bill_result = $db->get_row($return_bill);
if ($return_bill_result)
{
	$return_id = $return_bill_result->actu_bill_no;
	$return_amt = $return_bill_result->final_sale_amt;
	$date = $return_bill_result->s_bill_date;
	$financial_id = $return_bill_result->financial_id;
	$company_id = $return_bill_result->company_id;
	$cus_id = $return_bill_result->cus_id;

	$sales = "SELECT s_bill_no FROM t_sales_entry_main WHERE actu_bill_no = '".$return_id."' AND s_bill_date = '".$date."' AND financial_id = '".$financial_id."' AND company_id = '".$company_id."' AND cus_id = '".$cus_id."' AND final_sale_amt = '".$return_amt."' ";
	$sales_result = $db->get_row($sales);
	if ($sales_result)
	{
		$bill_no = $sales_result->s_bill_no;

		$payment_status = "UPDATE `t_sales_payment` SET payment_status_id = '2' WHERE `s_bill_no`= '".$bill_no."' ";
		$rslt = $db->insert($payment_status);
	}
}
// echo 'dffg';
// exit();

$select_query = "SELECT SUM(debit) AS total_debit, 
									SUM(credit) AS total_credit
									FROM transaction_details
									WHERE financial_id = '".$financial_id."'
									AND company_id = '".$sel_company."'
									AND cus_id = '".$txt_customer_id."'
									AND bill_no = '".$txt_bill_no."' ";

			$result = $db->get_row($select_query);
			if ($result) {
				
				$total_debit = $result->total_debit;
				$total_credit = $result->total_credit;
				// echo "total_debit ".$total_debit." total_credit ".$total_credit;
				// Check if total debit and credit are equal
				if ($total_debit == $total_credit) {
					// Update payment status for the 'Sales' row
					$update_query = "UPDATE transaction_details
									SET payment_status = '2'
									WHERE financial_id = '".$financial_id."'
												AND company_id = '".$sel_company."'
												AND cus_id = '".$txt_customer_id."'
												AND bill_no = '".$txt_bill_no."'
									AND particulars = 'Sales'";
					

					$rslt_update = $db->insert($update_query);

				}
			}


		echo json_encode(array("rslt"=>"1")); //success
	
	break;
	
	
	case 'update':
		// echo $txt_customer_id;
		// exit();
         $update_arr = array();	 	

	//$edit_id			
		$str_update_main="update t_return_entry_main set cgst_total='".$txt_cgst_total."', sgst_total='".$txt_sgst_total."', igst_total='".$txt_igst_total."', notes='".$txt_notes."',s_bill_date='".$txt_bill_date_db."',return_date='".$txt_return_date_db."', financial_id='".$financial_id."', company_id='".$sel_company."', cus_id='".$txt_customer_id."',total_sale_amount='".$txt_tot_sale_amt."', discount_per='".$overall_discount_per."', after_discount_amt='".$overall_discount_amt."', cgst_per='".$txt_cgst."', sgst_per='".$txt_sgst."', igst_per='".$txt_igst."', tot_tax_amt='".$txt_tax_amt."', final_sale_amt='".$txt_final_sale_amt."', debit_notes='".$txt_return_notes."', comments='".$txt_comments."', UserId='".$_SESSION["UserId"]."' where r_bill_no='".$edit_id."'   ";		
		$rslt = $db->insert($str_update_main);	
		
		//Transaction purchase details update [product or category details update]
		$pdt_cnt = count($hdn_pdt_cnt);
		for($i=0; $i<$pdt_cnt; $i++){			
			
			if(!empty($hdn_prev_sv_id[$i])){
				//update
				
				$str_update_det="update t_return_entry_details set pdt_sku='".$txt_pdt_sku[$i]."', saree_desc='".$txt_pdt_desc[$i]."', purchase_price='".$txt_purchase_price[$i]."', sale_price='".$txt_sale_price[$i]."', pdt_discount_percent='".$txt_pdt_discount_per[$i]."', pdt_discount_amt='".$txt_pdt_discount_amt[$i]."', tot_amount='".$txt_tot_amt[$i]."', UserId='".$_SESSION["UserId"]."' where r_bill_det_id='".$hdn_prev_sv_id[$i]."'  ";
								
				$update_arr[] = $hdn_prev_sv_id[$i];									
				$db->insert($str_update_det);
				
			}else{
				//insert								
				$str_insert_det="insert into t_return_entry_details(r_bill_no, pdt_sku, saree_desc, pdt_img, purchase_price, sale_price, pdt_discount_percent, pdt_discount_amt, tot_amount, IsActive, UserId, financial_id, createddate) values('".$edit_id."', '".$txt_pdt_sku[$i]."', '".$txt_pdt_desc[$i]."', '', '".$txt_purchase_price[$i]."', '".$txt_sale_price[$i]."', '".$txt_pdt_discount_per[$i]."',  '".$txt_pdt_discount_amt[$i]."', '".$txt_tot_amt[$i]."', '1', '".$_SESSION["UserId"]."', '".$_SESSION["Financial_id"]."', NOW())";
											
				$db->insert($str_insert_det);
				$update_arr[] = $db->insert_id;	
			}
		}
                //Update Sales Detail
                $c_update_ids = implode(',',$update_arr);
                $rslt_payment = $db->insert("delete from t_return_entry_details where r_bill_no='".$edit_id."' AND r_bill_det_id NOT IN (".$c_update_ids.")");		
		//payment details update
		$rslt_payment = $db->insert("update t_return_payment set tot_payment_amt='".$txt_final_sale_amt."', tot_paid_amt='0.00', due_amt='".$txt_final_sale_amt."', UserId='".$_SESSION["UserId"]."' where r_bill_no='".$edit_id."'  ");

	$transaction_update = " UPDATE transaction_details SET  `date` ='".$txt_return_date_db."',`financial_id`= '".$financial_id."',`company_id`= '".$sel_company."',`cus_id`= '".$txt_customer_id."',`modifieddate`= NOW()  WHERE bill_no = '".$txt_bill_no."' AND `debit` ='".$txt_final_sale_amt."' AND `financial_id`= '".$financial_id."' AND `company_id`= '".$sel_company."' AND `cus_id`= '".$txt_customer_id."' ";
	$rslt = $db->insert($transaction_update);

		$balance_update = "UPDATE total_balance SET debit = debit - '".$hdn_price."' + '".$txt_final_sale_amt."' WHERE financial_id='".$financial_id."' AND company_id='".$sel_company."' AND cus_id='".$sel_customer."'";


		$db->insert($balance_update);

		echo json_encode(array("rslt"=>"2")); //update success
		
	break;
	
	// case 'del':
	//   $edit_id = base64_decode($Id);
	  
	//   $chk_ref = check_reference($db, $edit_id);
	  
	//   if($chk_ref == 1){
	// 	   $str="update m_customer set IsActive = '2', UserId='".$_SESSION["UserId"]."'  where cus_id = '".$edit_id."'";
	// 	  $db->insert($str); 	 
		  
	// 	  $db->insert_log("delete","m_customer",$edit_id,"Customer deleted","Customer",$str);
	// 	  echo json_encode(array("rslt"=>"5")); //deletion
	//   }
	//   else{
	// 	 echo json_encode(array("rslt"=>"-1", "err_msg"=>"Reference exists with other data. Cannot Perform the action.")); //deletion  
	//   }	 		
	// break;
	
	
	case 'changestatus':
		$edit_id = base64_decode($Id);
		
		$status = $actval;
  
		 $chk_ref = check_reference($db, $edit_id);
		
	  // exit;
	  //   $status = $db->get_a_line("select IsActive from t_sales_entry_main where s_bill_no = '".$edit_id."' ");
  
		if($chk_ref == '1'){
			  $str="update t_return_entry_main set IsActive = '".$status."'  where r_bill_no = '".$edit_id."'";
			  
			  $db->insert($str); 	 
			
			  // $db->insert_log("changestatus","t_sales_entry_main",$edit_id,"Sales status changed","Sales",$str);
			  echo json_encode(array("rslt"=>"6")); //status update
		}
		else{
			  echo json_encode(array("rslt"=>"-1", "err_msg"=>"Reference exists with other data. Cannot Perform the action.")); //deletion  
		}	 
			 
		  
	  break;
	
	case 'del_pdt_det':
		if (isset($pdt_det_id) && !empty($pdt_det_id)) {
			try {
				// Check if tot_paid_amt is equal to '0.00'
				$rslt_pdt_det = $db->get_a_line("SELECT tot_paid_amt FROM t_return_entry_details WHERE r_bill_det_id = '".$pdt_det_id."'");
	
				if (isset($rslt_pdt_det['tot_paid_amt']) && $rslt_pdt_det['tot_paid_amt'] == '0.00') {
					// Perform the deletion
					$str = "UPDATE t_return_entry_details SET IsActive = '2', UserId='".$_SESSION["UserId"]."' WHERE r_bill_det_id = '".$pdt_det_id."'";
					$db->insert($str); 
	
					echo json_encode(array("rslt" => "1", "msg" => "Product Deleted Successfully"));
				} else {
					echo json_encode(array("rslt" => "-9", "err_msg" => "Reference exists with payment information. Cannot Perform the action."));
				}
			} catch (Exception $e) {
				echo json_encode(array("rslt" => "-1", "err_msg" => "Error: " . $e->getMessage()));
			}
		} else {
			echo json_encode(array("rslt" => "-1", "err_msg" => "Missing product identifier."));
		}
		break;

		case 'del':
			$edit_id = base64_decode($Id);
			// echo $edit_id;
			$query = "SELECT pdt_sku FROM t_return_entry_details WHERE r_bill_no = $edit_id";
			$bill_no = "SELECT actu_bill_no, financial_id, company_id,cus_id,final_sale_amt FROM t_return_entry_main WHERE r_bill_no = $edit_id";
			// echo $bill_no;

		$bill_no_result = $db->get_rsltset($bill_no);
		$actu_bill_no = $bill_no_result[0]['actu_bill_no'];
		$financial_id = $bill_no_result[0]['financial_id'];
		$company_id = $bill_no_result[0]['company_id'];
		$sel_customer = $bill_no_result[0]['cus_id'];
		$return_amt = $bill_no_result[0]['final_sale_amt'];
		// exit;

			$result = $db->get_rsltset($query);
		
			$product_ids_array = array();
		
			foreach ($result as $row) {
				$current_product_id = $row['pdt_sku'];
				
				// Output the update query for each iteration
				$query4 = "UPDATE t_purchase_entry_details SET stock_status = '2' WHERE pdt_sku = '$current_product_id' AND IsActive = '1' ";
				$db->insert($query4);
		
				$product_ids_array[] = $current_product_id;
				// $db->insert($product_ids_array);
			}
// print_r($product_ids_array);
// exit();
			$query1 = "DELETE FROM t_return_entry_main WHERE r_bill_no = $edit_id";
			$query2 = "DELETE FROM t_return_entry_details WHERE r_bill_no = $edit_id";
			$query3 = "DELETE FROM t_return_payment WHERE r_bill_no = $edit_id";


			$query5 = "DELETE FROM transaction_details WHERE bill_no = $actu_bill_no AND financial_id = $financial_id AND company_id = $company_id AND cus_id = $sel_customer AND debit = $return_amt ";
	// echo $query5;
	// 	exit;

			$query6 = "UPDATE total_balance SET debit = debit - $return_amt WHERE financial_id = $financial_id AND company_id = $company_id AND cus_id = $sel_customer";
			$db->insert($query6);
			
		if ($db->insert($query1) && $db->insert($query2) && $db->insert($query3) && $db->insert($query5)  ) {
			echo json_encode(array("rslt" => "5", "msg" => "Return Details Deleted Successfully"));
		} else {
			echo json_encode(array("rslt" => "-1", "err_msg" => "Error: " . $e->getMessage()));
		}
    
		$select_query = "SELECT SUM(debit) AS total_debit, 
									SUM(credit) AS total_credit
									FROM transaction_details
									WHERE financial_id = '".$financial_id."'
									AND company_id = '".$company_id."'
									AND cus_id = '".$sel_customer."'
									AND bill_no = '".$actu_bill_no."' ";

			$result = $db->get_row($select_query);
			if ($result) {
				$total_debit = $result->total_debit;
				$total_credit = $result->total_credit;

				// Check if total debit and credit are equal
				if ($total_debit != $total_credit) {
					// Update payment status for the 'Sales' row
					$update_query = "UPDATE transaction_details
									SET payment_status = NULL
									WHERE financial_id = '".$financial_id."'
												AND company_id = '".$company_id."'
												AND cus_id = '".$sel_customer."'
												AND bill_no = '".$actu_bill_no."'
												AND particulars = 'Sales'";

					$rslt_update = $db->insert($update_query);

				}
			}

			$sales = "SELECT s_bill_no FROM t_sales_entry_main WHERE actu_bill_no = '".$actu_bill_no."' AND financial_id = '".$financial_id."' AND company_id = '".$company_id."' AND cus_id = '".$sel_customer."' AND final_sale_amt = '".$return_amt."' ";


	$sales_result = $db->get_row($sales);
	if ($sales_result)
	{
		$bill_no = $sales_result->s_bill_no;

		$payment_status = "UPDATE `t_sales_payment` SET payment_status_id = '1' WHERE `s_bill_no`= '".$bill_no."' ";
		$rslt = $db->insert($payment_status);
	}

	break;
}


function check_reference($db, $customer_id){
	return 1;
}


?>