<?php
// STEP 2F-3 ADMIN PRAYER DYNAMIC

require_once __DIR__ . '/auth.php';

if (!function_exists('app_setting')) {
    function app_setting(PDO $pdo, string $key, string $default = ''): string {
        try {
            $stmt = $pdo->prepare("SELECT setting_value FROM app_settings WHERE setting_key = ? LIMIT 1");
            $stmt->execute([$key]);
            $value = $stmt->fetchColumn();
            return ($value !== false && $value !== null && $value !== '') ? (string)$value : $default;
        } catch (Throwable $e) {
            return $default;
        }
    }
}

$adminPrayerTitle = app_setting($pdo, 'admin_label_prayer', 'Manage Prayer Guide');

require_admin();

$pageTitle = $adminPrayerTitle;

$error = '';
$notice = '';

function pg_get_item($pdo, $id) {
    $stmt = $pdo->prepare("SELECT * FROM prayer_guides WHERE id = ? LIMIT 1");
    $stmt->execute([(int)$id]);
    $row = $stmt->fetch();
    return $row ? $row : null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $action = $_POST['action'] ?? '';
        $id = (int)($_POST['id'] ?? 0);

        if ($action === 'save') {
            $title = trim($_POST['title'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $image = trim($_POST['image_url'] ?? '');
            $sort = (int)($_POST['sort_order'] ?? 0);
            $active = isset($_POST['active']) ? 1 : 0;

            if ($title === '') {
                $error = 'Title is required.';
            } else {
                if ($id > 0) {
                    $stmt = $pdo->prepare("
                        UPDATE prayer_guides
                        SET title = ?, description = ?, content = ?, image_url = ?, sort_order = ?, active = ?
                        WHERE id = ?
                    ");
                    $stmt->execute([$title, $description, $description, $image, $sort, $active, $id]);
                    header('Location: admin_prayer.php?notice=updated');
                    exit;
                } else {
                    $stmt = $pdo->prepare("
                        INSERT INTO prayer_guides (title, description, content, image_url, sort_order, active)
                        VALUES (?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([$title, $description, $description, $image, $sort, $active]);
                    header('Location: admin_prayer.php?notice=added');
                    exit;
                }
            }
        }

        if ($action === 'toggle' && $id > 0) {
            $item = pg_get_item($pdo, $id);
            if ($item) {
                $newActive = empty($item['active']) ? 1 : 0;
                $stmt = $pdo->prepare("UPDATE prayer_guides SET active = ? WHERE id = ?");
                $stmt->execute([$newActive, $id]);
            }
            header('Location: admin_prayer.php?notice=updated');
            exit;
        }

        if ($action === 'delete' && $id > 0) {
            $stmt = $pdo->prepare("DELETE FROM prayer_guides WHERE id = ?");
            $stmt->execute([$id]);
            header('Location: admin_prayer.php?notice=deleted');
            exit;
        }

    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

if (!empty($_GET['notice'])) {
    $map = [
        'added' => 'Prayer guide added.',
        'updated' => 'Prayer guide updated.',
        'deleted' => 'Prayer guide deleted.'
    ];
    $notice = $map[$_GET['notice']] ?? '';
}

$editId = (int)($_GET['edit'] ?? 0);
$editItem = $editId > 0 ? pg_get_item($pdo, $editId) : null;

try {
    $items = $pdo->query("SELECT * FROM prayer_guides ORDER BY sort_order ASC, id DESC")->fetchAll();
} catch (Throwable $e) {
    $items = [];
    $error = $e->getMessage();
}

require_once __DIR__ . '/includes/header.php';

$editTitle = $editItem['title'] ?? '';
$editDescription = $editItem['description'] ?? ($editItem['content'] ?? '');
$editImage = $editItem['image_url'] ?? '';
$editSort = $editItem['sort_order'] ?? 0;
$editActive = $editItem ? !empty($editItem['active']) : true;
?>

<main>
<section class="section">
<div class="container">
<div class="panel">

<h1><?php echo h($adminPrayerTitle); ?></h1>
<p class="muted">Prayer Guide Editor v1.1 SAFE — Edit loads the guide into the editor below.</p>

<?php if ($error): ?>
    <div class="error"><?php echo h($error); ?></div>
<?php endif; ?>

<?php if ($notice): ?>
    <div class="notice"><?php echo h($notice); ?></div>
<?php endif; ?>

<div class="panel" style="margin-bottom:1rem;">
    <h2><?php echo h($adminPrayerTitle); ?></h2>

    <?php if ($editItem): ?>
        <div class="notice">
            Editing: <strong><?php echo h($editTitle); ?></strong>
        </div>
    <?php endif; ?>

    <form method="post">
        <input type="hidden" name="action" value="save">
        <input type="hidden" name="id" value="<?php echo h($editItem['id'] ?? 0); ?>">

        <label>Title</label>
        <input name="title" value="<?php echo h($editTitle); ?>" required>

        <label>Description</label>
        <textarea name="description"><?php echo h($editDescription); ?></textarea>

        <label>Image URL or Path</label>
        <input name="image_url" value="<?php echo h($editImage); ?>" placeholder="uploads/prayer/image.jpg">

        <label>Sort</label>
        <input name="sort_order" type="number" value="<?php echo h($editSort); ?>">

        <label>
            <input type="checkbox" name="active" <?php echo $editActive ? 'checked' : ''; ?> style="width:auto;">
            Active
        </label>

        <div class="btn-row">
            <button class="btn btn-primary" type="submit">
                <?php echo $editItem ? 'Save Changes' : 'Add'; ?>
            </button>

            <?php if ($editItem): ?>
                <a class="btn btn-secondary" href="admin_prayer.php">Cancel Edit</a>
            <?php endif; ?>
        </div>
    </form>
</div>

<div class="panel">
    <h2><?php echo h($adminPrayerTitle); ?></h2>

    <?php if (!$items): ?>
        <div class="notice">No prayer guides found.</div>
    <?php endif; ?>

    <div class="prayer-guide-list">
        <?php foreach ($items as $it): ?>
            <div class="card" style="margin-bottom:1rem;">
                <h3><?php echo h($it['title'] ?? 'Prayer Guide'); ?></h3>

                <p class="muted"><?php echo nl2br(h($it['description'] ?? ($it['content'] ?? ''))); ?></p>

                <?php if (!empty($it['image_url'])): ?>
                    <p class="muted" style="word-break:break-word;">
                        Image: <?php echo h($it['image_url']); ?>
                    </p>
                <?php endif; ?>

                <p class="muted">
                    Sort: <?php echo h($it['sort_order'] ?? 0); ?> |
                    Status: <?php echo !empty($it['active']) ? 'Active' : 'Hidden'; ?>
                </p>

                <div class="btn-row">
                    <a class="btn btn-secondary btn-small" href="admin_prayer.php?edit=<?php echo h($it['id']); ?>">Edit</a>

                    <form method="post" style="display:inline;">
                        <input type="hidden" name="action" value="toggle">
                        <input type="hidden" name="id" value="<?php echo h($it['id']); ?>">
                        <button class="btn btn-secondary btn-small" type="submit">
                            <?php echo !empty($it['active']) ? 'Hide' : 'Show'; ?>
                        </button>
                    </form>

                    <form method="post" style="display:inline;" onsubmit="return confirm('Delete this prayer guide?');">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?php echo h($it['id']); ?>">
                        <button class="btn btn-danger btn-small" type="submit">Delete</button>
                    </form>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

</div>
</div>
</section>
</main>

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