<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/secure_workspace.php';
require_once __DIR__ . '/../src/ContractTemplate.php';
require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/navigation.php';

$templateId = isset($_GET['id']) ? (int) $_GET['id'] : 0;

// Get current workspace company ID for validation
$companyId = null;
$workspaceParam = $_GET['workspace'] ?? null;
if ($workspaceParam) {
    $pdo = getPDO();
    $stmt = $pdo->prepare("SELECT id FROM companies WHERE username = ?");
    $stmt->execute([$workspaceParam]);
    $company = $stmt->fetch();
    $companyId = $company['id'] ?? null;
}

// Fallback to tenant context
if (!$companyId) {
    $companyId = TenantDB::getTenant();
}

if (!$companyId) {
    http_response_code(400);
    echo 'No workspace context available';
    exit;
}

// Load template with workspace validation
$template = null;
if ($templateId > 0 && $companyId) {
    $pdo = getPDO();
    $stmt = $pdo->prepare('SELECT * FROM contract_templates WHERE id = ? AND company_id = ?');
    $stmt->execute([$templateId, $companyId]);
    $template = $stmt->fetch(PDO::FETCH_ASSOC);
}

if (!$template) {
    http_response_code(404);
    echo 'Contract template not found or not accessible in current workspace';
    exit;
}

// Log contract template preview (best-effort)
try {
    workspace_log(
        'contract_template_previewed',
        'contract_template',
        $templateId,
        $template['name'] ?? null,
        null,
        null
    );
} catch (Throwable $e) {
    // ignore logging failures
}

// Process variables for preview
$templateVariables = [
    'client_name' => 'John Doe',
    'company_name' => 'Acme Corporation',
    'project_name' => 'Website Redesign',
    'contract_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',
    'contract_number' => 'CT-' . date('Y') . '-' . str_pad((string)$templateId, 4, '0', STR_PAD_LEFT)
];

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

$companyDisplayName = 'Workspace';
$workspaceSlug = $workspaceParam ? (string) $workspaceParam : null;
$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode($workspaceSlug) : '';
$workspaceQueryAmp = $workspaceSlug ? '&workspace=' . urlencode($workspaceSlug) : '';

$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);
    }
}
?>
<!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>Contract 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">
    <style>
        /* TinyMCE default content styles - exact match */
        .tinymce-content {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            font-size: 16px;
            line-height: 1.5;
            color: #222f3e;
            box-sizing: border-box;
        }
        
        /* Headings - TinyMCE default */
        .tinymce-content h1 {
            font-size: 2em;
            font-weight: bold;
            margin: 0.67em 0;
            line-height: 1.2;
        }
        .tinymce-content h2 {
            font-size: 1.5em;
            font-weight: bold;
            margin: 0.75em 0;
            line-height: 1.3;
        }
        .tinymce-content h3 {
            font-size: 1.17em;
            font-weight: bold;
            margin: 0.83em 0;
            line-height: 1.3;
        }
        .tinymce-content h4 {
            font-size: 1em;
            font-weight: bold;
            margin: 1.12em 0;
            line-height: 1.3;
        }
        .tinymce-content h5 {
            font-size: 0.83em;
            font-weight: bold;
            margin: 1.5em 0;
            line-height: 1.3;
        }
        .tinymce-content h6 {
            font-size: 0.75em;
            font-weight: bold;
            margin: 1.67em 0;
            line-height: 1.3;
        }
        
        /* Paragraphs and text */
        .tinymce-content p {
            margin: 1em 0;
            line-height: 1.5;
        }
        
        /* Text formatting */
        .tinymce-content strong {
            font-weight: bold;
        }
        .tinymce-content b {
            font-weight: bold;
        }
        .tinymce-content em {
            font-style: italic;
        }
        .tinymce-content i {
            font-style: italic;
        }
        
        /* Links */
        .tinymce-content a {
            color: #2276d2;
            text-decoration: underline;
        }
        .tinymce-content a:visited {
            color: #2276d2;
        }
        
        /* Lists */
        .tinymce-content ul, .tinymce-content ol {
            margin: 1em 0;
            padding-left: 40px;
        }
        .tinymce-content li {
            margin: 0.5em 0;
            line-height: 1.5;
        }
        
        /* Tables - TinyMCE default */
        .tinymce-content table {
            border-collapse: collapse;
            border-spacing: 0;
            empty-cells: show;
            border: 1px solid #ccc;
            width: 100%;
            margin: 1em 0;
        }
        .tinymce-content table caption {
            caption-side: top;
            text-align: left;
            padding: 8px;
            font-weight: bold;
            background-color: #f0f0f0;
        }
        .tinymce-content td, .tinymce-content th {
            border: 1px solid #ccc;
            padding: 8px;
            vertical-align: top;
        }
        .tinymce-content th {
            font-weight: bold;
            background-color: #f0f0f0;
            text-align: left;
        }
        
        /* Images - TinyMCE default with alignment support */
        .tinymce-content img {
            max-width: 100%;
            height: auto;
            border: 0;
            outline: 0;
            display: inline;
        }
        
        /* TinyMCE legacy HTML align attribute - HIGHEST SPECIFICITY */
        .tinymce-content img[align="left"] {
            float: left !important;
            margin: 0 1em 1em 0 !important;
            display: block !important;
        }
        .tinymce-content img[align="right"] {
            float: right !important;
            margin: 0 0 1em 1em !important;
            display: block !important;
        }
        .tinymce-content img[align="center"] {
            display: block !important;
            margin: 0 auto 1em auto !important;
            float: none !important;
        }
        .tinymce-content img[align="top"] {
            vertical-align: top !important;
        }
        .tinymce-content img[align="middle"] {
            vertical-align: middle !important;
        }
        .tinymce-content img[align="bottom"] {
            vertical-align: bottom !important;
        }
        
        /* Override any conflicting styles */
        .tinymce-content img[align="left"],
        .tinymce-content img[align="right"],
        .tinymce-content img[align="center"] {
            max-width: 100%;
            height: auto;
            border: 0;
            outline: 0;
        }
        
        /* TinyMCE image alignment patterns */
        .tinymce-content img.align-left {
            float: left !important;
            margin: 0 1em 1em 0 !important;
            display: block !important;
        }
        .tinymce-content img.align-right {
            float: right !important;
            margin: 0 0 1em 1em !important;
            display: block !important;
        }
        .tinymce-content img.align-center {
            display: block !important;
            margin: 0 auto 1em auto !important;
            float: none !important;
        }
        .tinymce-content img.align-top {
            vertical-align: top !important;
        }
        .tinymce-content img.align-middle {
            vertical-align: middle !important;
        }
        .tinymce-content img.align-bottom {
            vertical-align: bottom !important;
        }
        
        /* TinyMCE figure alignment patterns */
        .tinymce-content figure.align-left {
            float: left;
            margin: 0 1em 1em 0;
            text-align: left;
        }
        .tinymce-content figure.align-right {
            float: right;
            margin: 0 0 1em 1em;
            text-align: right;
        }
        .tinymce-content figure.align-center {
            display: block;
            margin: 0 auto 1em auto;
            text-align: center;
        }
        
        /* TinyMCE div wrapper patterns */
        .tinymce-content div.mce-content-body img[data-mce-selected="1"] {
            outline: 2px solid #4099ff;
        }
        
        /* TinyMCE alignment using data attributes */
        .tinymce-content img[data-align="left"] {
            float: left;
            margin: 0 1em 1em 0;
        }
        .tinymce-content img[data-align="right"] {
            float: right;
            margin: 0 0 1em 1em;
        }
        .tinymce-content img[data-align="center"] {
            display: block;
            margin: 0 auto 1em auto;
        }
        
        /* TinyMCE legacy alignment classes */
        .tinymce-content .mce-item-alignleft {
            float: left;
            margin: 0 1em 1em 0;
        }
        .tinymce-content .mce-item-alignright {
            float: right;
            margin: 0 0 1em 1em;
        }
        .tinymce-content .mce-item-aligncenter {
            display: block;
            margin: 0 auto 1em auto;
            text-align: center;
        }
        
        /* TinyMCE image wrapper divs */
        .tinymce-content div[data-mce-style] {
            position: relative;
        }
        .tinymce-content div[data-mce-style*="float: left"] img {
            float: left;
            margin: 0 1em 1em 0;
        }
        .tinymce-content div[data-mce-style*="float: right"] img {
            float: right;
            margin: 0 0 1em 1em;
        }
        .tinymce-content div[data-mce-style*="margin: 0 auto"] img {
            display: block;
            margin: 0 auto 1em auto;
        }
        
        /* TinyMCE centered images in paragraphs */
        .tinymce-content p[style*="text-align: center"] img {
            display: block;
            margin: 0 auto 1em auto;
        }
        .tinymce-content p[style*="text-align: left"] img {
            float: left;
            margin: 0 1em 1em 0;
        }
        .tinymce-content p[style*="text-align: right"] img {
            float: right;
            margin: 0 0 1em 1em;
        }
        
        /* Blockquotes */
        .tinymce-content blockquote {
            border-left: 4px solid #ccc;
            margin: 1em 0;
            padding: 0.5em 1em;
            background-color: #f9f9f9;
            font-style: italic;
            color: #555;
        }
        
        /* Code */
        .tinymce-content code {
            background-color: #f4f4f4;
            padding: 2px 4px;
            border-radius: 3px;
            font-family: "Courier New", Courier, monospace;
            font-size: 0.9em;
        }
        .tinymce-content pre {
            background-color: #f4f4f4;
            border: 1px solid #ddd;
            padding: 1em;
            border-radius: 4px;
            overflow-x: auto;
            font-family: "Courier New", Courier, monospace;
            font-size: 0.9em;
            line-height: 1.4;
        }
        .tinymce-content pre code {
            background-color: transparent;
            padding: 0;
            border-radius: 0;
        }
        
        /* Horizontal rule */
        .tinymce-content hr {
            border: none;
            border-top: 1px solid #ccc;
            margin: 2em 0;
            height: 1px;
        }
        
        /* Figure and figcaption */
        .tinymce-content figure {
            margin: 1em 0;
            text-align: center;
        }
        .tinymce-content figcaption {
            font-size: 0.9em;
            color: #666;
            font-style: italic;
            margin-top: 0.5em;
        }
        
        /* Div alignment classes */
        .tinymce-content .text-left {
            text-align: left;
        }
        .tinymce-content .text-center {
            text-align: center;
        }
        .tinymce-content .text-right {
            text-align: right;
        }
        .tinymce-content .text-justify {
            text-align: justify;
        }
        
        /* Clear floats */
        .tinymce-content::after {
            content: "";
            display: table;
            clear: both;
        }
    </style>
</head>
<body>
<?php
require_once __DIR__ . '/components/headers/page-header.php';
renderNavigationNew('Contracts', $currentTheme);
?>

<div class="main-container">
    <?php
    $actions = [
        [
            'label' => 'All contract templates',
            'url' => '/contract_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' => '/contract_templates.php?edit=' . (int) $template['id'] . $workspaceQueryAmp . '#template-builder',
            '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' => '/contract_template_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',
        ],
    ];

    renderPageHeader(
        breadcrumbs: [
            ['label' => htmlspecialchars($companyDisplayName), 'url' => '/index.php' . $workspaceQuery, 'icon' => 'M3 7h18M3 12h18M3 17h18'],
            ['label' => 'Contract templates', 'url' => '/contract_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">Contract 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 contract.</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="/contract_templates.php?edit=<?= (int) $template['id'] ?><?= $workspaceQueryAmp ?>#template-builder" class="btn-secondary">Edit template</a>
                    <a href="/contract_template_modules.php?id=<?= (int) $template['id'] ?><?= $workspaceQueryAmp ?>" class="btn-secondary">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 contract. Header renders before your modules, while the footer closes the document.</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 contract 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="/contract_templates.php<?= $workspaceQuery ?>" class="btn-secondary">Back to templates</a>
                        <a href="/contract_create.php?step=2&template_id=<?= (int) $template['id'] ?><?= $workspaceQueryAmp ?>" class="btn-emerald">Create contract</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', window.openAppSidebar);
    }
});
</script>

</body>
</html>
