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

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

$payment = fetchOne($conn, "SELECT * FROM payments WHERE id = ?", [$payment_id], "i");
if (!$payment) { echo json_encode(['success'=>false,'message'=>'Payment not found']); exit(); }

$loan = getLoanById($conn, $payment['loan_id']);
if (!$loan) { echo json_encode(['success'=>false,'message'=>'Loan not found']); exit(); }

try {
    // Restore balance if it was a regular payment
    if ($payment['payment_type'] !== 'interest_only') {
        $restored = min(
            floatval($loan['total_payable']),
            floatval($loan['balance']) + floatval($payment['amount'])
        );
        executeQuery($conn, "UPDATE loans SET balance = ? WHERE id = ?",
            [$restored, $loan['id']], "di");
    }

    // Restore loan status to released if it was marked paid by this payment
    if ($loan['status'] === 'paid') {
        $due = $loan['due_date'];
        $newStatus = (!empty($due) && $due < date('Y-m-d')) ? 'overdue' : 'released';
        executeQuery($conn, "UPDATE loans SET status = ? WHERE id = ?",
            [$newStatus, $loan['id']], "si");
    }

    // Delete the payment
    executeQuery($conn, "DELETE FROM payments WHERE id = ?", [$payment_id], "i");

    logActivity($conn, $_SESSION['user_id'], 'void_payment',
        "Voided payment ID: $payment_id — ₱{$payment['amount']} on loan #{$loan['id']}");

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
