<?php
/**
 * Group add/edit form
 */

$isEdit = ($action === 'edit' && $id);
$group = null;
$errors = [];

if ($isEdit) {
    $stmt = $pdo->prepare('SELECT * FROM `groups` WHERE id = ?');
    $stmt->execute([$id]);
    $group = $stmt->fetch();
    if (!$group) {
        header('Location: ' . BASE_PATH . '/groups');
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');

    if (empty($name)) $errors[] = 'Group name is required.';

    if (empty($errors)) {
        if ($isEdit) {
            $stmt = $pdo->prepare('UPDATE `groups` SET name=?, description=? WHERE id=?');
            $stmt->execute([$name, $description, $id]);
        } else {
            $stmt = $pdo->prepare('INSERT INTO `groups` (name, description) VALUES (?, ?)');
            $stmt->execute([$name, $description]);
        }
        header('Location: ' . BASE_PATH . '/groups?toast=' . urlencode('Group saved successfully.'));
        exit;
    }

    $group = [
        'name' => $name,
        'description' => $description,
    ];
}

$pageTitle = $isEdit ? 'Edit Group' : 'Add Group';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="header">
    <h1><?= $isEdit ? 'Edit Group' : 'Add Group' ?></h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/groups">Back to Groups</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<?php if (!empty($errors)): ?>
    <div data-toast="error" data-toast-msg="<?= htmlspecialchars(implode(' ', $errors)) ?>" style="display:none"></div>
<?php endif; ?>

<div class="card">
    <form method="post">
        <div class="form-group">
            <label for="name">Group Name *</label>
            <input type="text" id="name" name="name" required
                value="<?= htmlspecialchars($group['name'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label for="description">Description</label>
            <textarea id="description" name="description"><?= htmlspecialchars($group['description'] ?? '') ?></textarea>
        </div>
        <button type="submit" class="btn"><?= $isEdit ? 'Update' : 'Add' ?> Group</button>
        <a href="<?= BASE_PATH ?>/groups" class="btn btn-secondary">Cancel</a>
    </form>
</div>

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