<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/MultiTenant/TenantManager.php';
require_once __DIR__ . '/../src/TenantDB.php';
require_once __DIR__ . '/../src/Template.php';
require_once __DIR__ . '/navigation.php';
require_once __DIR__ . '/../src/ActivityLog.php';

// Require authentication
AuthManager::requireAuth();

// Initialize tenant context
TenantManager::initialize();

// Resolve workspace context
$companyId = null;
if (isset($_GET['workspace'])) {
    $workspaceParam = sanitizeText($_GET['workspace']);
    $pdo = getPDO();
    $stmt = $pdo->prepare('SELECT id FROM companies WHERE username = ?');
    $stmt->execute([$workspaceParam]);
    $company = $stmt->fetch();
    $companyId = $company['id'] ?? null;
}
if (!$companyId) {
    $companyId = TenantDB::getTenant();
}

// Set tenant context for Template class
if ($companyId) {
    TenantDB::setTenant($companyId);
}

// Workspace display context for breadcrumbs / links
$companyDisplayName = 'Selected workspace';
$workspaceSlug = null;
if ($companyId) {
    try {
        $pdo = getPDO();
        $stmt = $pdo->prepare('SELECT name, username FROM companies WHERE id = ?');
        $stmt->execute([$companyId]);
        if ($row = $stmt->fetch()) {
            $companyDisplayName = $row['name'] ?? $companyDisplayName;
            $workspaceSlug = $row['username'] ?? null;
        }
    } catch (Throwable $e) {
        // best-effort only, fall back to defaults on failure
    }
}

if (!$workspaceSlug && isset($workspaceParam)) {
    $workspaceSlug = $workspaceParam;
}

$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode($workspaceSlug) : '';
$workspaceQueryAmp = $workspaceSlug ? '&workspace=' . urlencode($workspaceSlug) : '';

$templateId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$template = $templateId > 0 ? Template::find($templateId) : null;

if (!$template) {
    http_response_code(404);
    echo 'Template not found';
    exit;
}

// Process variables for preview
$templateVariables = [
    'client_name' => 'John Doe',
    'company_name' => 'Acme Corporation',
    'project_name' => 'Website Redesign',
    'proposal_date' => date('F j, Y'),
    'client_email' => 'john.doe@acme.com',
    'client_phone' => '+1 (555) 123-4567',
    'client_address' => '123 Business St, Suite 100, New York, NY 10001'
];

// Log template preview (best-effort)
try {
    $companyIdForLog = TenantDB::getTenant();
    if ($companyIdForLog) {
        $userId = $_SESSION['user_id'] ?? null;
        ActivityLog::log(
            (int) $companyIdForLog,
            $userId ? (int) $userId : null,
            'template_previewed',
            'template',
            $templateId,
            $template['name'] ?? null,
            null,
            null
        );
    }
} catch (Throwable $e) {
    // ignore logging failures
}

// Theme (dark by default)
$currentTheme = $_GET['theme'] ?? 'dark';
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';

$previewGeneratedAt = date('M j, Y g:i A');
$lastUpdatedDisplay = 'Recently updated';
if (!empty($template['updated_at'])) {
    $timestamp = strtotime((string) $template['updated_at']);
    if ($timestamp) {
        $lastUpdatedDisplay = date('M j, Y', $timestamp);
    }
}
?>
<?php require_once __DIR__ . '/components/headers/page-header.php'; ?>
<!DOCTYPE html>
<html lang="en" data-theme="<?= h($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Preview: <?= h($template['name']) ?> · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
</head>
<body>
<?php renderNavigationNew('Templates', $currentTheme); ?>

<div class="main-container">
    <?php
    $actions = [
        [
            'label' => 'All templates',
            'url' => '/templates.php' . $workspaceQuery,
            'type' => 'secondary',
            'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z',
        ],
        [
            'label' => 'Edit template',
            'url' => '/template_create.php?id=' . (int) $template['id'] . $workspaceQueryAmp,
            'type' => 'secondary',
            'icon' => 'M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z',
        ],
        [
            'label' => 'Manage modules',
            'url' => '/template_edit_modules.php?id=' . (int) $template['id'] . $workspaceQueryAmp,
            'type' => 'secondary',
            'icon' => 'M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10',
        ],
        [
            'label' => 'Generate proposal',
            'url' => '/generate.php' . $workspaceQuery,
            'type' => 'primary',
            'icon' => 'M12 4v16m8-8H4',
        ],
    ];

    renderPageHeader(
        breadcrumbs: [
            ['label' => htmlspecialchars($companyDisplayName), 'url' => '/index.php' . $workspaceQuery, 'icon' => 'M3 7h18M3 12h18M3 17h18'],
            ['label' => 'Templates', 'url' => '/templates.php' . $workspaceQuery, 'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z'],
        ],
        currentPage: 'Preview',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

    <div class="dash-container">
        <div class="dash-section">
            <section class="card template-preview-hero">
                <div>
                    <p class="section-title">Template preview</p>
                    <h1 class="template-preview-hero__title"><?= h($template['name']) ?></h1>
                    <p class="template-preview-hero__subtitle">Review how your header and footer blocks frame every generated proposal before sharing it with a client.</p>
                </div>
                <div class="template-preview-hero__meta">
                    <div class="template-preview-hero__stat">
                        <p class="template-preview-hero__label">Workspace</p>
                        <p class="template-preview-hero__value"><?= h($companyDisplayName) ?></p>
                    </div>
                    <div class="template-preview-hero__stat">
                        <p class="template-preview-hero__label">Last updated</p>
                        <p class="template-preview-hero__value"><?= h($lastUpdatedDisplay) ?></p>
                    </div>
                    <div class="template-preview-hero__stat">
                        <p class="template-preview-hero__label">Preview generated</p>
                        <p class="template-preview-hero__value"><?= h($previewGeneratedAt) ?></p>
                    </div>
                </div>
                <div class="template-preview-hero__actions">
                    <a href="/template_create.php?id=<?= (int) $template['id'] ?><?= $workspaceQueryAmp ?>" class="btn-secondary">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                        </svg>
                        Edit template
                    </a>
                    <a href="/template_edit_modules.php?id=<?= (int) $template['id'] ?><?= $workspaceQueryAmp ?>" class="btn-secondary">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
                        </svg>
                        Manage modules
                    </a>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <section class="card template-preview-pane">
                <div class="template-preview-pane__header">
                    <div>
                        <p class="section-title">Preview surface</p>
                        <h2>Header &amp; footer blocks</h2>
                        <p>These blocks wrap every proposal. Header renders before your modules, while the footer closes the document for signatures, CTAs, and legal copy.</p>
                    </div>
                    <span class="template-preview-pane__hint">Uses sample data for variables</span>
                </div>

                <div class="template-preview-list">
                    <article class="preview-surface">
                        <div class="preview-surface__meta">
                            <span class="preview-chip">Header block</span>
                            <span>Appears before proposal content</span>
                        </div>
                        <div class="preview-paper">
                            <div class="tinymce-preview">
                                <?= renderWithVariables($template['header_html'] ?: '<p>No header content yet.</p>', $templateVariables) ?>
                            </div>
                        </div>
                    </article>

                    <article class="preview-surface">
                        <div class="preview-surface__meta">
                            <span class="preview-chip">Footer block</span>
                            <span>Printed after the last module</span>
                        </div>
                        <div class="preview-paper">
                            <div class="tinymce-preview">
                                <?= renderWithVariables($template['footer_html'] ?: '<p>No footer content yet.</p>', $templateVariables) ?>
                            </div>
                        </div>
                    </article>
                </div>

                <div class="template-preview-pane__footer">
                    <div class="template-preview-pane__id">
                        <p>Template ID: <?= (int) $template['id'] ?></p>
                        <p>Workspace: <?= h($companyDisplayName) ?></p>
                    </div>
                    <div class="template-preview-pane__actions">
                        <a href="/templates.php<?= $workspaceQuery ?>" class="btn-secondary">Back to templates</a>
                        <a href="/generate.php<?= $workspaceQuery ?>" class="btn-emerald">Generate proposal</a>
                    </div>
                </div>
            </section>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const mobileMenuBtn = document.getElementById('mobile-menu-btn');
    if (mobileMenuBtn && typeof window.openAppSidebar === 'function') {
        mobileMenuBtn.addEventListener('click', function () {
            window.openAppSidebar();
        });
    }
});
</script>

</body>
</html>
