<?php
require 'db.php';

$payment_id = intval($_POST['payment_id'] ?? 0);
$pay_amount = floatval($_POST['pay_amount'] ?? 0);
if ($payment_id <= 0 || $pay_amount <= 0) {
    die('Invalid input');
}

$pRes = $conn->query("SELECT * FROM bondhoki_payments WHERE id=$payment_id LIMIT 1");
if (!$pRes || $pRes->num_rows === 0) {
    die('Payment not found');
}
$payment = $pRes->fetch_assoc();

$new_paid = round($payment['paid_amount'] + $pay_amount, 2);
$due = floatval($payment['due_amount']);

if ($new_paid >= $due) {
    $new_status = 'paid';
    $paid_date = date('Y-m-d H:i:s');
} elseif ($new_paid > 0) {
    $new_status = 'partial';
    $paid_date = null;
} else {
    $new_status = 'unpaid';
    $paid_date = null;
}

$stmt = $conn->prepare("UPDATE bondhoki_payments SET paid_amount=?, status=?, paid_date=? WHERE id=?");
$stmt->bind_param('dssi', $new_paid, $new_status, $paid_date, $payment_id);
$stmt->execute();
$stmt->close();

// check if all months paid
$bondhoki_id = intval($payment['bondhoki_id']);
$res = $conn->query("SELECT COUNT(*) AS c FROM bondhoki_payments WHERE bondhoki_id=$bondhoki_id AND status!='paid'");
$row = $res->fetch_assoc();
if (intval($row['c']) === 0) {
    $conn->query("UPDATE bondhoki_customers SET status='closed' WHERE id=$bondhoki_id");
}

// ✅ Redirect back to list
header("Location: bondhoki_list.php");
exit;
