<?php
require_once "config.php";
require_once "auth.php";

// Only admin can access this page
requireAdmin();

$success = false;
$error = null;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = trim($_POST["name"]);
    $email = trim($_POST["email"]);
    $telefon = trim($_POST["telefon"] ?? '');
    $password = trim($_POST["password"]);
    $role = $_POST["role"];
    $komitent_id = !empty($_POST["komitent_id"]) ? (int)$_POST["komitent_id"] : null;
    
    if ($role === 'vozac' || $role === 'admin') {
        $komitent_id = null;
    }

    if (empty($name) || empty($email) || empty($password)) {
        $error = "Sva polja su obavezna.";
    } else if ($role === 'user' && empty($komitent_id)) {
        $error = "Komitent je obavezan za korisnike.";
    } else {
        $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $error = "Email adresa već postoji.";
        } else {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            
            if ($komitent_id === null) {
                $stmt = $conn->prepare("INSERT INTO users (name, email, telefon, password, role, komitent_id) VALUES (?, ?, ?, ?, ?, NULL)");
                $stmt->bind_param("sssss", $name, $email, $telefon, $hashed_password, $role);
            } else {
                $stmt = $conn->prepare("INSERT INTO users (name, email, telefon, password, role, komitent_id) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->bind_param("sssssi", $name, $email, $telefon, $hashed_password, $role, $komitent_id);
            }
            
            if ($stmt->execute()) {
                $success = true;
            } else {
                $error = "Greška prilikom kreiranja korisnika.";
            }
        }
    }
}

$stmt = $conn->prepare("SELECT id, naziv FROM komitenti ORDER BY naziv");
$stmt->execute();
$komitenti = $stmt->get_result();
?>

    <?php include "header.php"; ?>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <div class="card">
                    <div class="card-header">
                        <h2 class="mb-0">Novi korisnik</h2>
                    </div>
                    <div class="card-body">
                        <?php if ($success): ?>
                            <div class="alert alert-success">
                                Korisnik je uspešno kreiran.
                                <a href="users.php" class="alert-link">Povratak na listu korisnika</a>
                            </div>
                        <?php else: ?>
                            <?php if ($error): ?>
                                <div class="alert alert-danger"><?php echo $error; ?></div>
                            <?php endif; ?>

                            <form method="post">
                                <div class="mb-3">
                                    <label for="name" class="form-label">Ime i prezime</label>
                                    <input type="text" class="form-control" id="name" name="name" required>
                                </div>
                                <div class="mb-3">
                                    <label for="email" class="form-label">Email</label>
                                    <input type="email" class="form-control" id="email" name="email" required>
                                </div>
                                <div class="mb-3">
                                    <label for="telefon" class="form-label">Broj telefona</label>
                                    <input type="tel" class="form-control" id="telefon" name="telefon" placeholder="+381601234567">
                                </div>
                                <div class="mb-3">
                                    <label for="password" class="form-label">Lozinka</label>
                                    <input type="password" class="form-control" id="password" name="password" required>
                                </div>
                                <div class="mb-3">
                                    <label for="role" class="form-label">Uloga</label>
                                    <select class="form-select" id="role" name="role" required>
                                        <option value="user">Korisnik</option>
                                        <option value="vozac">Vozač</option>
                                        <?php if ($_SESSION['user']['role'] === 'admin'): ?>
                                            <option value="admin">Administrator</option>
                                        <?php endif; ?>
                                    </select>
                                </div>
                                <div class="mb-3" id="komitent-group">
                                    <label for="komitent_id" class="form-label">Komitent</label>
                                    <select class="form-select" id="komitent_id" name="komitent_id">
                                        <option value="">Izaberi komitenta</option>
                                        <?php while ($komitent = $komitenti->fetch_assoc()): ?>
                                            <option value="<?php echo $komitent['id']; ?>">
                                                <?php echo htmlspecialchars($komitent['naziv']); ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                    <div class="form-text">Obavezno za korisnike</div>
                                </div>
                                <div class="d-grid gap-2">
                                    <button type="submit" class="btn btn-primary"><i class="bi bi-person-plus me-1"></i>Kreiraj korisnika</button>
                                    <a href="users.php" class="btn btn-secondary"><i class="bi bi-x-circle me-1"></i>Otkaži</a>
                                </div>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const roleSelect = document.getElementById('role');
            const komitentGroup = document.getElementById('komitent-group');
            const komitentSelect = document.getElementById('komitent_id');

            function updateKomitentVisibility() {
                if (roleSelect.value === 'user') {
                    komitentGroup.style.display = 'block';
                    komitentSelect.setAttribute('required', 'required');
                } else {
                    komitentGroup.style.display = 'none';
                    komitentSelect.removeAttribute('required');
                    komitentSelect.value = '';
                }
            }

            roleSelect.addEventListener('change', updateKomitentVisibility);
            updateKomitentVisibility();
        });
    </script>
    <?php include 'footer.php'; ?> 