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

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

  // Get the customer's ID before deleting the loan
  $sql_get_cust_id = "SELECT cust_id FROM loans WHERE loan_id = '$loan_id'";
  $query_get_cust_id = mysqli_query($db_link, $sql_get_cust_id);
  checkSQL($db_link, $query_get_cust_id);
  $row = mysqli_fetch_assoc($query_get_cust_id);
  $cust_id = $row['cust_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 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: customer.php?cust='.$cust_id);
  } else {
    // Handle the case when the loan ID is empty
    header('Location: customer.php');
  }
} else {
  // Handle the case when the loan ID is not provided
  header('Location: customer.php');
}
?>
