<?php

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

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

$message = '';

if (isset($_POST['create_user']))
{
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) die('Invalid request.');
    $fullname  = trim($_POST['fullname']);
    $email     = trim($_POST['email']);
    $phone     = trim($_POST['phone']);
    $workplace = trim($_POST['workplace']);
    $role      = $_POST['role'];
    $zone_name = trim($_POST['zone_name'] ?? '');

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

    if (!filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($password) < 8)
    {
        $message = 'Enter a valid email address and a password of at least 8 characters.';
    }
    elseif (!in_array($role, ['admin', 'zonal_director', 'user'], true))
    {
        $message = 'Invalid user role.';
    }
    elseif ($role === 'zonal_director' && $zone_name === '')
    {
        $message = 'Select a zone for a zonal director.';
    }
    elseif ($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, zone_name, password, role)
                VALUES (?, ?, ?, ?, ?, ?, ?)"
            );

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

            if (mysqli_stmt_execute($stmt))
            {

                logActivity(
                    $conn,
                    'User Management',
                    'Create User',
                    'Created user "' .
                    $fullname .
                    '" (' .
                    $role .
                    ')'
                );

                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">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">

                        <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>
