<?php

include "../../config/master.php";

$donor_id = intval($_GET['donor_id']);
$category_id = intval($_GET['category_id']);

/* FETCH DONOR */

$donor = mysqli_fetch_assoc(mysqli_query($conn,"
SELECT * FROM donors
WHERE id='$donor_id'
"));

$balance = $donor['assigned_amount'] - $donor['received_amount'];

/* SAVE PAYMENT */

if(isset($_POST['receive']))
{

$amount = floatval($_POST['amount']);
$date   = $_POST['received_date'];

/* UPDATE DONOR */

mysqli_query($conn,"
UPDATE donors
SET received_amount = received_amount + '$amount'
WHERE id='$donor_id'
");

/* SAVE TRANSACTION */

mysqli_query($conn,"
INSERT INTO donation_transactions
(donor_id,category_id,amount,received_date)
VALUES
('$donor_id','$category_id','$amount','$date')
");

/* REDIRECT */

echo "<script>
alert('Payment Received Successfully');
window.location='donors_list.php?category_id=".$category_id."';
</script>";

}

include "../layout/header.php";
include "../layout/sidebar.php";

?>

<div class="main">

<h2>Receive Donation</h2>

<div class="form-box">

<p><b>Donor:</b> <?php echo htmlspecialchars($donor['donor_name']); ?></p>
<p><b>Father Name:</b> <?php echo htmlspecialchars($donor['father_name']); ?></p>

<p><b>Assigned:</b> ₹<?php echo number_format($donor['assigned_amount']); ?></p>

<p><b>Received:</b> ₹<?php echo number_format($donor['received_amount']); ?></p>

<p><b>Balance:</b> ₹<?php echo number_format($balance); ?></p>

<form method="POST">

<label>Receive Amount</label>
<input type="number" name="amount" max="<?php echo $balance; ?>" required>

<label>Receive Date</label>
<input type="date" name="received_date" value="<?php echo date('Y-m-d'); ?>">

<button type="submit" name="receive" class="btn-save">
Receive Payment
</button>

</form>

</div>

</div>

<?php include "../layout/footer.php"; ?>