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

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

$success = false;
$error = null;
$user = null;

if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    
    $stmt = $conn->prepare("SELECT id, name, email, telefon, role, komitent_id FROM users WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        header("Location: users.php");
        exit;
    }
    
    $user = $result->fetch_assoc();
}

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

    if (empty($name) || empty($email)) {
        $error = "Ime i email su obavezna polja.";
    } else {
        $stmt = $conn->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
        $stmt->bind_param("si", $email, $id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $error = "Email adresa već postoji.";
        } else {
            if (!empty($password)) {
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                if ($komitent_id === null) {
                    $stmt = $conn->prepare("UPDATE users SET name = ?, email = ?, telefon = ?, password = ?, role = ?, komitent_id = NULL WHERE id = ?");
                    $stmt->bind_param("sssssi", $name, $email, $telefon, $hashed_password, $role, $id);
                } else {
                    $stmt = $conn->prepare("UPDATE users SET name = ?, email = ?, telefon = ?, password = ?, role = ?, komitent_id = ? WHERE id = ?");
                    $stmt->bind_param("sssssii", $name, $email, $telefon, $hashed_password, $role, $komitent_id, $id);
                }
            } else {
                if ($komitent_id === null) {
                    $stmt = $conn->prepare("UPDATE users SET name = ?, email = ?, telefon = ?, role = ?, komitent_id = NULL WHERE id = ?");
                    $stmt->bind_param("ssssi", $name, $email, $telefon, $role, $id);
                } else {
                    $stmt = $conn->prepare("UPDATE users SET name = ?, email = ?, telefon = ?, role = ?, komitent_id = ? WHERE id = ?");
                    $stmt->bind_param("ssssii", $name, $email, $telefon, $role, $komitent_id, $id);
                }
            }
            
            if ($stmt->execute()) {
                $success = true;
            } else {
                $error = "Greška prilikom ažuriranja 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">Izmena korisnika</h2>
                    </div>
                    <div class="card-body">
                        <?php if ($success): ?>
                            <div class="alert alert-success">
                                Korisnik je uspešno ažuriran.
                                <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">
                                <input type="hidden" name="id" value="<?php echo $user['id']; ?>">
                                
                                <div class="mb-3">
                                    <label for="name" class="form-label">Ime i prezime</label>
                                    <input type="text" class="form-control" id="name" name="name" value="<?php echo htmlspecialchars($user['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" value="<?php echo htmlspecialchars($user['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" value="<?php echo htmlspecialchars($user['telefon'] ?? ''); ?>" placeholder="+381601234567">
                                </div>
                                
                                <div class="mb-3">
                                    <label for="password" class="form-label">Nova lozinka (ostavite prazno ako ne želite da je promenite)</label>
                                    <input type="password" class="form-control" id="password" name="password">
                                </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" <?php echo $user['role'] === 'user' ? 'selected' : ''; ?>>Korisnik</option>
                                        <option value="vozac" <?php echo $user['role'] === 'vozac' ? 'selected' : ''; ?>>Vozač</option>
                                        <option value="admin" <?php echo $user['role'] === 'admin' ? 'selected' : ''; ?>>Administrator</option>
                                    </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 $user['komitent_id'] == $komitent['id'] ? 'selected' : ''; ?>>
                                                <?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-floppy me-1"></i>Sačuvaj izmene</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'; ?> 