<?php 
include 'session.php';

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

// echo $txt_bill_date;
// exit;
switch($act)
{
	case 'insert':		
	
		//Transaction sales main details insert
		$str_insert_main="insert into t_sales_entry_main(cgst_total, sgst_total, igst_total, notes,actu_bill_no, s_bill_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, IsActive, UserId, createddate)values('".$txt_cgst_total."', '".$txt_sgst_total."', '".$txt_igst_total."', '".$txt_notes."','".$txt_bill_no."','".$txt_bill_date_db."', '".$financial_id."', '".$sel_company."', '".$sel_customer."', '".$txt_tot_sale_amt."', '".$txt_cmn_discount_per."', '".$txt_after_discount_amt."', '".$txt_cgst."', '".$txt_sgst."', '".$txt_igst."', '".$txt_tax_amt."', '".$txt_final_sale_amt."', '1', '".$_SESSION["UserId"]."', NOW())";
		

		$rslt = $db->query($str_insert_main);	
		$Last_insert_id=$db->insert_id;
		
		//Transaction sales details insert [product or category details insert]
		if(isset($Last_insert_id) && !empty($Last_insert_id)){
			$pdt_cnt = count($hdn_pdt_cnt);
			for($i=0; $i<$pdt_cnt; $i++){
				
				if(isset($txt_pdt_sku[$i]) && !empty($txt_pdt_sku[$i]) && isset($txt_purchase_price[$i]) && !empty($txt_purchase_price[$i]))
				{			
					$str_insert_det="insert into t_sales_entry_details(s_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."', '".$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())";

					$pdt_update_det ="update t_purchase_entry_details set stock_status = 2 where pdt_sku = '".$txt_pdt_sku[$i]."'";
					// exit();								
					$db->query($str_insert_det);	
					$db->query($pdt_update_det);	
					
				}
				
			}
			
			//payment details add
			$rslt_payment = $db->query("insert into t_sales_payment(s_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_insert = "INSERT INTO `transaction_details`( `date`, `bill_no`, `particulars`,  `credit`, `financial_id`, `company_id`, `cus_id`, `createddate`, `modifieddate`, `UserId`, `IsActive`)
		VALUES ('".$txt_bill_date_db."', '".$txt_bill_no."', 'Sales', '".$txt_final_sale_amt."', '".$financial_id."', '".$sel_company."', '".$sel_customer."', NOW(), NOW() , '".$_SESSION["UserId"]."', '1') ";

		$rslt = $db->query($transaction_insert);	

$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) 
{
	$newCreditAmount = (float)$txt_final_sale_amt;

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

}
else {
	$newCreditAmount = (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."', '".$newCreditAmount."','0.00', NOW(), NOW(), '1', '".$_SESSION["UserId"]."'   ) ";
}
$rslt = $db->query($balance_update);	

		echo json_encode(array("rslt"=>"1")); //success
		exit;
	
	break;
	
	
	case 'update':
         $update_arr = array();	 	
		//  echo $hdn_price;
		//  exit;
	//$edit_id			
		$str_update_main="UPDATE t_sales_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."', financial_id='".$financial_id."', company_id='".$sel_company."', cus_id='".$sel_customer."',total_sale_amount='".$txt_tot_sale_amt."', discount_per='".$txt_cmn_discount_per."', after_discount_amt='".$txt_after_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."', UserId='".$_SESSION["UserId"]."' where s_bill_no='".$edit_id."'   ";		
		// echo $txt_bill_no;
		// exit;
		$rslt = $db->query($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_sales_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 s_bill_det_id='".$hdn_prev_sv_id[$i]."'  ";
								
				$update_arr[] = $hdn_prev_sv_id[$i];									
				$db->query($str_update_det);
				
			}else{
				//insert								
				$str_insert_det="insert into t_sales_entry_details(s_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->query($str_insert_det);
				$update_arr[] = $db->insert_id;	
			}
		}

		$transaction_update = " UPDATE `transaction_details` SET `date` ='".$txt_bill_date_db."',`credit` ='".$txt_final_sale_amt."',`financial_id`= '".$financial_id."',`company_id`= '".$sel_company."',`cus_id`= '".$sel_customer."',`modifieddate`= NOW()  WHERE bill_no = '".$txt_bill_no."' AND `financial_id`= '".$financial_id."' AND `company_id`= '".$sel_company."' AND `cus_id`= '".$sel_customer."' ";
		$rslt = $db->query($transaction_update);

                //Update Sales Detail
                $c_update_ids = implode(',',$update_arr);
                $rslt_payment = $db->query("delete from t_sales_entry_details where s_bill_no='".$edit_id."' AND s_bill_det_id NOT IN (".$c_update_ids.")");		
		//payment details update
		$rslt_payment = $db->query("update t_sales_payment set tot_payment_amt='".$txt_final_sale_amt."', tot_paid_amt='0.00', due_amt='".$txt_final_sale_amt."', UserId='".$_SESSION["UserId"]."' where s_bill_no='".$edit_id."'  ");


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


		$db->query($balance_update);
		
		echo json_encode(array("rslt"=>"2")); //update success
		exit;	
	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_sales_entry_main set IsActive = '".$status."'  where s_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  
	  }	 
	  	 
		exit;	
	break;
	
	case 'del_pdt_det':
		if(isset($pdt_det_id) && !empty($pdt_det_id)){
			$rslt_pdt_det = $db->get_a_line("select t1.*, t2.s_payment_id, t2.tot_paid_amt from t_sales_entry_details t1 inner join t_sales_payment t2 on t1.s_bill_no = t2.s_bill_no where 1=1 and t1.s_bill_det_id='".$pdt_det_id."' ");
						
			if(isset($rslt_pdt_det['tot_paid_amt']) && $rslt_pdt_det['tot_paid_amt']=='0.00' ){	
				$str="update t_sales_entry_details set IsActive = '2', UserId='".$_SESSION["UserId"]."'  where s_bill_det_id = '".$pdt_det_id."'";
				$db->query($str); 
				
				echo json_encode(array("rslt"=>"1"));  
			}else{
				echo json_encode(array("rslt"=>"-9", "err_msg"=>"Reference exists with payment information. Cannot Perform the action."));  
			}
			
		}
		else{
			echo json_encode(array("rslt"=>"-1"));  
		}
			exit;
	break;	
	
	case 'del':
		$edit_id = base64_decode($Id);
		
		$query = "SELECT * FROM t_sales_entry_details WHERE s_bill_no = $edit_id";

		$bill_no = "SELECT actu_bill_no, financial_id, company_id,cus_id,final_sale_amt FROM t_sales_entry_main WHERE s_bill_no = $edit_id";
		$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'];
		$sales_amt = $bill_no_result[0]['final_sale_amt'];

		// echo $actu_bill_no;
		// echo $financial_id;
		// echo $company_id;
		// echo $sel_customer;

		// 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 = '0' WHERE pdt_sku = '$current_product_id'";
			$db->insert($query4);
	
			$product_ids_array[] = $current_product_id;
			// $db->insert($product_ids_array);
		}
// 		print_r($product_ids_array);
// exit();
		$query1 = "DELETE FROM t_sales_entry_main WHERE s_bill_no = $edit_id";
		$query2 = "DELETE FROM t_sales_entry_details WHERE s_bill_no = $edit_id";
		$query3 = "DELETE FROM t_sales_payment WHERE s_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 credit = $sales_amt ";

		$query6 = "UPDATE total_balance SET credit = credit - $sales_amt WHERE financial_id = $financial_id AND company_id = $company_id AND cus_id = $sel_customer";
		$db->query($query6);
		
	if ($db->query($query1) && $db->query($query2) && $db->query($query3) && $db->query($query5)  ) {
		echo json_encode(array("rslt" => "5", "msg" => "Product Deleted Successfully"));
	} else {
		echo json_encode(array("rslt" => "-1", "err_msg" => "Error: " . $e->getMessage()));
	}
exit;
break;
}



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


?>