<?php
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/session_check.php';
checkSession();
require_once __DIR__ . '/includes/activity_logger.php';

$pageTitle = 'Editar Plantilla';

$templateId = $_GET['id'] ?? null;
$template = null;
$error = '';

if (!$templateId) {
    header('Location: recurrentes.php');
    exit;
}

try {
    $pdo = getDbConnection();
    $stmt = $pdo->prepare("SELECT * FROM recurrent_messages WHERE id = ?");
    $stmt->execute([$templateId]);
    $template = $stmt->fetch();
} catch (Exception $e) {
    $error = $e->getMessage();
}

if (!$template) {
    echo "Plantilla no encontrada";
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'];
    $messageContent = $_POST['message_content'];
    $telegramCommand = $_POST['telegram_command'] ?? null;
    
    $stmt = $pdo->prepare("
        UPDATE recurrent_messages 
        SET name = ?, message_content = ?, telegram_command = ?, updated_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([$name, $messageContent, $telegramCommand, $templateId]);
    
    logActivity(getCurrentUserId(), 'update_template', "Plantilla actualizada: $name");
    header('Location: recurrentes.php?updated=1');
    exit;
}

require_once __DIR__ . '/templates/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-pencil"></i> Editar Plantilla</h2>
</div>

<?php if ($error): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<form method="POST">
    <div class="card border-0 shadow-sm">
        <div class="card-body">
            <div class="mb-3">
                <label class="form-label">Nombre</label>
                <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($template['name']) ?>" required>
            </div>
            
            <div class="mb-3">
                <label class="form-label">Comando de Telegram (sin #)</label>
                <input type="text" name="telegram_command" class="form-control" value="<?= htmlspecialchars($template['telegram_command'] ?? '') ?>" placeholder="ejemplo">
            </div>
            
            <div class="mb-3">
                <label class="form-label">Contenido</label>
                <textarea name="message_content" class="form-control" rows="10" required><?= htmlspecialchars($template['message_content']) ?></textarea>
                <small class="text-muted">Usa HTML básico: &lt;b&gt;, &lt;i&gt;, &lt;u&gt;, &lt;a href&gt;, &lt;img&gt;</small>
            </div>
            
            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-save"></i> Guardar
                </button>
                <a href="recurrentes.php" class="btn btn-outline-secondary">Cancelar</a>
            </div>
        </div>
    </div>
</form>

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