<?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/Permissions/require_permission.php';
require_once __DIR__ . '/../src/ActivityLog.php';

// Require authentication
AuthManager::requireAuth();

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

// Check permission
requirePermission('templates_create');

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

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

$errors = [];
$successMessage = $_GET['success'] ?? null;
$templateData = [
    'name' => '',
    'header_html' => '',
    'footer_html' => '',
];
$editingTemplate = null;

if (isset($_GET['id'])) {
    $templateId = (int) $_GET['id'];
    if ($templateId > 0) {
        $editingTemplate = Template::find($templateId);
        if ($editingTemplate) {
            $templateData = array_merge($templateData, $editingTemplate);
        }
    }
}

$templates = Template::all();
$totalTemplates = count($templates);
$latestTemplateTimestamp = null;
foreach ($templates as $template) {
    $candidate = $template['updated_at'] ?? $template['created_at'] ?? null;
    if ($candidate && (!$latestTemplateTimestamp || $candidate > $latestTemplateTimestamp)) {
        $latestTemplateTimestamp = $candidate;
    }
}
$latestTemplateLabel = $latestTemplateTimestamp ? date('M j, Y', strtotime($latestTemplateTimestamp)) : 'No templates yet';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'save_template') {
        $templateData['name'] = trim($_POST['name'] ?? '');
        $templateData['header_html'] = $_POST['header_html'] ?? '';
        $templateData['footer_html'] = $_POST['footer_html'] ?? '';

        if ($templateData['name'] === '') {
            $errors[] = 'Template name is required.';
        }

        if (!$errors) {
            if ($editingTemplate) {
                Template::update((int) $editingTemplate['id'], $templateData);

                // Log template update (best-effort)
                try {
                    if ($companyId) {
                        $currentUser = AuthManager::getCurrentUser();
                        $userId = $currentUser['id'] ?? null;
                        ActivityLog::log(
                            (int) $companyId,
                            $userId ? (int) $userId : null,
                            'template_updated',
                            'template',
                            (int) $editingTemplate['id'],
                            $templateData['name'] ?? null,
                            $editingTemplate,
                            $templateData
                        );
                    }
                } catch (Throwable $e) {
                    // ignore logging failures
                }

                $redirectParams = [
                    'id' => (int) $editingTemplate['id'],
                    'success' => 'Template updated.',
                ];
                if (isset($_GET['workspace'])) {
                    $redirectParams['workspace'] = $_GET['workspace'];
                }
                redirect('/template_create.php', $redirectParams);
            }

            $newId = Template::create($templateData);

            // Log template creation (best-effort)
            try {
                if ($companyId) {
                    $currentUser = AuthManager::getCurrentUser();
                    $userId = $currentUser['id'] ?? null;
                    ActivityLog::log(
                        (int) $companyId,
                        $userId ? (int) $userId : null,
                        'template_created',
                        'template',
                        (int) $newId,
                        $templateData['name'] ?? null,
                        null,
                        $templateData
                    );
                }
            } catch (Throwable $e) {
                // ignore logging failures
            }

            $redirectParams = [
                'id' => $newId,
                'success' => 'Template created successfully.',
            ];
            if (isset($_GET['workspace'])) {
                $redirectParams['workspace'] = $_GET['workspace'];
            }
            redirect('/template_create.php', $redirectParams);
        }
    }
}

// Theme handling (dark by default)
$currentTheme = $_GET['theme'] ?? 'dark';
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';
$companyDisplayName = $company['name'] ?? 'Workspace';
$workspaceSlug = $company['username'] ?? ($_GET['workspace'] ?? null);
$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode((string) $workspaceSlug) : '';
$availableVariables = function_exists('getTinyMCEVariableTokens')
    ? getTinyMCEVariableTokens()
    : [
        ['label' => 'Client name', 'token' => '{{client_name}}'],
        ['label' => 'Company', 'token' => '{{company_name}}'],
        ['label' => 'Project', 'token' => '{{project_name}}'],
        ['label' => 'Proposal date', 'token' => '{{proposal_date}}'],
        ['label' => 'Client email', 'token' => '{{client_email}}'],
        ['label' => 'Client phone', 'token' => '{{client_phone}}'],
        ['label' => 'Client address', 'token' => '{{client_address}}'],
    ];
$tinymceComponent = __DIR__ . '/components/editors/tinymce-init.php';
if (file_exists($tinymceComponent)) {
    require_once $tinymceComponent;
}
?>
<!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><?= $editingTemplate ? 'Edit Template' : 'Create Template' ?> · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
    <script src="https://cdn.jsdelivr.net/npm/tinymce@6.8.2/tinymce.min.js"></script>
    <?php if (function_exists('renderTinyMCEInit')) { renderTinyMCEInit(); } ?>
    <script>
        function insertVariable(variable) {
            if (window.tinymce && tinymce.activeEditor) {
                tinymce.activeEditor.insertContent(variable);
            }
        }
    </script>
</head>
<body>
<?php renderNavigationNew('Templates', $currentTheme); ?>

<div class="main-container">
    <?php
    require_once __DIR__ . '/components/headers/page-header.php';

    $actions = [
        [
            'label' => 'Manage templates',
            'url' => '/templates.php',
            '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',
            'append_workspace' => true,
        ],
        [
            'label' => 'Generate proposal',
            'url' => '/generate.php',
            'type' => 'secondary',
            'icon' => 'M12 4v16m8-8H4',
            'append_workspace' => true,
        ],
    ];

    renderPageHeader(
        breadcrumbs: [
            ['label' => htmlspecialchars($companyDisplayName), 'url' => '/index.php', 'icon' => 'M3 7h18M3 12h18M3 17h18'],
            ['label' => 'Templates', 'url' => '/templates.php', '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: $editingTemplate ? 'Edit template' : 'Create template',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

    <div class="dash-container proposal-wizard">
        <?php if ($successMessage): ?>
            <div class="dash-section">
                <div class="status-banner success">
                    <span><?= h($successMessage) ?></span>
                </div>
            </div>
        <?php endif; ?>

        <?php if ($errors): ?>
            <div class="dash-section">
                <div class="status-banner error">
                    <div>
                        <?php foreach ($errors as $error): ?>
                            <p><?= h($error) ?></p>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="dash-section">
            <section class="card template-hero">
                <div>
                    <p class="section-title">Template builder</p>
                    <h1 class="template-hero__title"><?= $editingTemplate ? 'Edit template' : 'Create template' ?> for <?= htmlspecialchars($companyDisplayName) ?></h1>
                    <p class="template-hero__subtitle">
                        Structure headers and footers with variables, embedded assets, and branded modules to keep every proposal on-message.
                    </p>
                </div>
                <div class="template-hero__meta">
                    <span class="status-chip"><?= $totalTemplates ?> active</span>
                    <span class="status-chip">Latest update <?= h($latestTemplateLabel) ?></span>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <section class="card template-stats">
                <div class="template-stats-grid">
                    <div class="template-stat">
                        <p class="template-stat__label">Total templates</p>
                        <p class="template-stat__value"><?= $totalTemplates ?></p>
                        <p class="template-stat__hint">Workspace-ready layouts</p>
                    </div>
                    <div class="template-stat">
                        <p class="template-stat__label">Variables</p>
                        <p class="template-stat__value"><?= count($availableVariables) ?>+</p>
                        <p class="template-stat__hint">Client + proposal placeholders</p>
                    </div>
                    <div class="template-stat">
                        <p class="template-stat__label">Last updated</p>
                        <p class="template-stat__value"><?= h($latestTemplateLabel) ?></p>
                        <p class="template-stat__hint">Most recent change</p>
                    </div>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <section class="card template-builder-card">
                <div class="template-builder-form">
                    <form method="POST" class="space-y-5">
                        <input type="hidden" name="action" value="save_template">
                        <?php if ($workspaceSlug): ?>
                            <input type="hidden" name="workspace" value="<?= h($workspaceSlug) ?>">
                        <?php endif; ?>
                        <?php if ($editingTemplate): ?>
                            <input type="hidden" name="id" value="<?= (int) $editingTemplate['id'] ?>">
                        <?php endif; ?>

                        <label class="form-field">
                            <span>Template name *</span>
                            <input
                                type="text"
                                name="name"
                                value="<?= h($templateData['name']) ?>"
                                class="field-input"
                                required
                                placeholder="e.g. Product Launch Proposal"
                            >
                        </label>

                        <div class="template-editor-block">
                            <div class="template-editor-block__head">
                                <div>
                                    <p class="template-editor-block__title">Header content</p>
                                    <p class="template-editor-block__subtitle">Appears at the top of every proposal</p>
                                </div>
                            </div>
                            <?php if (function_exists('renderTinyMCEVariableInserts')) { renderTinyMCEVariableInserts($availableVariables); } ?>
                            <textarea
                                name="header_html"
                                id="template_header"
                                class="editor-area rich"
                                rows="12"
                            ><?= h($templateData['header_html']) ?></textarea>
                        </div>

                        <div class="template-editor-block">
                            <div class="template-editor-block__head">
                                <div>
                                    <p class="template-editor-block__title">Footer content</p>
                                    <p class="template-editor-block__subtitle">Shown below pricing + signature blocks</p>
                                </div>
                            </div>
                            <?php if (function_exists('renderTinyMCEVariableInserts')) { renderTinyMCEVariableInserts($availableVariables); } ?>
                            <textarea
                                name="footer_html"
                                id="template_footer"
                                class="editor-area rich"
                                rows="10"
                            ><?= h($templateData['footer_html']) ?></textarea>
                        </div>

                        <div class="template-builder-actions">
                            <button type="submit" class="btn-primary">
                                <?= $editingTemplate ? 'Update template' : 'Create template' ?>
                            </button>
                            <a href="/templates.php<?= $workspaceQuery ?>" class="btn-secondary">Cancel</a>
                            <?php if ($editingTemplate): ?>
                                <a href="/template_preview.php?id=<?= (int) $editingTemplate['id'] ?><?= $workspaceSlug ? '&workspace=' . urlencode($workspaceSlug) : '' ?>" class="btn-tertiary">
                                    Preview
                                </a>
                            <?php endif; ?>
                        </div>
                    </form>
                </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>
