<?php
session_start();

// Samo admin može dodavati korisnike
if (!isset($_SESSION['uloga']) || $_SESSION['uloga'] !== 'admin') {
    exit("Pristup odbijen.");
}

$conn = new mysqli("localhost", "carsfory_locis", "8QYP2!S?ONk1HQ5_", "carsfory_locis");
$poruka = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $naziv = trim($_POST["naziv"]);
    $korisnicko_ime = trim($_POST["korisnicko_ime"]);
    $lozinka = $_POST["lozinka"];
    $uloga = $_POST["uloga"];

    if (!$naziv || !$korisnicko_ime || !$lozinka || !$uloga) {
        $poruka = "Sva polja su obavezna!";
    } else {
        // Provjeri postoji li korisničko ime
        $stmt = $conn->prepare("SELECT id FROM poslovnice WHERE korisnicko_ime = ?");
        $stmt->bind_param("s", $korisnicko_ime);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            $poruka = "Korisničko ime već postoji!";
        } else {
            $hash = password_hash($lozinka, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("INSERT INTO poslovnice (naziv, korisnicko_ime, lozinka, uloga) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssss", $naziv, $korisnicko_ime, $hash, $uloga);
            if ($stmt->execute()) {
                $poruka = "✅ Korisnik uspješno dodan!";
            } else {
                $poruka = "Greška prilikom dodavanja korisnika.";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Dodaj korisnika</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container mt-5">

  <h3 class="mb-4">➕ Dodaj novog korisnika</h3>

  <?php if ($poruka): ?>
    <div class="alert alert-info"><?= htmlspecialchars($poruka) ?></div>
  <?php endif; ?>

  <form method="POST" class="bg-white p-4 rounded shadow-sm">
    <div class="mb-3">
      <label for="naziv" class="form-label">Naziv poslovnice</label>
      <input type="text" name="naziv" id="naziv" class="form-control" required>
    </div>
    <div class="mb-3">
      <label for="korisnicko_ime" class="form-label">Korisničko ime</label>
      <input type="text" name="korisnicko_ime" id="korisnicko_ime" class="form-control" required>
    </div>
    <div class="mb-3">
      <label for="lozinka" class="form-label">Lozinka</label>
      <input type="password" name="lozinka" id="lozinka" class="form-control" required>
    </div>
    <div class="mb-3">
      <label for="uloga" class="form-label">Uloga</label>
      <select name="uloga" id="uloga" class="form-select" required>
        <option value="najmovi">Najmovi</option>
        <option value="kazne">Kazne</option>
        <option value="admin">Admin</option>
        <option value="poslovnica">Poslovnica</option>
      </select>
    </div>
    <button class="btn btn-success">Dodaj korisnika</button>
    <a href="admin.php" class="btn btn-secondary ms-2">Natrag</a>
  </form>
</div>
</body>
</html>
