<?php
include 'config.php';
checkAuth();

if (!hasPermission('admin')) {
    header('Location: dashboard.php');
    exit();
}

$editMode = false;
$userData = [];
$message = '';

if (isset($_GET['edit'])) {
    $editMode = true;
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([intval($_GET['edit'])]);
    $userData = $stmt->fetch();
    
    if (!$userData) {
        header('Location: users.php');
        exit();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = sanitizeInput($_POST['username']);
    $full_name = sanitizeInput($_POST['full_name']);
    $role = $_POST['role'];
    
    if ($editMode) {
        if (!empty($_POST['password'])) {
            $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET username = ?, full_name = ?, role = ?, password = ? WHERE id = ?");
            $stmt->execute([$username, $full_name, $role, $password, $userData['id']]);
        } else {
            $stmt = $pdo->prepare("UPDATE users SET username = ?, full_name = ?, role = ? WHERE id = ?");
            $stmt->execute([$username, $full_name, $role, $userData['id']]);
        }
        $message = "✅ Пользователь успешно обновлен!";
    } else {
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        try {
            $stmt = $pdo->prepare("INSERT INTO users (username, password, role, full_name) VALUES (?, ?, ?, ?)");
            $stmt->execute([$username, $password, $role, $full_name]);
            $message = "✅ Пользователь успешно создан!";
        } catch (PDOException $e) {
            $message = "❌ Ошибка: Имя пользователя уже существует!";
        }
    }
    
    $userData = $_POST;
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $editMode ? '✏️ Редактирование' : '➕ Добавление'; ?> пользователя - Агротопливо</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="dashboard">
        <?php include 'sidebar.php'; ?>
        
        <main class="content">
            <header class="content-header">
                <h1><?php echo $editMode ? '✏️ Редактирование пользователя' : '➕ Добавление пользователя'; ?></h1>
                <a href="users.php" class="btn btn-secondary">← Назад к списку</a>
            </header>
            
            <?php if($message): ?>
                <div class="alert <?php echo strpos($message, '❌') !== false ? 'error' : 'success'; ?>"><?php echo $message; ?></div>
            <?php endif; ?>
            
            <div class="card">
                <div class="card-body">
                    <form method="POST" class="form">
                        <div class="form-row">
                            <div class="form-group">
                                <label>👤 Имя пользователя *</label>
                                <input type="text" name="username" value="<?php echo $userData['username'] ?? ''; ?>" required>
                            </div>
                            
                            <div class="form-group">
                                <label>👤 ФИО</label>
                                <input type="text" name="full_name" value="<?php echo $userData['full_name'] ?? ''; ?>">
                            </div>
                        </div>
                        
                        <div class="form-row">
                            <div class="form-group">
                                <label>🔑 <?php echo $editMode ? 'Новый пароль' : 'Пароль *'; ?></label>
                                <input type="password" name="password" <?php echo $editMode ? '' : 'required'; ?>>
                                <?php if($editMode): ?>
                                    <small>Оставьте пустым, если не хотите менять пароль</small>
                                <?php endif; ?>
                            </div>
                            
                            <div class="form-group">
                                <label>🎭 Роль *</label>
                                <select name="role" required>
                                    <option value="refueler" <?php echo ($userData['role'] ?? '') == 'refueler' ? 'selected' : ''; ?>>⛽ Заправщик</option>
                                    <option value="engineer" <?php echo ($userData['role'] ?? '') == 'engineer' ? 'selected' : ''; ?>>🔧 Инженер</option>
                                    <option value="admin" <?php echo ($userData['role'] ?? '') == 'admin' ? 'selected' : ''; ?>>👑 Администратор</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary">
                                <?php echo $editMode ? '💾 Сохранить изменения' : '➕ Создать пользователя'; ?>
                            </button>
                            <a href="users.php" class="btn btn-secondary">Отмена</a>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>
    
    <script src="js/script.js"></script>
</body>
</html>