<?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']));



switch($act)
{
	case 'insert':		
        
        $str_is_purchase_sql = "select * from t_pur_return_entry_main where financial_id='$financial_id' and company_id='$sel_company' and actu_pur_bill_no='$txt_bill_no'";
		$res_is_purchase_res = $db->get_a_line($str_is_purchase_sql);
		if($res_is_purchase_res['p_invoice_id']!='') {
			echo json_encode(array("rslt"=>"3", "err_msg"=>"Purchase Record Already Exists!")); //deletion  
			exit;			
		}

    //    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_discount = implode(",",$overall_product_discount);
	   $overall_product_discount_amt = implode(",",$overall_product_discount_amt);
	   $overall_product_tot_amt = implode(",",$overall_product_tot_amt);

       $str_insert_main=" INSERT INTO `t_pur_return_entry_main` (`p_invoice_id`, `actu_pur_bill_no`, `p_bill_date`, `return_date`, `financial_id`, `company_id`, `sup_id`, `tot_pur_amount`, `discount_per`, `after_discount_amt`, `cgst_per`, `sgst_per`, `igst_per`, `cgst_total`, `sgst_total`, `igst_total`, `tot_tax_amt`, `final_pur_amt`, `notes`, `comments`, `IsActive`, `UserId`, `createddate`,  `credit_notes`) 
        VALUES ('".$p_invoice_id."', '".$txt_bill_no."', '".$txt_bill_date_db."','".$txt_return_date_db."', '".$financial_id."', '".$sel_company."', '".$txt_supplier_id."', '".$txt_tot_pur_amt."', '".$overall_discount_per."', '".$overall_discount_amt."',  '".$txt_cgst."', '".$txt_sgst."', '".$txt_igst."', '".$txt_cgst_total."', '".$txt_sgst_total."', '".$txt_igst_total."', '".$txt_tax_amt."', '".$txt_final_pur_amt."','".$txt_notes."','".$txt_comments."', '1', '".$_SESSION["UserId"]."', NOW() , '".$txt_return_notes."'
        
        )";
        // echo $str_insert_main;
        // exit();
        $rslt = $db->insert($str_insert_main);	
		$Last_insert_id=$db->insert_id;

        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_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_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_pur_return_entry_details(r_bill_no, pdt_sku, saree_desc, pdt_img, purchase_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_disc."',  '".$current_product_disc_amt."', '".$current_product_amt."', '1', '".$_SESSION["UserId"]."', '".$_SESSION["Financial_id"]."', NOW()
                )";
		// echo $str_insert_det;
        // exit();								
				$query4 = "UPDATE t_purchase_entry_details SET stock_status = '3' 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())");
		
		}
        echo json_encode(array("rslt"=>"1")); //success
	
        break;

        case 'update':
            // echo $txt_customer_id;
            // exit();
             $update_arr = array();	 	

             $str_update_main="   UPDATE `t_pur_return_entry_main` 
SET 
    `actu_pur_bill_no` = '".$txt_bill_no."',     `p_bill_date` = '".$txt_bill_date_db."',    `return_date` = '".$txt_return_date_db."', 
    `financial_id` = '".$financial_id."',     `company_id` = '".$sel_company."',     `sup_id` = '".$txt_supplier_id."', 
    `tot_pur_amount` = '".$txt_tot_pur_amt."',     `discount_per` = '".$overall_discount_per."', 
    `after_discount_amt` = '".$overall_discount_amt."',     `cgst_per` = '".$txt_cgst."',     `sgst_per` = '".$txt_sgst."', 
    `igst_per` = '".$txt_igst."',     `cgst_total` = '".$txt_cgst_total."',     `sgst_total` = '".$txt_sgst_total."', 
    `igst_total` = '".$txt_igst_total."',     `tot_tax_amt` = '".$txt_tax_amt."',     `final_pur_amt` = '".$txt_final_pur_amt."', 
    `notes` = '".$txt_notes."',     `comments` = '".$txt_comments."',     `IsActive` = '1',     `UserId` = '".$_SESSION["UserId"]."', 
    `createddate` = NOW(),      `credit_notes` = '".$txt_return_notes."' WHERE     `r_bill_no` = '".$edit_id."' 
    ";

    $rslt = $db->insert($str_update_main);	

    $pdt_cnt = count($hdn_pdt_cnt);
		for($i=0; $i<$pdt_cnt; $i++){			
			
			if(!empty($hdn_prev_sv_id[$i])){

                $str_update_det="UPDATE t_pur_return_entry_details set pdt_sku='".$txt_pdt_sku[$i]."', saree_desc='".$txt_pdt_desc[$i]."', purchase_price='".$txt_purchase_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]."'  ";
								
                // echo $str_update_det;
                // exit();

				$update_arr[] = $hdn_prev_sv_id[$i];									
				$db->insert($str_update_det);
    }else{
        //insert								
        $str_insert_det="INSERT into t_pur_return_entry_details(r_bill_no, pdt_sku, saree_desc, pdt_img, purchase_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_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.")");

  
  echo json_encode(array("rslt"=>"2")); //update success
		
  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_pur_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_pur_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_pur_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_pur_return_entry_details WHERE r_bill_no = $edit_id";
			$bill_no = "SELECT actu_bill_no, financial_id, company_id,sup_id,final_sale_amt FROM t_pur_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 = '0' 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_pur_return_entry_main WHERE r_bill_no = $edit_id";
			$query2 = "DELETE FROM t_pur_return_entry_details WHERE r_bill_no = $edit_id";
			
			
		if ($db->insert($query1) && $db->insert($query2)    ) {
			echo json_encode(array("rslt" => "5", "msg" => " Purchase Return Details Deleted Successfully"));
		} else {
			echo json_encode(array("rslt" => "-1", "err_msg" => "Error: " . $e->getMessage()));
		}
    
		
	

	break;
}



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