<?php

include "../config/db.php";

$slug = $_GET['village'] ?? '';
$work_id = isset($_GET['work']) ? intval($_GET['work']) : 0;

/* FETCH VILLAGE */

$village = mysqli_fetch_assoc(mysqli_query($conn,"
SELECT * FROM villages WHERE slug='$slug'
"));

if(!$village){
echo "Village not found";
exit;
}

$village_id = $village['id'];

include "header.php";

/* FETCH WORK */

$work = mysqli_fetch_assoc(mysqli_query($conn,"
SELECT *
FROM donation_categories
WHERE id='$work_id'
AND village_id='$village_id'
"));

?>

<div class="container">

<?php

if(!$work){
echo "<h2 class='section-title'>Donation Work Not Found</h2>";
exit;
}

/* CALCULATE TOTAL COLLECTED */

$total = mysqli_fetch_assoc(mysqli_query($conn,"
SELECT SUM(received_amount) as total
FROM donors
WHERE category_id='$work_id'
"));

$collected = $total['total'] ?? 0;

$target = $work['target_amount'];

$remaining = $target - $collected;

$percent = 0;

if($target > 0){
$percent = ($collected/$target)*100;
}

?>

<h2 class="section-title">
<?php echo $work['work_name']; ?>
</h2>


<!-- SUMMARY -->

<div style="background:#fff;padding:20px;border-radius:8px;margin-bottom:20px;box-shadow:0 2px 6px rgba(0,0,0,0.1);">

<p><strong>Target Amount:</strong> ₹<?php echo number_format($target); ?></p>

<p><strong>Collected:</strong> ₹<?php echo number_format($collected); ?></p>

<p><strong>Remaining:</strong> ₹<?php echo number_format($remaining); ?></p>

<!-- PROGRESS BAR -->

<div style="background:#eee;height:25px;border-radius:5px;overflow:hidden;margin-top:10px;">

<div style="width:<?php echo $percent; ?>%;background:#2c7be5;height:25px;color:#fff;text-align:center;line-height:25px;">

<?php echo round($percent,2); ?>%

</div>

</div>

</div>


<?php

/* FETCH DONORS */

$query = mysqli_query($conn,"
SELECT donor_name,father_name,received_amount
FROM donors
WHERE category_id='$work_id'
AND received_amount > 0
ORDER BY received_amount DESC
");

?>

<h3>Donors</h3>

<table width="100%" border="1" cellpadding="8">

<tr style="background:#eee">
<th>Donor Name</th>
<th>Father Name</th>
<th>Donation Amount</th>
</tr>

<?php

if(mysqli_num_rows($query)==0){
echo "<tr><td colspan='3'>No donations yet</td></tr>";
}

while($row=mysqli_fetch_assoc($query)){
?>

<tr>

<td><?php echo htmlspecialchars($row['donor_name']); ?></td>

<td><?php echo htmlspecialchars($row['father_name']); ?></td>

<td>₹<?php echo number_format($row['received_amount']); ?></td>

</tr>

<?php } ?>

</table>

</div>

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