<?php
require_once '../config/db.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';
requireLogin();
requireAdmin();
header('Content-Type: application/json');

$id = intval($_POST['id'] ?? 0);
if (!$id) { echo json_encode(['success'=>false,'message'=>'Invalid ID']); exit(); }

// Block deletion if borrower has any non-paid loans
$activeLoans = fetchOne($conn,
    "SELECT COUNT(*) as cnt FROM loans WHERE borrower_id = ? AND status NOT IN ('paid')",
    [$id], "i");
if ($activeLoans && $activeLoans['cnt'] > 0) {
    echo json_encode([
        'success' => false,
        'message' => "Cannot delete: this borrower has {$activeLoans['cnt']} active loan(s). Settle all loans first."
    ]);
    exit();
}

try {
    deleteBorrowerFull($conn, $id);
    logActivity($conn, $_SESSION['user_id'], 'delete_borrower', "Deleted borrower ID: $id");
    echo json_encode(['success' => true]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
