<?php
include '../config/db.php';
session_start();
if (!isset($_SESSION['login']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.php");
    exit;
}

if ($_POST) {
    $username = $_POST['username'];
    $password = sha1($_POST['password']);
    $role = $_POST['role'];

    $cek = mysqli_query($conn, "SELECT * FROM petugas WHERE username='$username'");
    if (mysqli_num_rows($cek) > 0) {
        $error = "Username sudah digunakan!";
    } else {
        mysqli_query($conn, "INSERT INTO petugas (username, password, role) VALUES ('$username', '$password', '$role')");
        $success = "User berhasil ditambahkan.";
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Register Petugas</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<style>
        body {
            background: linear-gradient(to right, #5cb8ff, #2d9fff);
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .register-card {
            width: 100%;
            max-width: 450px;
            padding: 2rem;
            border-radius: 15px;
            background-color: white;
            box-shadow: 0 0 15px rgba(0,0,0,0.15);
        }
        .register-title {
            font-weight: bold;
            text-align: center;
            margin-bottom: 1.5rem;
            color: #0d6efd;
        }
    </style>
<body class="bg-light">
<div class="container mt-5 col-md-5 bg-white p-4 rounded shadow">
    <h4>Register Petugas Baru</h4>
    <?php if (isset($error)) echo "<div class='alert alert-danger'>$error</div>"; ?>
    <?php if (isset($success)) echo "<div class='alert alert-success'>$success</div>"; ?>
    <form method="POST">
        <div class="mb-3"><label>Username</label><input name="username" required class="form-control"></div>
        <div class="mb-3"><label>Password</label><input type="password" name="password" required class="form-control"></div>
        <div class="mb-3">
            <label>Role</label>
            <select name="role" class="form-control">
                <option value="operator">Operator</option>
                <option value="admin">Admin</option>
            </select>
        </div>
        <button class="btn btn-success">Register</button>
        <a href="../index.php" class="btn btn-secondary">Kembali</a>
    </form>
</div>
</body>
</html>