( ′∀`)σ≡σ☆))Д′)レ(゚∀゚;)ヘ=З=З=Зε≡(ノ´_ゝ`)ノ HEX
HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux mail.thebrand.ai 6.8.0-107-generic #107-Ubuntu SMP PREEMPT_DYNAMIC Fri Mar 13 19:51:50 UTC 2026 x86_64
User: www-data (33)
PHP: 8.3.6
Disabled: NONE
Upload Files
File: /var/www/html/tmpr/../tmpr/..//n8nphp/index.php
<?php
session_start();
// N8N PHP Dashboard (standalone)
// URL: http://localhost/n8nphp and deployable to https://thebrand.ai/n8nphp

require __DIR__ . '/lib/N8nHttp.php';
$appCfg = @include __DIR__ . '/config/app.php';
$authCfg = is_array($appCfg) && isset($appCfg['auth']) ? $appCfg['auth'] : ['username' => 'admin'];
if (empty($_SESSION['auth'])) {
    header('Location: auth.php');
    exit;
}
$px = @include __DIR__ . '/config.php';
$cfg = n8n_config();
$tools = $cfg['tools'] ?? [
    'ProposalX' => 'proposalx',
    'PitchX' => 'pitchx',
    'ContractX' => 'contractx',
    'DeepX' => 'deepx',
    'StrategyX' => 'strategyx',
];
// Hero content per tool
$toolHeroes = [
    'ProposalX' => [
        'title' => 'ProposalX',
        'icon' => 'fa-solid fa-file-signature',
        'subtitle' => 'Generate persuasive, on-brand proposals via a two-step flow.',
        'bullets' => [
            'Start with prompt, tone, brand voice, audience, CTA.',
            'Answer auto-generated questions to tailor the proposal.',
            'Depth and breadth control for scope and coverage.',
        ],
    ],
    'PitchX' => [
        'title' => 'PitchX',
        'icon' => 'fa-solid fa-chart-line',
        'subtitle' => 'Craft persuasive pitch outlines and slide content.',
        'bullets' => [
            'Define audience and key message to guide structure.',
            'Use tone, brand voice, CTA for consistent delivery.',
            'Generates content via n8n webhook.',
        ],
    ],
    'ContractX' => [
        'title' => 'ContractX',
        'icon' => 'fa-solid fa-file-contract',
        'subtitle' => 'Draft agreement templates and key clauses fast.',
        'bullets' => [
            'Capture parties, term, amount, and constraints.',
            'Formal tone and brand voice ensure professional style.',
            'Outputs via webhook for downstream processing.',
        ],
    ],
    'DeepX' => [
        'title' => 'DeepX',
        'icon' => 'fa-solid fa-magnifying-glass',
        'subtitle' => 'Research topics and synthesize insights at depth.',
        'bullets' => [
            'Provide topic, sources, and desired depth.',
            'Tone and voice keep summaries on-brand.',
            'Returns findings via webhook.',
        ],
    ],
    'StrategyX' => [
        'title' => 'StrategyX',
        'icon' => 'fa-solid fa-compass',
        'subtitle' => 'Develop GTM strategies and channel plans.',
        'bullets' => [
            'Set objective, market, and channels.',
            'Tone and voice to match stakeholder expectations.',
            'Generates strategic recommendations via webhook.',
        ],
    ],
];
// Selected tool via query string
$toolKeys = array_keys($tools);
$selectedTool = (isset($_GET['tool']) && isset($tools[$_GET['tool']])) ? $_GET['tool'] : (count($toolKeys) ? $toolKeys[0] : null);
// Simple landing page route
$page = strtolower($_GET['page'] ?? '');

// Actions
$action = $_POST['action'] ?? null;
$message = null;
$result = null;

if ($action === 'activate') {
    $id = trim($_POST['workflow_id'] ?? '');
    if ($id) {
        $result = n8n_activate_workflow($id);
        $message = $result['status'] === 200 ? "Workflow {$id} activated" : ($result['error'] ?? 'Activation failed');
    }
} elseif ($action === 'deactivate') {
    $id = trim($_POST['workflow_id'] ?? '');
    if ($id) {
        $result = n8n_deactivate_workflow($id);
        $message = $result['status'] === 200 ? "Workflow {$id} deactivated" : ($result['error'] ?? 'Deactivation failed');
    }
} elseif ($action === 'trigger_webhook') {
    $path = trim($_POST['webhook_path'] ?? '');
    $payloadStr = $_POST['webhook_payload'] ?? '{}';
    $method = $_POST['webhook_method'] ?? 'POST';
    $payload = json_decode($payloadStr, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        $message = 'Invalid JSON payload';
    } else {
        $result = n8n_trigger_webhook($path, $payload, $method);
        $message = $result['status'] >= 200 && $result['status'] < 300 ? 'Webhook triggered' : ($result['error'] ?? 'Webhook failed');
    }
} elseif ($action === 'execution_status') {
    $id = trim($_POST['execution_id'] ?? '');
    if ($id) {
        $result = n8n_execution_status($id, true);
        $message = $result['status'] >= 200 && $result['status'] < 300 ? 'Execution fetched' : ($result['error'] ?? 'Fetch failed');
    }
} elseif ($action === 'run_tool') {
    $toolKey = trim($_POST['tool_key'] ?? '');
    $method = 'POST';
    if ($toolKey && isset($tools[$toolKey])) {
        $path = $tools[$toolKey];
        // Build payload from form fields
        $payload = ['tool' => $toolKey, 'source' => 'dashboard'];
        switch ($toolKey) {
            case 'ProposalX':
                $payload += [
                    'title' => trim($_POST['title'] ?? ''),
                    'client' => trim($_POST['client'] ?? ''),
                    'scope' => trim($_POST['scope'] ?? ''),
                    'due_date' => trim($_POST['due_date'] ?? ''),
                ];
                break;
            case 'PitchX':
                $payload += [
                    'deck_name' => trim($_POST['deck_name'] ?? ''),
                    'audience' => trim($_POST['audience'] ?? ''),
                    'key_message' => trim($_POST['key_message'] ?? ''),
                ];
                break;
            case 'ContractX':
                $payload += [
                    'party_a' => trim($_POST['party_a'] ?? ''),
                    'party_b' => trim($_POST['party_b'] ?? ''),
                    'term' => trim($_POST['term'] ?? ''),
                    'amount' => trim($_POST['amount'] ?? ''),
                ];
                break;
            case 'DeepX':
                $payload += [
                    'topic' => trim($_POST['topic'] ?? ''),
                    'sources' => trim($_POST['sources'] ?? ''),
                    'depth' => trim($_POST['depth'] ?? 'deep'),
                ];
                break;
            case 'StrategyX':
                $payload += [
                    'objective' => trim($_POST['objective'] ?? ''),
                    'market' => trim($_POST['market'] ?? ''),
                    'channels' => trim($_POST['channels'] ?? ''),
                ];
                break;
        }
        // Common copywriting controls
        $payload += [
            'tone' => trim($_POST['tone'] ?? ''),
            'brand_voice' => trim($_POST['brand_voice'] ?? ''),
            'cta' => trim($_POST['cta'] ?? ''),
            'keywords' => trim($_POST['keywords'] ?? ''),
        ];
        $result = n8n_trigger_webhook($path, $payload, $method);
        $message = $result['status'] >= 200 && $result['status'] < 300 ? ($toolKey . ' triggered') : ($result['error'] ?? ($toolKey . ' failed'));
    } else {
        $message = 'Unknown tool selected';
    }
}
// ProposalX two-step actions
elseif ($action === 'proposalx_start') {
    $prompt = trim($_POST['prompt'] ?? '');
    $depth = (int)($_POST['depth'] ?? 1);
    $breadth = (int)($_POST['breadth'] ?? 2);
    $tone = trim($_POST['tone'] ?? 'Professional');
    $brandVoice = trim($_POST['brand_voice'] ?? '');
    $audience = trim($_POST['audience'] ?? '');
    $objectives = trim($_POST['objectives'] ?? '');
    $cta = trim($_POST['cta'] ?? '');
    $keywords = trim($_POST['keywords'] ?? '');
    $payload = [
        'prompt' => $prompt,
        'depth' => $depth,
        'breadth' => $breadth,
        'tone' => $tone,
        'brand_voice' => $brandVoice,
        'audience' => $audience,
        'objectives' => $objectives,
        'cta' => $cta,
        'keywords' => $keywords,
    ];
    $path = 'webhook/proposal/start';
    $result = n8n_trigger_webhook($path, $payload, 'POST');
    $message = $result['status'] >= 200 && $result['status'] < 300 ? 'ProposalX questions generated' : ($result['error'] ?? 'ProposalX start failed');
}
elseif ($action === 'proposalx_answers') {
    $requestId = trim($_POST['request_id'] ?? '');
    $prompt = trim($_POST['prompt'] ?? '');
    $depth = (int)($_POST['depth'] ?? 1);
    $breadth = (int)($_POST['breadth'] ?? 2);
    $tone = trim($_POST['tone'] ?? 'Professional');
    $brandVoice = trim($_POST['brand_voice'] ?? '');
    $audience = trim($_POST['audience'] ?? '');
    $objectives = trim($_POST['objectives'] ?? '');
    $cta = trim($_POST['cta'] ?? '');
    $keywords = trim($_POST['keywords'] ?? '');
    $answers = null;
    if (isset($_POST['answers']) && is_array($_POST['answers'])) {
        // Answers provided via structured fields
        $answers = array_values($_POST['answers']);
    } else {
        // Fallback to JSON payload
        $answersStr = $_POST['answers_json'] ?? '[]';
        $answers = json_decode($answersStr, true);
        if (json_last_error() !== JSON_ERROR_NONE || !is_array($answers)) {
            $message = 'Invalid answers JSON';
            $answers = null;
        }
    }
    if ($answers !== null) {
        $payload = [
            'request_id' => $requestId,
            'prompt' => $prompt,
            'depth' => $depth,
            'breadth' => $breadth,
            'answers' => $answers,
            'tone' => $tone,
            'brand_voice' => $brandVoice,
            'audience' => $audience,
            'objectives' => $objectives,
            'cta' => $cta,
            'keywords' => $keywords,
        ];
        $path = 'webhook/proposal/answers';
        $result = n8n_trigger_webhook($path, $payload, 'POST');
        $message = $result['status'] >= 200 && $result['status'] < 300 ? 'ProposalX answers submitted' : ($result['error'] ?? 'ProposalX answers failed');
    }
}

// Base data
$health = n8n_health_check();
$workflows = n8n_list_workflows(['limit' => 25]);
$workflowItems = [];
if (!empty($workflows['data'])) {
    $data = $workflows['data'];
    $workflowItems = $data['data'] ?? $data; // handle {data: [...]} or array
}

function h($str) { return htmlspecialchars((string)$str, ENT_QUOTES, 'UTF-8'); }

?><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Strategy & Content Studio</title>
    <link rel="stylesheet" href="assets/styles.css">
    <script>
        function setWorkflow(id, name) {
            document.getElementById('workflow_id').value = id;
            document.getElementById('workflow_name').textContent = name || id;
        }
        function setExecution(id) {
            document.getElementById('execution_id').value = id;
        }
        function applyTemplateTo(inputId, template) {
            var el = document.getElementById(inputId);
            if (el) { el.value = template; }
        }
    </script>
    </head>
<body>
<header>
    <h1>Strategy & Content Studio</h1>
    <div style="float:right; font-size:14px;">
        <span style="opacity:.85; margin-right:10px;">Signed in as <?php echo htmlspecialchars($_SESSION['name'] ?? ($_SESSION['user_email'] ?? 'user'), ENT_QUOTES, 'UTF-8'); ?></span>
        <a href="logout.php" style="color:#fff; text-decoration:none; border:1px solid #2a3447; padding:6px 10px; border-radius:8px; background:#182235;">Logout</a>
    </div>
</header>
<div class="layout">
    <aside>
        <nav class="nav" style="margin-bottom:12px;">
            <?php $homeActive = ($page === 'home') ? 'active' : ''; ?>
            <a class="<?php echo $homeActive; ?>" href="?page=home">Home</a>
            <a href="test.php">Test Harness</a>
        </nav>
        <h2 style="color:#f9fafb; font-size:18px; margin-top:0;">Tools</h2>
        <nav class="nav">
            <?php foreach ($tools as $label => $path): ?>
                <?php $active = ($label === $selectedTool) ? 'active' : ''; ?>
                <a class="<?php echo $active; ?>" href="?tool=<?php echo urlencode($label); ?>"><?php echo h($label); ?></a>
            <?php endforeach; ?>
        </nav>
        <div style="margin-top:12px; font-size:12px; color:#9ca3af;">Webhook base: <?php echo h($cfg['webhook_base_url']); ?></div>
    </aside>
    <div class="container">
    <?php if ($page === 'home'): ?>
        <div class="card" style="margin-bottom:16px;">
            <div class="hero hero-aws">
                <div class="title">Strategy & Content Studio</div>
                <div class="subtitle">Plan, create, and launch persuasive strategies and content powered by n8n workflows.</div>
                <div class="cta-group">
                    <a class="button primary" href="?tool=ProposalX">Start with ProposalX</a>
                    <a class="button secondary" href="?tool=StrategyX">Explore StrategyX</a>
                </div>
                <ul class="bullets" style="margin-top:12px;">
                    <li>Generate proposals, pitches, contracts, and strategic narratives in minutes.</li>
                    <li>Control tone, brand voice, audience, CTA, and depth for consistent outputs.</li>
                    <li>Operate with visibility: health checks, workflow status, and webhook triggers.</li>
                </ul>
            </div>
        </div>

        <div class="grid" style="margin-bottom:16px;">
            <div class="card">
                <h3>ProposalX</h3>
                <p>Create persuasive, on-brand proposals with guided prompts and Q&A.</p>
                <a href="?tool=ProposalX" class="button">Open ProposalX</a>
            </div>
            <div class="card">
                <h3>PitchX</h3>
                <p>Outline slide content and pitch narratives tailored to your audience.</p>
                <a href="?tool=PitchX" class="button">Open PitchX</a>
            </div>
            <div class="card">
                <h3>ContractX</h3>
                <p>Draft contract language and scope summaries from structured inputs.</p>
                <a href="?tool=ContractX" class="button">Open ContractX</a>
            </div>
            <div class="card">
                <h3>StrategyX</h3>
                <p>Develop GTM plans, channel strategies, and stakeholder-aligned narratives.</p>
                <a href="?tool=StrategyX" class="button">Open StrategyX</a>
            </div>
            <div class="card">
                <h3>DeepX</h3>
                <p>Expand research, trends, and insights with structured synthesis.</p>
                <a href="?tool=DeepX" class="button">Open DeepX</a>
            </div>
        </div>

        <div class="grid">
            <div class="card">
                <h3>How it works</h3>
                <ol style="margin:0 0 8px 18px;">
                    <li>Pick a workflow from the left.</li>
                    <li>Describe your goal, audience, tone, and constraints.</li>
                    <li>Trigger the webhook; monitor status and results.</li>
                    <li>Iterate with templates and structured Q&A.</li>
                </ol>
                <div class="config">Secure, session-based access. Auth via internal users database.</div>
            </div>
            <div class="card">
                <h3>Why it’s better</h3>
                <ul class="bullets">
                    <li>Structured prompts produce sharper, on-brand content.</li>
                    <li>Consistent voice via templates and tone controls.</li>
                    <li>Observable operations: health, status, and webhook insights.</li>
                </ul>
            </div>
        </div>
    <?php endif; ?>
    <div class="card">
        <h2><?php echo h($selectedTool ?: 'Tool'); ?> UI</h2>
        <?php if ($selectedTool): ?>
            <div class="container">
            <?php if ($selectedTool === 'ProposalX'): ?>
                <?php $hero = $toolHeroes['ProposalX'] ?? null; if ($hero): ?>
                <div class="hero hero-aws">
                    <div class="title"><?php echo h($hero['title']); ?></div>
                    <div class="subtitle"><?php echo h($hero['subtitle']); ?></div>
                    <?php if (!empty($hero['bullets'])): ?>
                    <ul class="bullets">
                        <?php foreach ($hero['bullets'] as $b): ?><li><?php echo h($b); ?></li><?php endforeach; ?>
                    </ul>
                    <?php endif; ?>
                    <div class="cta-group">
                        <a class="button primary" href="#tool-form">Start now</a>
                        <a class="button secondary" href="?page=home">Explore workflows</a>
                    </div>
                </div>
                <?php endif; ?>
                <div class="card" id="tool-form" style="margin-bottom:12px;">
                    <h3>Start Proposal</h3>
                    <div class="helper">
                        Craft a clear, specific request. Define objectives, audience, and constraints. Choose a tone and brand voice. Include differentiators and proof points. Strong prompts produce persuasive, on-brand content.
                    </div>
                    <form method="post">
                        <input type="hidden" name="action" value="proposalx_start">
                        <div class="row"><input type="text" id="proposal_prompt" name="prompt" placeholder="Proposal request / prompt" required></div>
                        <div class="two-col">
                            <div class="row"><select name="tone">
                                <option>Professional</option>
                                <option>Persuasive</option>
                                <option>Concise</option>
                                <option>Evangelical</option>
                                <option>Data-driven</option>
                            </select></div>
                            <div class="row"><input type="text" name="brand_voice" placeholder="Brand voice (e.g., confident, helpful)"></div>
                        </div>
                        <div class="two-col">
                            <div class="row"><input type="text" name="audience" placeholder="Target audience (buyers, execs, SMEs)"></div>
                            <div class="row"><input type="text" name="cta" placeholder="Primary CTA (book a call, sign, reply)"></div>
                        </div>
                        <div class="row"><textarea name="objectives" rows="3" placeholder="Objectives & constraints"></textarea></div>
                        <div class="row"><input type="text" name="keywords" placeholder="Keywords (comma-separated)"></div>
                        <div class="two-col">
                            <div class="row"><input type="text" name="depth" placeholder="Depth (default 1)"></div>
                            <div class="row"><input type="text" name="breadth" placeholder="Breadth (default 2)"></div>
                        </div>
                        <div class="row">
                            <select onchange="applyTemplateTo('proposal_prompt', this.value)">
                                <option value="">Templates…</option>
                                <option value="Write a proposal for launching our new AI-powered analytics platform to enterprise CIOs. Emphasize ROI, data governance, and seamless integration. Include a CTA to schedule a pilot.">New product launch</option>
                                <option value="Craft an RFP response highlighting our track record, technical fit, and risk mitigation plan. Address each requirement succinctly and persuasively with proof points.">RFP response</option>
                                <option value="Develop a partnership proposal with a leading cloud provider. Focus on joint GTM, co-selling motions, and shared success metrics.">Partnership proposal</option>
                                <option value="Prepare a grant application summary showcasing innovation, community impact, and measurable outcomes. Align with grant guidelines and selection criteria.">Grant application</option>
                            </select>
                        </div>
                        <button type="submit">Generate Questions</button>
                        <div class="config">Endpoint: <?php echo h($cfg['webhook_base_url'] . '/webhook/proposal/start'); ?></div>
                    </form>
                </div>
                <?php if ($action === 'proposalx_start' && !empty($result['data'])): ?>
                    <?php
                        $data = $result['data'];
                        $reqId = $data['request_id'] ?? '';
                        $questions = $data['questions'] ?? [];
                        $prefPrompt = isset($prompt) ? $prompt : '';
                        $prefDepth = isset($depth) ? $depth : 1;
                        $prefBreadth = isset($breadth) ? $breadth : 2;
                    ?>
                    <div class="card">
                        <h3>Questions</h3>
                        <?php if (!empty($questions) && is_array($questions)): ?>
                            <ul>
                                <?php foreach ($questions as $q): ?>
                                    <li><?php echo h($q); ?></li>
                                <?php endforeach; ?>
                            </ul>
                        <?php else: ?>
                            <p>No questions returned.</p>
                        <?php endif; ?>
                        <h3>Submit Answers</h3>
                        <form method="post">
                            <input type="hidden" name="action" value="proposalx_answers">
                            <input type="hidden" name="request_id" value="<?php echo h($reqId); ?>">
                            <div class="row"><input type="text" name="prompt" placeholder="Original prompt (repeat)" value="<?php echo h($prefPrompt); ?>" required></div>
                            <div class="row"><input type="text" name="depth" placeholder="Depth" value="<?php echo h($prefDepth); ?>"></div>
                            <div class="row"><input type="text" name="breadth" placeholder="Breadth" value="<?php echo h($prefBreadth); ?>"></div>
                            <div class="two-col">
                                <div class="row"><select name="tone">
                                    <option>Professional</option>
                                    <option>Persuasive</option>
                                    <option>Concise</option>
                                    <option>Evangelical</option>
                                    <option>Data-driven</option>
                                </select></div>
                                <div class="row"><input type="text" name="brand_voice" placeholder="Brand voice"></div>
                            </div>
                            <div class="two-col">
                                <div class="row"><input type="text" name="audience" placeholder="Target audience"></div>
                                <div class="row"><input type="text" name="cta" placeholder="Primary CTA"></div>
                            </div>
                            <div class="row"><input type="text" name="keywords" placeholder="Keywords"></div>
                            <?php if (!empty($questions) && is_array($questions)): ?>
                                <?php foreach ($questions as $i => $q): ?>
                                    <div class="row">
                                        <input type="hidden" name="answers[<?php echo (int)$i; ?>][question]" value="<?php echo h($q); ?>">
                                        <label style="width:100%;">
                                            <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Answer to: <?php echo h($q); ?></div>
                                            <input type="text" name="answers[<?php echo (int)$i; ?>][answer]" placeholder="Your answer" required>
                                        </label>
                                    </div>
                                <?php endforeach; ?>
                                <details style="margin-top:8px;">
                                    <summary>Or paste JSON answers</summary>
                                    <div class="row"><textarea name="answers_json" rows="6" placeholder='[{"question":"...","answer":"..."}]'></textarea></div>
                                </details>
                            <?php else: ?>
                                <div class="row"><textarea name="answers_json" rows="6" placeholder='[{"question":"...", "answer":"..."}]'></textarea></div>
                            <?php endif; ?>
                            <button type="submit">Submit Answers</button>
                            <div class="config">Endpoint: <?php echo h($cfg['webhook_base_url'] . '/webhook/proposal/answers'); ?></div>
                        </form>
                    </div>
                <?php endif; ?>
            <?php else: ?>
                <?php $hero = $toolHeroes[$selectedTool] ?? null; if ($hero): ?>
                <div class="hero hero-aws">
                    <div class="title"><?php echo h($hero['title']); ?></div>
                    <div class="subtitle"><?php echo h($hero['subtitle']); ?></div>
                    <?php if (!empty($hero['bullets'])): ?>
                    <ul class="bullets">
                        <?php foreach ($hero['bullets'] as $b): ?><li><?php echo h($b); ?></li><?php endforeach; ?>
                    </ul>
                    <?php endif; ?>
                    <div class="cta-group">
                        <a class="button primary" href="#tool-form">Start now</a>
                        <a class="button secondary" href="?page=home">Explore workflows</a>
                    </div>
                </div>
                <?php endif; ?>
                <div class="card" id="tool-form">
                <form method="post">
                    <input type="hidden" name="action" value="run_tool">
                    <input type="hidden" name="tool_key" value="<?php echo h($selectedTool); ?>">
                    <?php if ($selectedTool === 'PitchX'): ?>
                        <div class="row"><input type="text" name="deck_name" placeholder="Deck name" required></div>
                        <div class="row"><input type="text" name="audience" placeholder="Audience" required></div>
                        <div class="row"><textarea name="key_message" rows="3" placeholder="Key message"></textarea></div>
                    <?php elseif ($selectedTool === 'ContractX'): ?>
                        <div class="row"><input type="text" name="party_a" placeholder="Party A" required></div>
                        <div class="row"><input type="text" name="party_b" placeholder="Party B" required></div>
                        <div class="row"><input type="text" name="term" placeholder="Term (e.g., 12 months)"></div>
                        <div class="row"><input type="text" name="amount" placeholder="Amount (e.g., 10000 USD)"></div>
                    <?php elseif ($selectedTool === 'DeepX'): ?>
                        <div class="row"><input type="text" name="topic" placeholder="Research topic" required></div>
                        <div class="row"><input type="text" name="sources" placeholder="Sources (comma-separated)"></div>
                        <div class="row"><input type="text" name="depth" placeholder="Depth (e.g., deep)"></div>
                    <?php elseif ($selectedTool === 'StrategyX'): ?>
                        <div class="row"><input type="text" name="objective" placeholder="Objective" required></div>
                        <div class="row"><input type="text" name="market" placeholder="Market"></div>
                        <div class="row"><input type="text" name="channels" placeholder="Channels (comma-separated)"></div>
                    <?php endif; ?>
                    <div class="section-title">Copywriting controls</div>
                    <div class="two-col">
                        <div class="row"><select name="tone">
                            <option>Professional</option>
                            <option>Persuasive</option>
                            <option>Concise</option>
                            <option>Evangelical</option>
                            <option>Data-driven</option>
                        </select></div>
                        <div class="row"><input type="text" name="brand_voice" placeholder="Brand voice"></div>
                    </div>
                    <div class="two-col">
                        <div class="row"><input type="text" name="audience" placeholder="Target audience"></div>
                        <div class="row"><input type="text" name="cta" placeholder="Primary CTA"></div>
                    </div>
                    <div class="row"><input type="text" name="keywords" placeholder="Keywords (comma-separated)"></div>
                    <div class="row"><button type="submit">Run <?php echo h($selectedTool); ?></button></div>
                    <div class="config">Webhook: <?php echo h($cfg['webhook_base_url'] . '/' . ltrim($tools[$selectedTool], '/')); ?></div>
                </form>
                </div>
            <?php endif; ?>
            </div>
        <?php else: ?>
            <p>No tool configured.</p>
        <?php endif; ?>
    </div>
    <?php if ($message): ?>
        <div class="notice <?php echo isset($result['error']) ? 'error' : '';?>"><?php echo h($message); ?></div>
    <?php endif; ?>

    <div class="grid">
        <div class="card">
            <h2>Health</h2>
            <div class="row">
                <span>Connectivity:</span>
                <?php if (!empty($health['connectivity'])): ?>
                    <span class="badge green">OK</span>
                <?php else: ?>
                    <span class="badge gray">No</span>
                <?php endif; ?>
            </div>
            <div class="row">
                <span>Auth:</span>
                <?php if (!empty($health['auth'])): ?>
                    <span class="badge green">OK</span>
                <?php else: ?>
                    <span class="badge gray">Required</span>
                <?php endif; ?>
            </div>
            <div class="row">
                <span>Status:</span>
                <strong><?php echo h($health['status']); ?></strong>
            </div>
            <div class="row">
                <span>Response Time:</span>
                <strong><?php echo h($health['response_time_ms']); ?> ms</strong>
            </div>
            <?php if (!empty($health['error'])): ?>
            <div class="config">Error: <?php echo h($health['error']); ?></div>
            <?php endif; ?>
            <div class="config">
                Using API: <?php echo h($cfg['api_base_url']); ?>
            </div>
        </div>

        <div class="card">
            <h2>Trigger Webhook</h2>
            <form method="post">
                <input type="hidden" name="action" value="trigger_webhook">
                <div class="row"><input type="text" name="webhook_path" placeholder="webhook/path" required></div>
                <div class="row">
                    <select name="webhook_method">
                        <option>POST</option>
                        <option>GET</option>
                        <option>PUT</option>
                        <option>DELETE</option>
                    </select>
                </div>
                <div class="row"><textarea name="webhook_payload" rows="5" placeholder='{"hello":"world"}'></textarea></div>
                <button type="submit">Trigger</button>
                <div class="config">Webhook base: <?php echo h($cfg['webhook_base_url']); ?></div>
            </form>
        </div>
    </div>

    <div class="card" style="margin-top:16px;">
        <h2>Workflows</h2>
        <table>
            <thead><tr><th>ID</th><th>Name</th><th>Active</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach ($workflowItems as $w): ?>
                <?php $id = is_array($w) ? ($w['id'] ?? '') : ($w['id'] ?? '');
                      $name = is_array($w) ? ($w['name'] ?? '') : ($w['name'] ?? '');
                      $active = is_array($w) ? (!empty($w['active'])) : (!empty($w['active'])); ?>
                <tr>
                    <td><?php echo h($id); ?></td>
                    <td><?php echo h($name); ?></td>
                    <td><?php echo $active ? '<span class="badge green">Yes</span>' : '<span class="badge gray">No</span>'; ?></td>
                    <td>
                        <form method="post" style="display:inline-block;">
                            <input type="hidden" name="action" value="activate">
                            <input type="hidden" name="workflow_id" value="<?php echo h($id); ?>">
                            <button type="submit">Activate</button>
                        </form>
                        <form method="post" style="display:inline-block; margin-left:8px;">
                            <input type="hidden" name="action" value="deactivate">
                            <input type="hidden" name="workflow_id" value="<?php echo h($id); ?>">
                            <button type="submit" class="secondary">Deactivate</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <div class="grid" style="margin-top:16px;">
        <div class="card">
            <h2>Execution Status</h2>
            <form method="post">
                <input type="hidden" name="action" value="execution_status">
                <div class="row"><input type="text" id="execution_id" name="execution_id" placeholder="Execution ID" required></div>
                <button type="submit">Fetch</button>
            </form>
            <?php if ($action === 'execution_status' && $result): ?>
                <h3>Result</h3>
                <pre><?php echo h(json_encode($result['data'] ?? ($result['error'] ?? []), JSON_PRETTY_PRINT)); ?></pre>
            <?php endif; ?>
        </div>

        <div class="card">
            <h2>Details</h2>
            <?php if ($action && $result): ?>
                <pre><?php echo h(json_encode($result, JSON_PRETTY_PRINT)); ?></pre>
            <?php else: ?>
                <p>Select an action to view details.</p>
            <?php endif; ?>
        </div>
    </div>

    <footer>
        <div>Configured for local: <?php echo h($cfg['api_base_url']); ?> | Deploy to: thebrand.ai/n8nphp</div>
    </footer>
    </div>
</div>
</body>
</html>