<?php 
require 'functions.php';
checkLogin();
checkPermissionDelete();
$db_link = connect();

//DELETE-Button
if (isset($_GET['loan_id'])){
  $loan_id = sanitize($db_link, $_GET['loan_id']);

  // Get the customer's ID before deleting the loan
  $sql_get_group_id = "SELECT group_id FROM group_loans WHERE loan_id = '$loan_id'";
  $query_get_group_id = mysqli_query($db_link, $sql_get_group_id);
  checkSQL($db_link, $query_get_group_id);
  $row = mysqli_fetch_assoc($query_get_group_id);
  $group_id = $row['group_id'];

  if (!empty($loan_id)) {
    // Delete related transactions from LTRANS
    $sql_del_ltrans = "DELETE FROM ltrans WHERE loan_id = '$loan_id'";
    $query_del_ltrans = mysqli_query($db_link, $sql_del_ltrans);
    checkSQL($db_link, $query_del_ltrans);

    // Delete related incomes from INCOMES where applicable
    $sql_del_inc = "DELETE FROM incomes WHERE loan_id = '$loan_id'";
    $query_del_inc = mysqli_query($db_link, $sql_del_inc);
    checkSQL($db_link, $query_del_inc);

    // Delete loan
    $sql_del_loan = "DELETE FROM group_loans WHERE loan_id = '$loan_id'";
    $query_del_loan = mysqli_query($db_link, $sql_del_loan);
    checkSQL($db_link, $query_del_loan);

    // Refer back to CUSTOMER.PHP
    header('Location: group.php?group_id='.$group_id);
  } else {
    // Handle the case when the loan ID is empty
    header('Location: group.php');
  }
} else {
  // Handle the case when the loan ID is not provide
  header('Location: group.php');
}
?>
