<?php

date_default_timezone_set('Asia/Colombo');

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/csrf.php';

if (($_SESSION['role'] ?? '') !== 'admin') {
    die('Access Denied');
}

$id = filter_input(
    INPUT_GET,
    'id',
    FILTER_VALIDATE_INT,
    [
        'options' => [
            'min_range' => 1
        ]
    ]
);

if (!$id) {
    die('Invalid User ID');
}

$stmt = mysqli_prepare(
    $conn,
    'SELECT
        id,
        fullname,
        email,
        phone,
        workplace,
        role,
        zone_name,
        status
     FROM users
     WHERE id = ?
     LIMIT 1'
);

if (!$stmt) {
    die('Unable to load user: ' . mysqli_error($conn));
}

mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);

$result = mysqli_stmt_get_result($stmt);
$user = mysqli_fetch_assoc($result);

mysqli_stmt_close($stmt);

if (!$user) {
    die('User not found');
}

/*
|--------------------------------------------------------------------------
| Protect the main system administrator
|--------------------------------------------------------------------------
*/

if (
    (int)$user['id'] === 1 &&
    (int)($_SESSION['user_id'] ?? 0) !== 1
) {
    die('Access Denied');
}

require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/navbar.php';
?>

<div class="container mt-4">

<div class="card shadow">

<div class="card-header bg-warning">

<h4>Edit User</h4>

</div>

<div class="card-body">

<form
method="POST"
action="update_user.php">

<input
type="hidden"
name="csrf_token"
value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES) ?>">

<input
type="hidden"
name="id"
value="<?= $user['id'] ?>">

<div class="row">

<div class="col-md-6">

<label>Full Name</label>

<input
type="text"
name="fullname"
class="form-control"
required
value="<?= htmlspecialchars($user['fullname']) ?>">

</div>

    <div class="col-md-6">

        <label>Email</label>

        <input
        type="email"
        name="email"
        class="form-control"
        value="<?= htmlspecialchars($user['email']) ?>">

    </div>

</div>

    <div class="row mt-3">

        <div class="col-md-6">

            <label>Phone Number</label>

            <input
            type="text"
            name="phone"
            class="form-control"
            required
            value="<?= htmlspecialchars($user['phone']) ?>">

        </div>

        <div class="col-md-6">

            <label>Workplace</label>

            <input
            type="text"
            name="workplace"
            class="form-control"
            value="<?= htmlspecialchars($user['workplace']) ?>">

        </div>

    </div>

<div class="row mt-3">

    <div class="col-md-6">

        <label>Role</label>

        <select
            name="role"
            id="role"
            class="form-select">

            <option
                value="user"
                <?= $user['role']=='user'?'selected':'' ?>>
                User
            </option>

            <option
                value="zonal_director"
                <?= $user['role']=='zonal_director'?'selected':'' ?>>
                Zonal Director
            </option>

            <option
                value="admin"
                <?= $user['role']=='admin'?'selected':'' ?>>
                Administrator
            </option>

        </select>

    </div>

</div>

<!-- Zone -->

<div class="row mt-3">

<div
class="col-md-6"
id="zone_div">

<label>Zone</label>

<select
name="zone_name"
class="form-select">

<option value="">
-- Select Zone --
</option>

<?php

$zones = mysqli_query(
    $conn,
    "SELECT DISTINCT zone_name
     FROM schools
     WHERE zone_name IS NOT NULL
     ORDER BY zone_name ASC"
);

while($zone = mysqli_fetch_assoc($zones))
{

?>

<option
value="<?= htmlspecialchars($zone['zone_name']) ?>"

<?= ($user['zone_name']==$zone['zone_name'])
? 'selected'
: '' ?>>

<?= htmlspecialchars($zone['zone_name']) ?>

</option>

<?php
}
?>

</select>

</div>

<div class="col-md-6">

<label>Status</label>

<select
name="status"
class="form-select">

<option
value="Active"
<?= $user['status']=='Active'
? 'selected'
: '' ?>>

Active

</option>

<option
value="Inactive"
<?= $user['status']=='Inactive'
? 'selected'
: '' ?>>

Inactive

</option>

</select>

</div>

</div>

<hr>

<h5>Change Password</h5>

<p class="text-muted">

Leave blank if you do not want to change the password.

</p>

<div class="row">

<div class="col-md-6">

<label>New Password</label>

<input
type="password"
name="password"
class="form-control">

</div>

<div class="col-md-6">

<label>Confirm Password</label>

<input
type="password"
name="confirm_password"
class="form-control">

</div>

</div>

<hr>

<div class="d-flex justify-content-between">

<a
href="users.php"
class="btn btn-secondary">

<i class="fa-solid fa-arrow-left"></i>

Back

</a>

<button
type="submit"
class="btn btn-success">

<i class="fa-solid fa-floppy-disk"></i>

Update User

</button>

</div>

</form>

</div>

</div>

</div>

<script>

function toggleZone()
{
    let role =
    document.getElementById('role').value;

    let zone =
    document.getElementById('zone_div');

    if(role == 'zonal_director')
    {
        zone.style.display = 'block';
    }
    else
    {
        zone.style.display = 'none';
    }
}

document
.getElementById('role')
.addEventListener(
'change',
toggleZone
);

toggleZone();

</script>

<?php include '../includes/footer.php'; ?>
