<?php
/**
 * Add/Edit ministry - admin only
 */

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    if (empty($name)) $errors[] = 'Ministry name is required.';

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

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

<div class="header">
    <h1><?= $isEdit ? 'Edit Service Group' : 'Add Service Group' ?></h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/ministries" class="link-muted">← Service 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="form-card">
    <form method="post">
        <div class="form-group">
            <label for="name">Service group name</label>
            <input type="text" id="name" name="name" required placeholder="Church Choir"
                value="<?= htmlspecialchars($ministry['name'] ?? '') ?>">
        </div>
        <div class="form-actions">
            <button type="submit" class="btn"><?= $isEdit ? 'Update' : 'Add' ?> Service Group</button>
            <a href="<?= BASE_PATH ?>/ministries" class="btn btn-ghost">Cancel</a>
        </div>
    </form>
</div>

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