<?php

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

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

/* HIDE SIDEBAR */
echo "<style>
.sidebar{display:none !important;}
.topbar{margin-left:0 !important;}
.main{margin-left:0 !important;padding-bottom:80px;}
</style>";

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

/* FETCH DATA */
$data = mysqli_query($conn,"SELECT * FROM departments WHERE id='$id'");
$row = mysqli_fetch_assoc($data);

if(!$row){
echo "<script>alert('Department not found');window.location='view_departments.php';</script>";
exit;
}

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

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

$district_id = intval($_POST['district_id']);
$department_name = mysqli_real_escape_string($conn,$_POST['department_name']);
$description = $_POST['description'];

mysqli_query($conn,"
UPDATE departments
SET district_id='$district_id',
department_name='$department_name',
description='$description'
WHERE id='$id'
");

echo "<script>alert('Department Updated Successfully');</script>";

}

?>

<div class="app-content">

<!-- HEADER -->
<div class="card-box">
<h4>Edit Department</h4>
<p style="font-size:12px;color:#777;">Update department details</p>
</div>

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

<form method="POST">

<label>Select District</label>
<select name="district_id" class="form-control" required>

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

<?php echo htmlspecialchars($d['district_name']); ?>

</option>
<?php } ?>

</select>

<label style="margin-top:10px;">Department Name</label>
<input type="text" name="department_name" class="form-control"
value="<?php echo htmlspecialchars($row['department_name']); ?>" required>

<label style="margin-top:10px;">Description</label>
<textarea name="description" id="editor" class="form-control">
<?php echo htmlspecialchars($row['description']); ?>
</textarea>

<br>

<button type="submit" name="update" class="btn-mobile"
style="background:#f39c12;color:#fff;">
Update Department
</button>

</form>

</div>

</div>

<!-- CKEDITOR -->
<script src="https://cdn.ckeditor.com/4.21.0/standard/ckeditor.js"></script>
<script>
CKEDITOR.replace('editor');
</script>

<!-- ===== FOOTER ===== -->

<div class="bottom-nav">
    <a href="../dashboard.php">
        <i class="fa fa-house"></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"; ?>