<?php

include "../../config/master.php";
allowRoles([1]);

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

/* FILTER */
$search   = $_GET['search'] ?? '';
$district = $_GET['district'] ?? '';

$where = "WHERE 1";

if($search != ''){
$where .= " AND (
b.block_name LIKE '%$search%' 
OR b.block_name_hi LIKE '%$search%'
)";
}

if($district != ''){
$where .= " AND b.district_id='$district'";
}

/* DATA */
$query = mysqli_query($conn,"
SELECT b.*, d.district_name, d.district_name_hi
FROM blocks b
LEFT JOIN districts d ON b.district_id = d.id
$where
ORDER BY b.block_name
");

/* DISTRICTS */
$districts = mysqli_query($conn,"SELECT * FROM districts ORDER BY district_name");

?>

<div class="card-box">
<h4>Block List</h4>
</div>

<!-- FILTER -->
<div class="card-box">

<form method="GET" class="filter-form">

<input type="text" name="search" placeholder="Search Block"
value="<?php echo $search; ?>">

<select name="district">
<option value="">All Districts</option>

<?php while($d=mysqli_fetch_assoc($districts)){ ?>

<option value="<?php echo $d['id']; ?>"
<?php if($district==$d['id']) echo "selected"; ?>>

<?php 
echo ($d['district_name_hi'] != '') 
? $d['district_name_hi'] 
: $d['district_name']; 
?>

</option>

<?php } ?>

</select>

<button type="submit" class="btn-mobile btn-save">Search</button>
<a href="block_list.php" class="btn-mobile btn-reset">Reset</a>

</form>

</div>

<!-- LIST -->
<?php while($row=mysqli_fetch_assoc($query)){ ?>

<div class="card-box">

<h5>
<?php 
echo ($row['block_name_hi'] != '') 
? $row['block_name_hi'] 
: $row['block_name']; 
?>
</h5>

<p style="font-size:12px;color:#666;">
📍 
<?php 
echo ($row['district_name_hi'] != '') 
? $row['district_name_hi'] 
: $row['district_name']; 
?>
</p>

<p style="font-size:12px;color:#999;">
(<?php echo $row['block_name']; ?>)
</p>

<div class="action-icons">

<a href="edit_block.php?id=<?php echo $row['id']; ?>" class="icon-btn edit">
<i class="fa fa-pen"></i>
</a>

</div>

</div>

<?php } ?>

<!-- NAV -->
<div class="bottom-nav">
    <a href="../dashboard.php"><i class="fa fa-home"></i>Home</a>
    <a href="../villages/village_data.php"><i class="fa fa-map"></i>Villages</a>
    <a href="../families/view_families.php"><i class="fa fa-users"></i>Families</a>
    <a href="../schemes/view_schemes.php"><i class="fa fa-list"></i>Schemes</a>
</div>

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