<?php

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

/*
|--------------------------------------------------------------------------
| Only Admin Access
|--------------------------------------------------------------------------
*/
if ($_SESSION['role'] != 'admin')
{
    die("Access Denied");
}

$message = '';

if (isset($_POST['create_user']))
{
    $fullname  = trim($_POST['fullname']);
    $email     = trim($_POST['email']);
    $phone     = trim($_POST['phone']);
    $workplace = trim($_POST['workplace']);
    $role      = $_POST['role'];

    $password         = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];

    if ($password != $confirm_password)
    {
        $message = "Passwords do not match";
    }
    else
    {
        /*
        |--------------------------------------------------------------------------
        | Check Email Exists
        |--------------------------------------------------------------------------
        */
        $check = mysqli_prepare(
            $conn,
            "SELECT id FROM users WHERE email = ?"
        );

        mysqli_stmt_bind_param($check, "s", $email);
        mysqli_stmt_execute($check);

        $result = mysqli_stmt_get_result($check);

        if (mysqli_num_rows($result) > 0)
        {
            $message = "Email already exists";
        }
        else
        {
            /*
            |--------------------------------------------------------------------------
            | Insert User
            |--------------------------------------------------------------------------
            */
            $hash = password_hash($password, PASSWORD_DEFAULT);

            $stmt = mysqli_prepare(
                $conn,
                "INSERT INTO users
                (fullname, email, phone, workplace, password, role)
                VALUES (?, ?, ?, ?, ?, ?)"
            );

            mysqli_stmt_bind_param(
                $stmt,
                "ssssss",
                $fullname,
                $email,
                $phone,
                $workplace,
                $hash,
                $role
            );

            if (mysqli_stmt_execute($stmt))
            {
                echo "
                <script>
                    alert('User Created Successfully');
                    window.location='users.php';
                </script>
                ";
                exit;
            }
            else
            {
                $message = "Error creating user";
            }
        }
    }
}

include '../includes/header.php';
include '../includes/navbar.php';
?>

<div class="container mt-5">

    <div class="row justify-content-center">

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

            <div class="card shadow">

                <div class="card-header bg-primary text-white">
                    Add New User (Admin)
                </div>

                <div class="card-body">

                    <?php if ($message != '') { ?>
                        <div class="alert alert-danger">
                            <?= $message ?>
                        </div>
                    <?php } ?>

                    <form method="POST">

                        <div class="mb-3">
                            <label>Full Name</label>
                            <input type="text" name="fullname" class="form-control" required>
                        </div>

                        <div class="mb-3">
                            <label>Email Address</label>
                            <input type="email" name="email" class="form-control" required>
                        </div>

                        <div class="mb-3">
                            <label>Phone Number</label>
                            <input type="text" name="phone" class="form-control" required>
                        </div>

                        <div class="mb-3">
                            <label>Workplace</label>
                            <input type="text" name="workplace" class="form-control" required>
                        </div>

                        <div class="mb-3">
                            <label>Password</label>
                            <input type="password" name="password" class="form-control" required>
                        </div>

                        <div class="mb-3">
                            <label>Confirm Password</label>
                            <input type="password" name="confirm_password" class="form-control" required>
                        </div>

                        <div class="mb-3">
                            <label>Role</label>
                            <select name="role" id="role" class="form-select" required>
                                <option value="user">User</option>
                                <option value="zonal_director">Zonal Director</option>
                                <option value="admin">Admin</option>
                            </select>

                            <div id="zone_div" style="display:none;">

                                <label class="mt-3">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($row = mysqli_fetch_assoc($zones))
                                    {
                                    ?>

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

                                    <?php } ?>

                                </select>

                            </div>

                        </div>

                        <button type="submit"
                                name="create_user"
                                class="btn btn-success w-100">
                                Create User
                        </button>

                    </form>

                </div>

            </div>

        </div>

    </div>

</div>

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

<script>

const role = document.getElementById('role');
const zone = document.getElementById('zone_div');

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

role.addEventListener('change', toggleZone);

toggleZone();

</script>