<?php
require_once '../includes/init.php';
require_role('admin');
$pdo = db();

$user = [
    'id' => '',
    'email' => '',
    'role' => 'client',
    'is_active' => 1,
    'client_id' => null
];
$is_new_user = true;
$pageTitle = 'Dodaj użytkownika';

if (isset($_GET['id'])) {
    $is_new_user = false;
    $pageTitle = 'Edytuj użytkownika';
    try {
        $stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
        $stmt->execute([$_GET['id']]);
        $user = $stmt->fetch();
        if (!$user) {
            die('Użytkownik nie znaleziony.');
        }
    } catch (PDOException $e) {
        die("Błąd bazy danych: " . $e->getMessage());
    }
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';
    $role = $_POST['role'] ?? 'client';
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $client_id = (in_array($role, ['client', 'supplier'])) ? ($_POST['client_id'] ?? null) : null;

    if (empty($email)) {
        $errors[] = 'Email jest wymagany.';
    }
    if ($is_new_user && empty($password)) {
        $errors[] = 'Hasło jest wymagane dla nowych użytkowników.';
    }

    try {
        $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ? AND id != ?');
        $stmt->execute([$email, $user['id']]);
        if ($stmt->fetch()) {
            $errors[] = 'Adres email jest już w użyciu.';
        }

        if (!$is_new_user && $user['role'] === 'admin' && (!$is_active || $role !== 'admin')) {
            $stmt = $pdo->query('SELECT COUNT(*) FROM users WHERE role = \'admin\' AND is_active = 1');
            $admin_count = $stmt->fetchColumn();
            $self_deactivation = $user['id'] === $_GET['id'];
            if ($admin_count <= 1 && $self_deactivation) {
                $errors[] = 'Nie można deaktywować lub zmienić roli ostatniego administratora.';
            }
        }

        if (in_array($role, ['client', 'supplier']) && empty($client_id)) {
            $errors[] = 'Firma klienta jest wymagana dla użytkownika typu Klient lub Dostawca.';
        }

        if (empty($errors)) {
            $pdo->beginTransaction();
            if ($is_new_user) {
                $password_hash = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare('INSERT INTO users (email, password_hash, role, is_active, client_id) VALUES (?, ?, ?, ?, ?)');
                $stmt->execute([$email, $password_hash, $role, $is_active, $client_id]);
            } else {
                if (!empty($password)) {
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare('UPDATE users SET email = ?, password_hash = ?, role = ?, is_active = ?, client_id = ? WHERE id = ?');
                    $stmt->execute([$email, $password_hash, $role, $is_active, $client_id, $_GET['id']]);
                } else {
                    $stmt = $pdo->prepare('UPDATE users SET email = ?, role = ?, is_active = ?, client_id = ? WHERE id = ?');
                    $stmt->execute([$email, $role, $is_active, $client_id, $_GET['id']]);
                }
            }
            $pdo->commit();
            header('Location: users.php');
            exit;
        }
    } catch (PDOException $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $errors[] = "Błąd bazy danych: " . $e->getMessage();
    }
}

try {
    $clients_stmt = $pdo->query('SELECT id, name FROM clients ORDER BY name');
    $clients = $clients_stmt->fetchAll();
} catch (PDOException $e) {
    die("Błąd bazy danych: " . $e->getMessage());
}
$page_title = $pageTitle;

?>
<?php require_once __DIR__ . '/../includes/html_head.php'; ?>
<body>
<?php include __DIR__ . '/menu.php'; ?>

<main class="container mt-4">
    <div class="card">
        <div class="card-header">
            <h1><?php echo $pageTitle; ?></h1>
        </div>
        <div class="card-body">
            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <?php foreach ($errors as $error): ?>
                        <p><?php echo htmlspecialchars($error); ?></p>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <form action="" method="post">
                <div class="mb-3">
                    <label for="email" class="form-label">E-mail</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="password" class="form-label">Hasło</label>
                    <input type="password" class="form-control" id="password" name="password" <?php if($is_new_user) echo 'required' ?> >
                    <?php if (!$is_new_user): ?>
                        <div class="form-text">Zostaw puste, aby zachować obecne hasło.</div>
                    <?php endif; ?>
                </div>
                <div class="mb-3">
                    <label for="role" class="form-label">Rola</label>
                    <select class="form-select" id="role" name="role" onchange="toggleClientDropdown()">
                        <option value="admin" <?php if($user['role'] === 'admin') echo 'selected'; ?>>Administrator</option>
                        <option value="handlowiec" <?php if($user['role'] === 'handlowiec') echo 'selected'; ?>>Handlowiec</option>
                        <option value="client" <?php if($user['role'] === 'client') echo 'selected'; ?>>Klient</option>
                        <option value="supplier" <?php if($user['role'] === 'supplier') echo 'selected'; ?>>Dostawca</option>
                    </select>
                </div>
                <div id="client-dropdown" class="mb-3" style="display: <?php echo (in_array($user['role'], ['client', 'supplier'])) ? 'block' : 'none'; ?>;">
                    <label for="client_id" class="form-label">Powiązana firma</label>
                    <select class="form-select" id="client_id" name="client_id">
                        <option value="">Wybierz firmę</option>
                        <?php foreach ($clients as $client): ?>
                            <option value="<?php echo $client['id']; ?>" <?php if(isset($user['client_id']) && $user['client_id'] == $client['id']) echo 'selected'; ?>><?php echo htmlspecialchars($client['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-check mb-3">
                    <input type="hidden" name="is_active" value="0">
                    <input class="form-check-input" type="checkbox" id="is_active" name="is_active" value="1" <?php if($user['is_active']) echo 'checked'; ?>>
                    <label class="form-check-label" for="is_active">Aktywny</label>
                </div>
                <button type="submit" class="btn btn-primary">Zapisz</button>
                <a href="users.php" class="btn btn-secondary">Anuluj</a>
            </form>
            <script>
                function toggleClientDropdown() {
                    var role = document.getElementById('role').value;
                    var clientDropdown = document.getElementById('client-dropdown');
                    if (role === 'client' || role === 'supplier') {
                        clientDropdown.style.display = 'block';
                    } else {
                        clientDropdown.style.display = 'none';
                    }
                }
            </script>
        </div>
    </div>
</main>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
</body>
</html>