<?php

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

allowRoles([1]);

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

/* FETCH DISTRICTS */

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

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

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


/* CHECK DUPLICATE BLOCK IN SAME DISTRICT */

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

if(mysqli_num_rows($check) > 0)
{

echo "<script>
alert('Block already exists in this district');
window.location='add_block.php';
</script>";

exit;

}
else
{

mysqli_query($conn,"
INSERT INTO blocks
(district_id,block_name)
VALUES
('$district_id','$block_name')
");

echo "<script>
alert('Block Added Successfully');
window.location='add_block.php';
</script>";

exit;

}

}

?>

<div class="main">

<h2>Add Block</h2>

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

<label>Select District</label>

<select name="district_id" required>

<option value="">Select District</option>

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

<option value="<?php echo $d['id']; ?>">
<?php echo $d['district_name']; ?>
</option>

<?php } ?>

</select>

<label>Block Name</label>

<input type="text" name="block_name" placeholder="Enter Block Name" required>

<button type="submit" name="add" class="btn-save">
Add Block
</button>

</form>

</div>

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