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

// Require authentication
AuthManager::requireAuth();

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

// Check permission - Contract templates require contracts_edit permission
requirePermission('contracts_edit');

// Initialize tenant context
TenantManager::initialize();
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/ContractTemplate.php';
require_once __DIR__ . '/../src/ContractModule.php';

$pdo = getPDO();

// Resolve workspace context early so ContractTemplate/ContractModule queries run in the right tenant
$companyId = null;
$companyRecord = null;
$workspaceParam = isset($_GET['workspace']) ? sanitizeText($_GET['workspace']) : null;
if ($workspaceParam) {
    $stmt = $pdo->prepare('SELECT * FROM companies WHERE username = ?');
    $stmt->execute([$workspaceParam]);
    $companyRecord = $stmt->fetch() ?: null;
    $companyId = $companyRecord['id'] ?? null;
}
if (!$companyId) {
    $companyId = TenantDB::getTenant();
    if ($companyId) {
        $stmt = $pdo->prepare('SELECT * FROM companies WHERE id = ?');
        $stmt->execute([$companyId]);
        $companyRecord = $stmt->fetch() ?: $companyRecord;
    }
}
if ($companyId) {
    TenantDB::setTenant((int) $companyId);
}
$companyDisplayName = $companyRecord['name'] ?? 'Workspace';
$workspaceSlug = $companyRecord['username'] ?? $workspaceParam;
$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' => 'Contract date', 'token' => '{{contract_date}}'],
        ['label' => 'Contract number', 'token' => '{{contract_number}}'],
        ['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;
}

// Handle form submissions
$action = $_POST['action'] ?? '';
$editingTemplate = null;
$formDataCreate = ['name' => '', 'description' => '', 'header_html' => '', 'footer_html' => ''];
$formDataEdit = ['name' => '', 'description' => '', 'header_html' => '', 'footer_html' => ''];
$successMessage = '';
$errors = [];

if ($action === 'create') {
    $formDataCreate = [
        'name' => $_POST['name'] ?? '',
        'description' => $_POST['description'] ?? '',
        'header_html' => $_POST['header_html'] ?? '',
        'footer_html' => $_POST['footer_html'] ?? '',
    ];

    if (empty($formDataCreate['name'])) {
        $errors[] = 'Template name is required.';
    } else {
        $templateId = ContractTemplate::create($formDataCreate);
        
        // Attach default required modules
        $defaultModules = ContractModule::all();
        foreach ($defaultModules as $module) {
            if (!empty($module['default_required'])) {
                ContractTemplate::attachModule($templateId, $module['id'], $module['sort_order']);
            }
        }
        
        // Log contract template creation (best-effort)
        try {
            $createdTemplate = ContractTemplate::find((int) $templateId);
            $companyId = (int) ($createdTemplate['company_id'] ?? 0);
            if ($companyId > 0) {
                $currentUser = AuthManager::getCurrentUser();
                $userId = $currentUser['id'] ?? null;
                ActivityLog::log(
                    $companyId,
                    $userId ? (int) $userId : null,
                    'template_created',
                    'contract_template',
                    (int) $templateId,
                    $formDataCreate['name'] ?? null,
                    null,
                    $formDataCreate
                );
            }
        } catch (Throwable $e) {
            // ignore logging failures
        }

        $successMessage = 'Contract template created successfully.';
        $formDataCreate = ['name' => '', 'description' => '', 'header_html' => '', 'footer_html' => ''];
    }
}

if ($action === 'update' && isset($_POST['id'])) {
    $editingTemplate = ContractTemplate::find((int) $_POST['id']);
    if ($editingTemplate) {
        $formDataEdit = [
            'name' => $_POST['name'] ?? $editingTemplate['name'],
            'description' => $_POST['description'] ?? $editingTemplate['description'],
            'header_html' => $_POST['header_html'] ?? $editingTemplate['header_html'],
            'footer_html' => $_POST['footer_html'] ?? $editingTemplate['footer_html'],
        ];

        if (empty($formDataEdit['name'])) {
            $errors[] = 'Template name is required.';
        } else {
            ContractTemplate::update((int) $_POST['id'], $formDataEdit);
            // Log contract template update (best-effort)
            try {
                $companyId = (int) ($editingTemplate['company_id'] ?? 0);
                if ($companyId > 0) {
                    $currentUser = AuthManager::getCurrentUser();
                    $userId = $currentUser['id'] ?? null;
                    ActivityLog::log(
                        $companyId,
                        $userId ? (int) $userId : null,
                        'template_updated',
                        'contract_template',
                        (int) $_POST['id'],
                        $formDataEdit['name'] ?? null,
                        $editingTemplate,
                        $formDataEdit
                    );
                }
            } catch (Throwable $e) {
                // ignore logging failures
            }
            $successMessage = 'Contract template updated successfully.';
            $editingTemplate = null;
        }
    }
}

if ($action === 'delete' && isset($_POST['id'])) {
    $existingTemplate = ContractTemplate::find((int) $_POST['id']);
    ContractTemplate::delete((int) $_POST['id']);

    // Log contract template deletion (best-effort)
    try {
        $companyId = (int) ($existingTemplate['company_id'] ?? 0);
        if ($companyId > 0) {
            $currentUser = AuthManager::getCurrentUser();
            $userId = $currentUser['id'] ?? null;
            ActivityLog::log(
                $companyId,
                $userId ? (int) $userId : null,
                'template_deleted',
                'contract_template',
                (int) ($_POST['id'] ?? 0),
                $existingTemplate['name'] ?? null,
                $existingTemplate,
                null
            );
        }
    } catch (Throwable $e) {
        // ignore logging failures
    }
    $successMessage = 'Contract template deleted successfully.';
}

if (isset($_GET['edit'])) {
    $editingTemplate = ContractTemplate::find((int) $_GET['edit']);
    if ($editingTemplate) {
        $formDataEdit = [
            'name' => $editingTemplate['name'],
            'description' => $editingTemplate['description'],
            'header_html' => $editingTemplate['header_html'],
            'footer_html' => $editingTemplate['footer_html'],
        ];
    }
}

$templates = ContractTemplate::all();

// Theme (dark by default)
$currentTheme = $_GET['theme'] ?? 'dark';
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';
?>
<!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 Templates · 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('Contracts', $currentTheme); ?>

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

    $actions = [
        [
            'label' => 'Manage modules',
            'url' => '/contract_modules.php',
            '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',
            'append_workspace' => true,
        ],
    ];

    renderPageHeader(
        breadcrumbs: [
            ['label' => htmlspecialchars($companyDisplayName), 'url' => '/index.php', 'icon' => 'M3 7h18M3 12h18M3 17h18'],
            ['label' => 'Contracts', 'url' => '/contracts.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: 'Contract templates',
        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">Contract templates</p>
                    <h1 class="template-hero__title">Reusable contract layouts for <?= htmlspecialchars($companyDisplayName) ?></h1>
                    <p class="template-hero__subtitle">Standardize headers, footers, and modules to generate contracts faster.</p>
                </div>
                <div class="template-hero__meta">
                    <span class="status-chip"><?= count($templates) ?> total</span>
                    <a href="#template-builder" class="btn-primary">New contract template</a>
                </div>
            </section>
        </div>

        <div class="dash-section" id="template-builder">
            <section class="card template-builder-card">
                <div class="template-builder-form">
                    <form method="POST" action="/contract_templates.php<?= $workspaceQuery ?>#template-builder">
                        <input type="hidden" name="action" value="<?= $editingTemplate ? 'update' : 'create' ?>">
                        <?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($editingTemplate ? ($formDataEdit['name'] ?? '') : ($formDataCreate['name'] ?? '')) ?>"
                                class="field-input"
                                required
                                placeholder="e.g. Master Services Agreement"
                            >
                        </label>

                        <label class="form-field">
                            <span>Description</span>
                            <textarea name="description" class="field-input" rows="3" placeholder="Short description to help your team pick the right template."><?= h($editingTemplate ? ($formDataEdit['description'] ?? '') : ($formDataCreate['description'] ?? '')) ?></textarea>
                        </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 contract</p>
                                </div>
                            </div>
                            <?php if (function_exists('renderTinyMCEVariableInserts')) { renderTinyMCEVariableInserts($availableVariables); } ?>
                            <textarea
                                name="header_html"
                                id="contract_template_header"
                                class="editor-area rich"
                                rows="12"
                            ><?= h($editingTemplate ? ($formDataEdit['header_html'] ?? '') : ($formDataCreate['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 at the bottom of the contract PDF</p>
                                </div>
                            </div>
                            <?php if (function_exists('renderTinyMCEVariableInserts')) { renderTinyMCEVariableInserts($availableVariables); } ?>
                            <textarea
                                name="footer_html"
                                id="contract_template_footer"
                                class="editor-area rich"
                                rows="10"
                            ><?= h($editingTemplate ? ($formDataEdit['footer_html'] ?? '') : ($formDataCreate['footer_html'] ?? '')) ?></textarea>
                        </div>

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

        <div class="dash-section">
            <section class="card">
                <div class="template-library__header">
                    <div>
                        <p class="section-title">Template library</p>
                        <p class="template-section-subtitle">Contract templates available in this workspace</p>
                    </div>
                </div>

                <?php if ($templates): ?>
                    <div class="template-library-grid">
                        <?php foreach ($templates as $template): ?>
                            <div class="template-library-card">
                                <div class="template-library-card__top">
                                    <div>
                                        <h3 class="template-library-card__title"><?= h($template['name']) ?></h3>
                                        <p class="template-library-card__meta">Updated <?= h(date('M j, Y', strtotime($template['updated_at'] ?? $template['created_at']))) ?></p>
                                    </div>
                                    <span class="status-chip">Contract</span>
                                </div>

                                <div class="template-library-card__details">
                                    <span>ID #<?= (int) $template['id'] ?></span>
                                    <span><?= h($template['description'] ?? '') ?></span>
                                </div>

                                <div class="template-library-card__actions">
                                    <div class="template-library-card__actions-left">
                                        <a href="/contract_template_preview.php?id=<?= (int) $template['id'] ?><?= $workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '' ?>" class="btn-secondary btn-sm">Preview</a>
                                        <a href="/contract_templates.php?edit=<?= (int) $template['id'] ?><?= $workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '' ?>#template-builder" class="btn-secondary btn-sm">Edit</a>
                                        <a href="/contract_template_modules.php?id=<?= (int) $template['id'] ?><?= $workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '' ?>" class="btn-secondary btn-sm">Modules</a>
                                        <a href="/contract_create.php?step=2&template_id=<?= (int) $template['id'] ?><?= $workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '' ?>" class="btn-secondary btn-sm">Create contract</a>
                                    </div>
                                    <form method="POST" action="/contract_templates.php<?= $workspaceQuery ?>" onsubmit="return confirm('Delete this template?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= (int) $template['id'] ?>">
                                        <button type="submit" class="btn-danger btn-sm">Delete</button>
                                    </form>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="empty-state">
                        <div class="empty-icon">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="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"></path>
                            </svg>
                        </div>
                        <h3 class="empty-title">No contract templates yet</h3>
                        <p class="empty-desc">Create your first contract template to standardize contract creation.</p>
                        <a href="#template-builder" class="btn-primary">Create contract template</a>
                    </div>
                <?php endif; ?>
            </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);
    }
    if (typeof window.initializeRichEditors === 'function') {
        window.initializeRichEditors();
    }
});
</script>

</body>
</html>
