<?php
/**
 * Add / Edit committee
 */

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

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

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

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

    if (empty($errors)) {
        try {
            if ($isEdit) {
                $stmt = $pdo->prepare('UPDATE committees SET name = ?, description = ? WHERE id = ?');
                $stmt->execute([$name, $desc ?: null, $id]);
                header('Location: ' . BASE_PATH . '/committees?toast=' . urlencode('Committee updated.'));
            } else {
                $stmt = $pdo->prepare('INSERT INTO committees (name, description) VALUES (?, ?)');
                $stmt->execute([$name, $desc ?: null]);
                header('Location: ' . BASE_PATH . '/committees?toast=' . urlencode('Committee created.'));
            }
            exit;
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'Duplicate') !== false || strpos($e->getMessage(), 'UNIQUE') !== false) {
                $errors[] = 'A committee with that name already exists.';
            } else {
                throw $e;
            }
        }
    }
    $committee = ['name' => $name, 'description' => $desc];
}

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

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

<div class="header">
    <h1><?= $isEdit ? 'Edit Committee' : 'New Committee' ?></h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/committees" class="link-muted">← Committees</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<div class="form-card" style="max-width: 520px;">
    <form method="post">
        <div class="form-group">
            <label for="name">Committee name *</label>
            <input type="text" id="name" name="name" required autofocus
                   placeholder="e.g. Finance Committee"
                   value="<?= htmlspecialchars($committee['name'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label for="description">Description <span style="font-weight:400; color:var(--text-muted);">(optional)</span></label>
            <textarea id="description" name="description" rows="3"
                      placeholder="Brief description of the committee's purpose…"
                      style="width:100%; padding:0.5rem 0.75rem; border:1px solid var(--border); border-radius:6px; font-size:0.875rem; font-family:inherit; resize:vertical;"><?= htmlspecialchars($committee['description'] ?? '') ?></textarea>
        </div>
        <div class="form-actions">
            <button type="submit" class="btn"><?= $isEdit ? 'Update Committee' : 'Create Committee' ?></button>
            <a href="<?= BASE_PATH ?>/committees" class="btn btn-ghost">Cancel</a>
        </div>
    </form>
</div>

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