<?php

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

/* Only Super Admin */
allowRoles([1]);

$id = intval($_GET['id']);

/* FETCH BLOCK */
$data = mysqli_query($conn,"
SELECT b.*, d.district_name 
FROM blocks b
LEFT JOIN districts d ON b.district_id = d.id
WHERE b.id='$id'
");

$row = mysqli_fetch_assoc($data);

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

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

/* UPDATE */
if(isset($_POST['update']))
{

$district_id   = intval($_POST['district_id']);
$block_name    = mysqli_real_escape_string($conn, trim($_POST['block_name']));
$block_name_hi = mysqli_real_escape_string($conn, trim($_POST['block_name_hi']));

/* CHECK DUPLICATE */
$check = mysqli_query($conn,"
SELECT id FROM blocks
WHERE district_id='$district_id'
AND LOWER(block_name)=LOWER('$block_name')
AND id != '$id'
");

if(mysqli_num_rows($check) > 0)
{
echo "<script>alert('Block already exists in this district');</script>";
}
else
{

mysqli_query($conn,"UPDATE blocks SET
district_id='$district_id',
block_name='$block_name',
block_name_hi='$block_name_hi'
WHERE id='$id'");

echo "<script>alert('Block Updated Successfully');</script>";
echo "<script>window.location='../villages/village_data.php';</script>";

}

}
?>

<div class="main">

<h2>Edit Block</h2>

<form method="POST" class="form-box">

<label>Select District</label>
<select name="district_id" required>

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

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

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

</option>

<?php } ?>

</select>

<label>Block Name (English)</label>
<input type="text" name="block_name"
value="<?php echo htmlspecialchars($row['block_name']); ?>" required>

<label>Block Name (Hindi)</label>
<input type="text" name="block_name_hi"
value="<?php echo htmlspecialchars($row['block_name_hi']); ?>">

<button name="update" class="btn-save">Update Block</button>

</form>

</div>

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