<?php
// deleteLoan.php
include '../../config.php';


if(isset($_POST['loan_id'])){
    $loan_id = mysqli_real_escape_string($conn, $_POST['loan_id']);
    
    // Anza transaction
    mysqli_begin_transaction($conn);
    
    try {
        // Futa schedule ya mkopo
        $query1 = "DELETE FROM loans_schedule WHERE loan_id = '$loan_id'";
        mysqli_query($conn, $query1);
        
        // Futa repayments (loans_collection)
        $query2 = "DELETE FROM loans_collection WHERE loan_id = '$loan_id'";
        mysqli_query($conn, $query2);
        
        // Futa rekodi ya mkopo
        $query3 = "DELETE FROM loans WHERE loan_id = '$loan_id'";
        mysqli_query($conn, $query3);
        
        // Commit transaction
        mysqli_commit($conn);
        
        echo json_encode(['status' => 'success', 'message' => 'Mkopo umefutwa kikamilifu']);
    } catch (Exception $e) {
        // Rollback ikiwa kuna tatizo
        mysqli_rollback($conn);
        echo json_encode(['status' => 'error', 'message' => 'Imeshindikana kufuta mkopo']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Loan ID haikupatiwa']);
}
?>
