<?php

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

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

/* FETCH WORKS */

$query = mysqli_query($conn,"
SELECT dc.*, d.district_name, b.block_name, v.village_name
FROM donation_categories dc
LEFT JOIN districts d ON d.id = dc.district_id
LEFT JOIN blocks b ON b.id = dc.block_id
LEFT JOIN villages v ON v.id = dc.village_id
ORDER BY dc.id DESC
");

?>

<div class="main">

<h2>Donation Works</h2>

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

<tr style="background:#eee;">

<th>ID</th>
<th>Work</th>
<th>Village</th>
<th>Target</th>
<th>Collected</th>
<th>Progress</th>
<th>Donors</th>
<th>Status</th>
<th>Action</th>

</tr>

<?php while($row=mysqli_fetch_assoc($query)){ 

$category_id = $row['id'];

/* TOTAL COLLECTED */

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

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

/* DONOR COUNT */

$donors = mysqli_fetch_assoc(mysqli_query($conn,"
SELECT COUNT(*) as total
FROM donors
WHERE category_id='$category_id'
"));

$donor_count = $donors['total'];

/* PROGRESS */

$target = $row['target_amount'];

$progress = 0;

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

?>

<tr>

<td><?php echo $row['id']; ?></td>

<td><?php echo $row['work_name']; ?></td>

<td><?php echo $row['village_name']; ?></td>

<td>₹<?php echo number_format($target); ?></td>

<td>₹<?php echo number_format($collected); ?></td>

<td width="200">

<div style="background:#ddd;height:12px;border-radius:6px;overflow:hidden;">

<div style="
width:<?php echo $progress; ?>%;
background:#2c7be5;
height:12px;
"></div>

</div>

<small><?php echo round($progress); ?>%</small>

</td>

<td><?php echo $donor_count; ?></td>

<td>

<?php

if($row['status']=="in_progress")
{
echo "<span style='color:green;'>In Progress</span>";
}
else
{
echo "<span style='color:blue;'>Completed</span>";
}

?>

</td>

<td>

<a href="add_donor.php?category_id=<?php echo $row['id']; ?>">
Add Donor
</a>

|

<a href="donors_list.php?category_id=<?php echo $row['id']; ?>">
View Donors
</a>

|

<a href="edit_work.php?id=<?php echo $row['id']; ?>">
Edit
</a>

</td>

</tr>

<?php } ?>

</table>

</div>

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