<?php
/**
 * Message templates – reusable SMS/email templates with placeholders
 * Placeholders: {member_name}, {event_title}, {event_date}, {event_time}, {date}, etc.
 */

/**
 * Ensure message_templates table exists (for existing installs).
 */
function ensureMessageTemplatesTable() {
    global $pdo;
    if (!isset($pdo)) return;
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS message_templates (
                id INT AUTO_INCREMENT PRIMARY KEY,
                name VARCHAR(100) NOT NULL,
                type ENUM('sms','email') NOT NULL DEFAULT 'email',
                subject VARCHAR(255) NULL,
                body TEXT NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                UNIQUE KEY (name)
            )
        ");
    } catch (PDOException $e) {
        // ignore
    }
}

/**
 * Get a template by id.
 * @return array|null { id, name, type, subject, body } or null
 */
function getTemplateById($id) {
    global $pdo;
    ensureMessageTemplatesTable();
    $stmt = $pdo->prepare('SELECT id, name, type, subject, body FROM message_templates WHERE id = ?');
    $stmt->execute([(int) $id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ?: null;
}

/**
 * Get a template by name.
 * @return array|null { id, name, type, subject, body } or null
 */
function getTemplateByName($name) {
    global $pdo;
    ensureMessageTemplatesTable();
    $stmt = $pdo->prepare('SELECT id, name, type, subject, body FROM message_templates WHERE name = ?');
    $stmt->execute([$name]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ?: null;
}

/**
 * List all templates.
 * @return array
 */
function getAllTemplates() {
    global $pdo;
    ensureMessageTemplatesTable();
    $stmt = $pdo->query('SELECT id, name, type, subject, body, updated_at FROM message_templates ORDER BY name');
    return $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
}

/**
 * Replace placeholders in a string.
 * @param string $text Subject or body
 * @param array $context e.g. ['member_name' => 'John', 'event_title' => 'Service']
 * @return string
 */
function replaceTemplatePlaceholders($text, array $context) {
    if ($text === null || $text === '') return $text;
    foreach ($context as $key => $value) {
        $text = str_replace('{' . $key . '}', (string) $value, $text);
    }
    return $text;
}

/**
 * Get default placeholder hints for the UI.
 * @return array [ 'member_name' => 'Member full name', ... ]
 */
function getTemplatePlaceholderHints() {
    return [
        'member_name' => 'Member full name',
        'event_title' => 'Event title',
        'event_date'  => 'Event date',
        'event_time'  => 'Event time',
        'date'        => 'Current or chosen date',
        'church_name' => 'Church name',
    ];
}
