<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/secure_workspace.php';
require_once __DIR__ . '/../src/Permissions/require_permission.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Contract.php';
require_once __DIR__ . '/../src/Proposal.php';
require_once __DIR__ . '/../src/Client.php';
require_once __DIR__ . '/../src/ContractTemplate.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/navigation.php';

// Check permission
requirePermission('contracts_create');

$errors = [];
$successMessage = $_GET['success'] ?? null;

$step = (int) ($_GET['step'] ?? 1);
$clientId = (int) ($_GET['client_id'] ?? 0);
$templateId = (int) ($_GET['template_id'] ?? 0);
$contractId = (int) ($_GET['contract_id'] ?? 0);
$editMode = $contractId > 0;

// Load proposals for the selected client
$clientProposals = [];
if ($clientId > 0) {
    $pdo = getPDO();
    $stmt = $pdo->prepare('SELECT * FROM proposals WHERE client_id = ? ORDER BY created_at DESC');
    $stmt->execute([$clientId]);
    $clientProposals = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Load existing contract data if editing
if ($editMode) {
    $existingContract = Contract::find($contractId);
    if (!$existingContract) {
        $errors[] = 'Contract not found.';
        $editMode = false;
    } else {
        $clientId = $existingContract['client_id'];
        // Only force step 3 if we're not already on step 4
        if ($step !== 4) {
            $step = 3; // Skip to step 3 for editing
        }
        $contractData = [
            'modules' => $existingContract['modules_json'] ?? [],
            'variables' => $existingContract['variables_json'] ?? [],
            'pricing' => [],
            'currency' => 'USD',
            'proposal_id' => $existingContract['proposal_id'] ?? null,
        ];
    }
}

$client = $clientId > 0 ? Client::find($clientId) : null;
$template = $templateId > 0 ? ContractTemplate::find($templateId) : null;
$attachedModules = [];
// Load all proposals (used for Link Proposal selector modal, like invoice_create)
$allProposals = Proposal::all();
if ($editMode && !empty($existingContract['modules_json'])) {
    $attachedModules = $existingContract['modules_json'];
} elseif ($template) {
    $attachedModules = ContractTemplate::getModules($templateId);
}

if (!$editMode) {
    $contractData = [
        'modules' => $attachedModules,
        'variables' => [],
        'pricing' => [],
        'currency' => 'USD',
    ];
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    // Step 1: handle template selection like proposal wizard
    if ($action === 'set_template' && $step === 1) {
        $selectedTemplateId = (int) ($_POST['template_id'] ?? 0);
        if ($selectedTemplateId > 0) {
            $templateExists = ContractTemplate::find($selectedTemplateId);
            if ($templateExists) {
                $params = [
                    'step' => 2,
                    'template_id' => $selectedTemplateId,
                ];
                if (isset($_GET['workspace'])) {
                    $params['workspace'] = $_GET['workspace'];
                }
                $query = http_build_query($params);
                header('Location: /contract_create.php?' . $query);
                exit;
            }
        }
    }

    // Step 2: handle client selection similar to proposal wizard
    if ($action === 'set_client' && $step === 2) {
        $selectedClientId = (int) ($_POST['client_id'] ?? 0);
        if ($selectedClientId > 0) {
            $clientExists = Client::find($selectedClientId);
            if ($clientExists) {
                // Ensure we carry template forward
                $currentTemplateId = (int) ($_POST['template_id'] ?? $templateId);
                $params = [
                    'step' => 3,
                    'client_id' => $selectedClientId,
                    'template_id' => $currentTemplateId,
                ];
                if (isset($_GET['workspace'])) {
                    $params['workspace'] = $_GET['workspace'];
                } elseif (isset($_POST['workspace'])) {
                    $params['workspace'] = $_POST['workspace'];
                }
                $query = http_build_query($params);
                header('Location: /contract_create.php?' . $query);
                exit;
            }
        }
    }

    if ($action === 'save_contract' && $step === 3) {
        // Decode JSON strings from form
        $modulesJson = json_decode($_POST['modules_json'] ?? '[]', true) ?: [];
        $variablesJson = json_decode($_POST['variables_json'] ?? '{}', true) ?: [];
        $pricingJson = json_decode($_POST['pricing_json'] ?? '[]', true) ?: [];
        
        // Collect party information
        $partyInfo = [
            'party1_name' => $_POST['party1_name'] ?? '',
            'party1_email' => $_POST['party1_email'] ?? '',
            'party1_company' => $_POST['party1_company'] ?? '',
            'party1_phone' => $_POST['party1_phone'] ?? '',
            'party1_address' => $_POST['party1_address'] ?? '',
            'party2_name' => $_POST['party2_name'] ?? '',
            'party2_email' => $_POST['party2_email'] ?? '',
            'party2_title' => $_POST['party2_title'] ?? '',
            'party2_phone' => $_POST['party2_phone'] ?? '',
            'party2_company' => $_POST['party2_company'] ?? ''
        ];
        
        // Validate all foreign key references
        $proposalId = $_POST['proposal_id'] ?? null;
        // Convert empty string to null
        if ($proposalId === '') {
            $proposalId = null;
        }
        
        if ($proposalId && !empty($proposalId)) {
            error_log('Validating proposal ID: ' . $proposalId);
            // Check if proposal exists
            $proposal = Proposal::find((int) $proposalId);
            if (!$proposal) {
                error_log('Proposal validation failed - ID: ' . $proposalId);
                $_SESSION['error'] = 'Selected proposal not found';
                $workspaceParam = isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '';
                header('Location: /contract_create.php?step=3' . $workspaceParam);
                exit;
            }
            error_log('Proposal validation passed');
        }
        
        // Validate client exists
        error_log('Validating client ID: ' . $clientId);
        $client = Client::find((int) $clientId);
        if (!$client) {
            error_log('Client validation failed - ID: ' . $clientId);
            $_SESSION['error'] = 'Selected client not found';
            $workspaceParam = isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '';
            header('Location: /contract_create.php?step=3' . $workspaceParam);
            exit;
        }
        error_log('Client validation passed');
        
        // Validate contract template exists
        error_log('Validating template ID: ' . $templateId);
        $template = ContractTemplate::find((int) $templateId);
        if (!$template) {
            error_log('Template validation failed - ID: ' . $templateId);
            $_SESSION['error'] = 'Selected contract template not found';
            $workspaceParam = isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '';
            header('Location: /contract_create.php?step=3' . $workspaceParam);
            exit;
        }
        error_log('Template validation passed');
        
        error_log('All validations passed, proceeding with contract creation');
        
        $proposalInput = $_POST['proposal_id'] ?? null;
        if ($proposalInput === '') {
            $proposalInput = null;
        }

        $contractId = Contract::create([
            'client_id' => $clientId,
            'contract_template_id' => $templateId,
            'title' => $_POST['title'] ?? 'Contract',
            'modules_json' => $modulesJson,
            'variables_json' => array_merge($variablesJson, $partyInfo),
            'pricing_json' => $pricingJson,
            'currency' => $_POST['currency'] ?? 'USD',
            'status' => 'draft',
            'workspace' => $_GET['workspace'] ?? null,
            // Persist linked proposal like update_contract path so PDF can show proposal number
            'proposal_id' => $proposalInput,
            'party_info' => $partyInfo,
        ]);
        
        // Log contract creation in workspace activity (best-effort)
        workspace_log(
            'contract_created',
            'contract',
            (int) $contractId,
            $_POST['title'] ?? 'Contract',
            null,
            [
                'client_id' => $clientId,
                'template_id' => $templateId,
                'proposal_id' => $proposalInput,
                'currency' => $_POST['currency'] ?? 'USD',
            ]
        );
        
        // Generate PDF automatically like proposals
        try {
            Contract::generatePdf($contractId, null, $_GET['workspace'] ?? null);
        } catch (Exception $e) {
            // Continue even if PDF generation fails
            error_log('PDF generation failed: ' . $e->getMessage());
        }
        
        $workspaceParam = isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '';
        header("Location: /contract_create.php?step=4&contract_id=$contractId&success=1" . $workspaceParam);
        exit;
    }
    
    if ($action === 'update_contract' && $editMode && $step === 3) {
        // Decode JSON strings from form
        $modulesJson = json_decode($_POST['modules_json'] ?? '[]', true) ?: [];
        $variablesJson = json_decode($_POST['variables_json'] ?? '{}', true) ?: [];
        $pricingJson = json_decode($_POST['pricing_json'] ?? '[]', true) ?: [];
        
        // Collect party information
        $partyInfo = [
            'party1_name' => $_POST['party1_name'] ?? '',
            'party1_email' => $_POST['party1_email'] ?? '',
            'party1_company' => $_POST['party1_company'] ?? '',
            'party1_phone' => $_POST['party1_phone'] ?? '',
            'party1_address' => $_POST['party1_address'] ?? '',
            'party2_name' => $_POST['party2_name'] ?? '',
            'party2_email' => $_POST['party2_email'] ?? '',
            'party2_title' => $_POST['party2_title'] ?? '',
            'party2_phone' => $_POST['party2_phone'] ?? '',
            'party2_company' => $_POST['party2_company'] ?? ''
        ];
        
        Contract::update($contractId, [
            'modules_json' => $modulesJson,
            'variables_json' => array_merge($variablesJson, $partyInfo),
            'pricing_json' => $pricingJson,
            'currency' => $_POST['currency'] ?? 'USD',
            'proposal_id' => $_POST['proposal_id'] ?? null,
        ]);
        
        // Regenerate PDF like proposals (automatically increments version)
        try {
            Contract::generatePdf($contractId, null, $_GET['workspace'] ?? null);
        } catch (Exception $e) {
            // Continue even if PDF generation fails
            error_log('PDF generation failed: ' . $e->getMessage());
        }
        
        // Log contract update in workspace activity (best-effort)
        workspace_log(
            'contract_updated',
            'contract',
            (int) $contractId,
            $existingContract['title'] ?? ($_POST['title'] ?? 'Contract'),
            null,
            [
                'currency' => $_POST['currency'] ?? 'USD',
            ]
        );
        
        $workspaceParam = isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '';
        header("Location: /contract_create.php?step=4&contract_id=$contractId&success=1" . $workspaceParam);
        exit;
    }
}

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

$workspaceSlug = $_GET['workspace'] ?? null;
$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode((string) $workspaceSlug) : '';
?>
<!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><?= $editMode ? 'Edit Contract' : 'Create Contract' ?> · 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
    $tinymceComponent = __DIR__ . '/components/editors/tinymce-init.php';
    if (file_exists($tinymceComponent)) {
        require_once $tinymceComponent;
        if (function_exists('renderTinyMCEInit')) {
            renderTinyMCEInit();
        }
    }
    ?>
    <script>
        function insertVariable(variable) {
            const activeEditor = window.tinymce ? tinymce.activeEditor : null;
            if (activeEditor) {
                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' => 'All contracts',
            'url' => '/contracts.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,
        ],
    ];

    renderPageHeader(
        breadcrumbs: [
            ['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: $editMode ? 'Edit contract' : 'Create contract',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

    <div class="dash-container proposal-wizard">
        <div class="dash-section">
            <section class="card" style="margin-bottom: 0;">
                <div style="display: flex; flex-direction: column; gap: 12px;">
                    <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px;">
                        <div>
                            <p class="section-title">Contract builder</p>
                            <h2 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 4px 0;">
                                <?= $editMode ? 'Edit contract' : 'Create contract' ?>
                            </h2>
                            <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Generate a new contract in 4 compact steps.</p>
                        </div>
                    </div>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <div class="flex items-center justify-between">
                <div class="flex items-center">
                    <div class="flex items-center justify-center w-8 h-8 rounded-full <?= $step >= 1 ? 'bg-neutral-50 text-neutral-900' : 'bg-neutral-900 text-neutral-500' ?> font-medium text-xs">1</div>
                    <div class="ml-3">
                        <div class="text-xs font-medium <?= $step >= 1 ? 'text-neutral-50' : 'text-neutral-500' ?>">Template</div>
                        <div class="text-[11px] text-neutral-500">Choose contract template</div>
                    </div>
                </div>
                <div class="flex-1 mx-4"><div class="h-0.5 rounded-full <?= $step >= 2 ? 'bg-neutral-50' : 'bg-neutral-900' ?>"></div></div>
                <div class="flex items-center">
                    <div class="flex items-center justify-center w-8 h-8 rounded-full <?= $step >= 2 ? 'bg-neutral-50 text-neutral-900' : 'bg-neutral-900 text-neutral-500' ?> font-medium text-xs">2</div>
                    <div class="ml-3">
                        <div class="text-xs font-medium <?= $step >= 2 ? 'text-neutral-50' : 'text-neutral-500' ?>">Client</div>
                        <div class="text-[11px] text-neutral-500">Select client for contract</div>
                    </div>
                </div>
                <div class="flex-1 mx-4"><div class="h-0.5 rounded-full <?= $step >= 3 ? 'bg-neutral-50' : 'bg-neutral-900' ?>"></div></div>
                <div class="flex items-center">
                    <div class="flex items-center justify-center w-8 h-8 rounded-full <?= $step >= 3 ? 'bg-neutral-50 text-neutral-900' : 'bg-neutral-900 text-neutral-500' ?> font-medium text-xs">3</div>
                    <div class="ml-3">
                        <div class="text-xs font-medium <?= $step >= 3 ? 'text-neutral-50' : 'text-neutral-500' ?>">Content</div>
                        <div class="text-[11px] text-neutral-500">Customize modules and variables</div>
                    </div>
                </div>
                <div class="flex-1 mx-4"><div class="h-0.5 rounded-full <?= $step >= 4 ? 'bg-neutral-50' : 'bg-neutral-900' ?>"></div></div>
                <div class="flex items-center">
                    <div class="flex items-center justify-center w-8 h-8 rounded-full <?= $step >= 4 ? 'bg-neutral-50 text-neutral-900' : 'bg-neutral-900 text-neutral-500' ?> font-medium text-xs">4</div>
                    <div class="ml-3">
                        <div class="text-xs font-medium <?= $step >= 4 ? 'text-neutral-50' : 'text-neutral-500' ?>">Review & Generate</div>
                        <div class="text-[11px] text-neutral-500">Preview and generate PDF</div>
                    </div>
                </div>
            </div>
        </div>

        <?php if ($successMessage): ?>
            <div class="dash-section">
                <div class="status-banner success">
                    <span>Contract saved successfully.</span>
                </div>
            </div>
        <?php endif; ?>

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

    <?php if ($step === 1): ?>
        <?php $templates = ContractTemplate::all(); ?>
        <div class="dash-section">
        <section class="card" style="margin-bottom: 0;">
            <div style="padding: 16px 20px; border-bottom: 1px solid var(--border-subtle); display: flex; flex-direction: column; gap: 6px;">
                <div style="display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;">
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <div style="width: 32px; height: 32px; border-radius: 8px; background: var(--bg-surface); border: 1px solid var(--border-default); display: flex; align-items: center; justify-content: center; color: var(--text-secondary);">
                            <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path>
                            </svg>
                        </div>
                        <div>
                            <p class="section-title" style="margin-bottom: 2px;">Select template</p>
                            <p style="font-size: 11px; color: var(--text-tertiary); margin: 0;">Pick a base layout to start customizing your contract.</p>
                        </div>
                    </div>
                    <span style="font-size: 11px; color: var(--text-tertiary);"><?= count($templates) ?> templates available</span>
                </div>
            </div>
            <div class="p-4 md:p-6">
                <form method="POST">
                    <input type="hidden" name="action" value="set_template">
                    <?php if (isset($_GET['workspace'])): ?>
                        <input type="hidden" name="workspace" value="<?= h($_GET['workspace']) ?>">
                    <?php endif; ?>

                    <?php if ($templates): ?>
                        <div class="template-grid">
                            <?php foreach ($templates as $t): ?>
                                <label class="template-card__option">
                                    <input type="radio" name="template_id" value="<?= (int) $t['id'] ?>" required class="template-card__radio">
                                    <div class="template-card">
                                        <div class="template-card__top">
                                            <div class="template-card__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>
                                            <span class="template-card__check"></span>
                                        </div>
                                        <div class="template-card__body">
                                            <h3><?= h($t['name']) ?></h3>
                                            <p><?= h($t['description'] ?? 'Structured sections for signing, scope, and terms.') ?></p>
                                        </div>
                                        <div class="template-card__meta">
                                            <span class="status-chip">
                                                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <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>
                                                <?= count(ContractTemplate::getModules($t['id'])) ?> modules
                                            </span>
                                            <span style="font-size: 11px; color: var(--text-tertiary);">Ready-to-send</span>
                                        </div>
                                    </div>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="empty-state" style="border: 2px dashed var(--border-subtle); border-radius: 8px; background: var(--bg-surface);">
                            <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" style="max-width: 360px; margin: 0 auto 16px;">Create your first contract template to start generating professional contracts.</p>
                            <a href="/contract_templates.php<?= isset($_GET['workspace']) ? '?workspace=' . urlencode($_GET['workspace']) : '' ?>" class="btn-primary" style="justify-content: center;">
                                <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                                </svg>
                                Create template
                            </a>
                        </div>
                    <?php endif; ?>

                    <div style="margin-top: 24px; padding-top: 12px; border-top: 1px solid var(--border-subtle); display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;">
                        <button type="button" onclick="history.back()" class="btn-secondary" style="font-size: 11px; padding: 4px 8px;">
                            <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                            </svg>
                            <span>Back</span>
                        </button>
                        <div style="display: flex; align-items: center; gap: 8px;">
                            <span style="font-size: 11px; color: var(--text-tertiary);" class="hidden sm:inline">Next: pick a client</span>
                            <button type="submit" class="btn-primary">
                                <span>Continue</span>
                                <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                                </svg>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </section>
        </div>
    <?php elseif ($step === 2): ?>
        <?php $clients = Client::all(); ?>
        <div class="dash-section">
        <section class="card" style="margin-bottom: 0;">
            <div class="px-4 md:px-6 py-3 border-b border-neutral-800">
                <h2 class="text-sm font-semibold text-neutral-50 flex items-center gap-3">
                    <div class="p-1.5 bg-amber-500/10 rounded-lg">
                        <svg class="w-4 h-4 text-amber-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283-.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                        </svg>
                    </div>
                    Select a client
                    <span class="ml-auto text-[11px] font-normal text-neutral-400"><?= count($clients) ?> clients available</span>
                </h2>
                <p class="text-xs text-neutral-400 mt-1 ml-9">Choose the client for this contract</p>
            </div>
            <div class="p-4 md:p-6">
                <div class="mb-6">
                    <div class="input-with-icon">
                        <input type="text" id="clientSearch" placeholder="Search clients by name or company..." class="input" autocomplete="off">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                        </svg>
                    </div>
                    <div style="margin-top: 4px; font-size: 11px; color: var(--text-tertiary);">
                        <span id="searchHint">Start typing to search clients...</span>
                        <span id="searchCount" class="hidden"></span>
                    </div>
                </div>

                <div class="client-grid" id="clientList">
                    <?php foreach ($clients as $c): ?>
                        <?php
                        $clientInitialSource = $c['name'] ?? 'C';
                        if (function_exists('mb_substr')) {
                            $clientInitial = mb_strtoupper(mb_substr($clientInitialSource, 0, 1, 'UTF-8'), 'UTF-8');
                        } else {
                            $clientInitial = strtoupper(substr($clientInitialSource, 0, 1));
                        }
                        ?>
                        <div
                            class="client-card client-item"
                            data-client-name="<?= strtolower(h($c['name'])) ?>"
                            data-client-company="<?= strtolower(h($c['company'] ?? '')) ?>"
                            data-client-email="<?= strtolower(h($c['email'] ?? '')) ?>"
                            onclick="selectClient(<?= (int) $c['id'] ?>)"
                            style="cursor: pointer;"
                        >
                            <div style="display: flex; align-items: center; justify-content: space-between; gap: 12px;">
                                <div style="display: flex; align-items: center; gap: 12px; flex: 1; min-width: 0;">
                                    <div style="width: 32px; height: 32px; border-radius: 3px; display: flex; align-items: center; justify-content: center; background: var(--bg-surface); border: 1px solid var(--border-default); color: var(--text-primary); font-size: 12px; font-weight: 600; flex-shrink: 0;">
                                        <?= h($clientInitial ?: 'C') ?>
                                    </div>
                                    <div style="flex: 1; min-width: 0;">
                                        <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-bottom: 4px;">
                                            <h3 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 0;">
                                                <?= h($c['name']) ?>
                                            </h3>
                                            <?php if ($c['company']): ?>
                                                <span style="display: inline-flex; align-items: center; padding: 2px 6px; border-radius: 3px; background: var(--bg-surface); color: var(--text-secondary); font-size: 10px; font-weight: 500;">
                                                    <?= h($c['company']) ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                        <?php if ($c['email']): ?>
                                            <p style="font-size: 11px; color: var(--text-tertiary); margin: 0;">
                                                <?= h($c['email']) ?>
                                            </p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <svg style="width: 14px; height: 14px; color: var(--text-tertiary); flex-shrink: 0;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                                </svg>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </section>
        </div>

        <script>
        const CLIENTS = <?= json_encode($clients) ?>;

        function filterClients() {
            const term = (document.getElementById('clientSearch')?.value || '').toLowerCase().trim();
            const hint = document.getElementById('searchHint');
            const count = document.getElementById('searchCount');
            const items = document.querySelectorAll('.client-item');
            let visibleCount = 0;

            items.forEach(item => {
                const name = item.dataset.clientName || '';
                const company = item.dataset.clientCompany || '';
                const email = item.dataset.clientEmail || '';
                const matches = !term || name.includes(term) || company.includes(term) || email.includes(term);
                item.style.display = matches ? '' : 'none';
                if (matches) visibleCount++;
            });

            if (!term) {
                if (hint) hint.classList.remove('hidden');
                if (count) count.classList.add('hidden');
            } else {
                if (hint) hint.classList.add('hidden');
                if (count) {
                    count.classList.remove('hidden');
                    count.textContent = visibleCount + ' client' + (visibleCount === 1 ? '' : 's') + ' found';
                }
            }
        }

        function selectClient(clientId) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="action" value="set_client">
                <input type="hidden" name="client_id" value="${clientId}">
                <input type="hidden" name="template_id" value="<?= (int) $templateId ?>">
                <?php if (isset($_GET['workspace'])): ?>
                    <input type="hidden" name="workspace" value="<?= h($_GET['workspace']) ?>">
                <?php endif; ?>
            `;
            document.body.appendChild(form);
            form.submit();
        }

        document.addEventListener('DOMContentLoaded', function () {
            const input = document.getElementById('clientSearch');
            if (input) {
                input.addEventListener('input', filterClients);
            }
        });
        </script>

    <!-- Step 3: Customize Modules -->
    <?php elseif ($step === 3): ?>
        <div class="dash-section">
        <section class="card">
            <div class="proposal-step-card-header">
                <div style="display: flex; align-items: center; gap: 12px;">
                    <div class="step-icon">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <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>
                    </div>
                    <div>
                        <p class="section-title" style="margin-bottom: 2px;">Configure modules & variables</p>
                        <p class="section-subtitle">Fine-tune module copy, drop in merge fields, and confirm party details.</p>
                    </div>
                </div>
                <span class="step-tag">Step 3 of 4</span>
            </div>

            <div class="p-4 md:p-6">
                <form method="POST" id="contract-form">
                    <input type="hidden" name="action" value="<?= $editMode ? 'update_contract' : 'save_contract' ?>">
                    <input type="hidden" name="modules_json" id="modules-json">
                    <input type="hidden" name="variables_json" id="variables-json">
                    <input type="hidden" name="pricing_json" id="pricing-json">
                    <input type="hidden" name="currency" id="currency" value="<?= h($contractData['currency']) ?>">
                    <input type="hidden" name="title" value="<?= h($client['name']) ?> - <?= h($template['name']) ?>">

                    <?php
                    $variableTokens = [
                        ['label' => 'Client name', 'token' => '{{client_name}}'],
                        ['label' => 'Company', 'token' => '{{company_name}}'],
                        ['label' => 'Project', 'token' => '{{project_name}}'],
                        ['label' => 'Contract date', 'token' => '{{contract_date}}'],
                        ['label' => 'Client email', 'token' => '{{client_email}}'],
                        ['label' => 'Client phone', 'token' => '{{client_phone}}'],
                        ['label' => 'Client address', 'token' => '{{client_address}}'],
                    ];

                    $variablesExisting = $contractData['variables'] ?? [];

                    $linkedProposalTitle = '';
                    $linkedProposalId = null;
                    if (!empty($existingContract['proposal_id'] ?? null)) {
                        $linkedProposalId = (int) $existingContract['proposal_id'];
                        $linkedProposal = Proposal::find($linkedProposalId);
                        if ($linkedProposal) {
                            $linkedProposalTitle = $linkedProposal['title'] ?? '';
                        }
                    }
                    ?>

                    <div class="info-panel" style="margin-top: 0;">
                        <div class="info-panel__header">
                            <div class="step-icon" style="width: 28px; height: 28px;">
                                <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>
                            <div>
                                <p class="info-panel__title">Link proposal</p>
                                <p class="info-panel__subtitle">Optionally attach an existing proposal to this contract.</p>
                            </div>
                        </div>

                        <label class="form-field">
                            <span>Proposal</span>
                            <div class="input-with-icon">
                                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                </svg>
                                <input
                                    type="text"
                                    id="proposalDisplay"
                                    readonly
                                    value="<?= $linkedProposalTitle ? h($linkedProposalTitle) : '' ?>"
                                    class="field-input"
                                    placeholder="Search and select proposal"
                                    onclick="showProposalSelector()"
                                >
                            </div>
                            <input type="hidden" name="proposal_id" id="proposalId" value="<?= $linkedProposalId ? (int) $linkedProposalId : '' ?>">
                        </label>
                    </div>

                    <div class="info-panel">
                        <div class="info-panel__header">
                            <div class="step-icon" style="width: 28px; height: 28px;">
                                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283-.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                </svg>
                            </div>
                            <div>
                                <p class="info-panel__title">Party information</p>
                                <p class="info-panel__subtitle">Confirm party details that will be merged into the contract.</p>
                            </div>
                        </div>

                        <div class="party-info-grid">
                            <div class="party-info-column">
                                <label class="form-field">
                                    <span>Party 1 name *</span>
                                    <input type="text" name="party1_name" required class="field-input" value="<?= h($variablesExisting['party1_name'] ?? ($client['name'] ?? '')) ?>" placeholder="Client full name">
                                </label>
                                <label class="form-field">
                                    <span>Party 1 email *</span>
                                    <input type="email" name="party1_email" required class="field-input" value="<?= h($variablesExisting['party1_email'] ?? ($client['email'] ?? '')) ?>" placeholder="Client email">
                                </label>
                                <label class="form-field">
                                    <span>Party 1 company</span>
                                    <input type="text" name="party1_company" class="field-input" value="<?= h($variablesExisting['party1_company'] ?? ($client['company'] ?? '')) ?>" placeholder="Client company">
                                </label>
                                <label class="form-field">
                                    <span>Party 1 phone</span>
                                    <input type="tel" name="party1_phone" class="field-input" value="<?= h($variablesExisting['party1_phone'] ?? ($client['phone'] ?? '')) ?>" placeholder="Client phone">
                                </label>
                            </div>

                            <div class="party-info-column">
                                <label class="form-field">
                                    <span>Party 2 name *</span>
                                    <input type="text" name="party2_name" required class="field-input" value="<?= h($variablesExisting['party2_name'] ?? '') ?>" placeholder="Your representative name">
                                </label>
                                <label class="form-field">
                                    <span>Party 2 email *</span>
                                    <input type="email" name="party2_email" required class="field-input" value="<?= h($variablesExisting['party2_email'] ?? '') ?>" placeholder="Your representative email">
                                </label>
                                <label class="form-field">
                                    <span>Party 2 title</span>
                                    <input type="text" name="party2_title" class="field-input" value="<?= h($variablesExisting['party2_title'] ?? '') ?>" placeholder="e.g. CEO, Project Manager">
                                </label>
                                <label class="form-field">
                                    <span>Party 2 company</span>
                                    <input type="text" name="party2_company" class="field-input" value="<?= h($variablesExisting['party2_company'] ?? '') ?>" placeholder="Your company name">
                                </label>
                            </div>
                        </div>
                    </div>

                    <div class="module-stack" style="margin-top: 18px;">
                        <?php foreach ($attachedModules as $index => $m): ?>
                            <?php
                            $moduleId = (int) ($m['id'] ?? 0);
                            $moduleName = (string) ($m['name'] ?? ($m['title'] ?? 'Module'));
                            $moduleCategory = (string) ($m['category'] ?? 'legal');
                            $modulePrice = (float) ($m['price'] ?? 0);
                            $moduleContent = (string) ($m['content'] ?? ($m['description'] ?? ($m['content_html'] ?? '')));
                            $templateEnabled = isset($m['enabled']) ? (int) $m['enabled'] === 1 : true;
                            $isRequired = false;
                            $isEnabled = $templateEnabled;
                            ?>
                            <div class="module-card<?= $isEnabled ? '' : ' module-card--disabled' ?>" data-module-id="<?= $moduleId ?>" data-module-name="<?= h($moduleName) ?>" data-module-price="<?= h((string) $modulePrice) ?>" data-module-category="<?= h($moduleCategory) ?>" data-module-required="false">
                                <div class="module-card__head">
                                    <div>
                                        <p class="eyebrow">Module <?= $index + 1 ?></p>
                                        <div class="module-card__title-row">
                                            <h3><?= h($moduleName) ?></h3>
                                        </div>
                                        <p class="module-card__label"><?= h($moduleCategory) ?></p>
                                    </div>
                                    <label class="module-toggle">
                                        <input
                                            type="checkbox"
                                            class="module-enabled"
                                            value="1"
                                            <?= $isEnabled ? 'checked' : '' ?>
                                            onchange="toggleModuleState(this)"
                                            data-target="module-<?= $moduleId ?>"
                                        >
                                        <span class="module-toggle__control"></span>
                                        <span class="module-toggle__label<?= $isEnabled ? '' : ' is-disabled' ?>"><?= $isEnabled ? 'Enabled' : 'Disabled' ?></span>
                                    </label>
                                </div>
                                <div class="module-card__body<?= $isEnabled ? '' : ' is-disabled' ?>" id="module-<?= $moduleId ?>">
                                    <div class="module-card__inserts">
                                        <p>Quick inserts</p>
                                        <div class="chip-group">
                                            <?php foreach ($variableTokens as $variable): ?>
                                                <button type="button" class="variable-chip" onclick="insertVariable('<?= h($variable['token']) ?>')">
                                                    <?= h($variable['label']) ?>
                                                </button>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                    <textarea id="rich_<?= $moduleId ?>" class="editor-area rich" rows="12"><?= h($moduleContent) ?></textarea>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <div class="info-panel" id="variables-panel">
                        <div class="info-panel__header">
                            <div class="step-icon" style="width: 28px; height: 28px;">
                                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                </svg>
                            </div>
                            <div>
                                <p class="info-panel__title">Variables</p>
                                <p class="info-panel__subtitle">Provide values for placeholders used across the selected modules.</p>
                            </div>
                        </div>
                        <div id="variables-section"></div>
                        <p class="info-panel__hint">Tip: click a token above to insert it into the active editor.</p>
                    </div>

                    <div class="mt-6" style="padding-top: 12px; border-top: 1px solid var(--border-subtle); display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;">
                        <a href="?step=2&template_id=<?= $templateId ?><?= isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '' ?>" class="btn-secondary" style="font-size: 11px; padding: 4px 8px;">
                            <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                            </svg>
                            <span>Back</span>
                        </a>
                        <div style="display: flex; align-items: center; gap: 8px;">
                            <span style="font-size: 11px; color: var(--text-tertiary);" class="hidden sm:inline">Step 3 of 4 · Review content</span>
                            <button type="submit" class="btn-emerald">
                                <span><?= $editMode ? 'Update contract' : 'Generate contract' ?></span>
                                <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                </svg>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </section>
        </div>

    <!-- Step 4: Generate Contract -->
    <?php elseif ($step === 4): ?>
        <?php
            $contract = $contractId > 0 ? Contract::find($contractId) : null;
            $timestamp = time();
            $workspaceParam = isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '';
            $viewLink = "/download.php?action=view&contract_id={$contractId}&t={$timestamp}&force=1{$workspaceParam}";
            $contractNumber = $contract['contract_number'] ?? ('CTR-' . $contractId);
            $clientSigningToken = (string) ($contract['signing_token_client'] ?? '');
            $shareLink = $clientSigningToken !== ''
                ? ("/contract_sign.php?token=" . urlencode($clientSigningToken) . $workspaceParam)
                : '';
            $editLink = "/contract_create.php?contract_id=" . (int) $contractId . "&edit=1" . $workspaceParam;
        ?>

        <div class="dash-section">
        <section class="card wizard-complete-card">
            <div class="wizard-complete-card__header">
                <div class="wizard-success-icon">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                </div>
                <div>
                    <p class="wizard-complete-card__title">Contract ready</p>
                    <p class="wizard-complete-card__subtitle">All modules compiled and the PDF is ready to share.</p>
                </div>
                <div class="proposal-id-chip">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
                    </svg>
                    <span>Contract ID: <?= h((string) $contractNumber) ?></span>
                </div>
            </div>

            <div class="wizard-complete-card__actions">
                <a href="<?= $viewLink ?>" target="_blank" class="btn-secondary">
                    <svg style="width: 14px; height: 14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                    </svg>
                    View
                </a>
                <a href="<?= $viewLink ?>" target="_blank" class="btn-emerald">
                    <svg style="width: 14px; height: 14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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>
                    Download PDF
                </a>
                <button type="button" onclick="showSharePopup()" class="btn-secondary">Share for signing</button>
                <a href="<?= $editLink ?>" class="btn-secondary">Edit contract</a>
                <a href="/contracts.php<?= isset($_GET['workspace']) ? '?workspace=' . urlencode($_GET['workspace']) : '' ?>" class="btn-secondary">All contracts</a>
            </div>

            <div class="wizard-complete-card__downloads">
                <div class="proposal-download-card">
                    <div class="proposal-download-card__content">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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>
                            <p class="proposal-download-card__title">Download contract PDF</p>
                            <p class="proposal-download-card__subtitle">Get the latest version with current signatures</p>
                        </div>
                    </div>
                    <a href="<?= $viewLink ?>" target="_blank" class="proposal-download-card__action is-primary">Download</a>
                </div>

                <div class="proposal-download-card">
                    <div class="proposal-download-card__content">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                        </svg>
                        <div>
                            <p class="proposal-download-card__title">Preview in browser</p>
                            <p class="proposal-download-card__subtitle">Open the PDF in a new tab without saving</p>
                        </div>
                    </div>
                    <a href="<?= $viewLink ?>" target="_blank" class="proposal-download-card__action">Preview</a>
                </div>
            </div>
        </section>
        </div>
    <?php endif; ?>

    <div class="delete-modal-overlay" style="position: fixed; inset: 0; z-index: 100; display: none; align-items: center; justify-content: center; padding: 16px;" id="shareModal">
        <div class="delete-modal-content">
            <div class="delete-modal-header">
                <p style="font-size: 11px; font-weight: 500; text-transform: uppercase; letter-spacing: 0.03em; color: var(--text-tertiary); margin: 0 0 8px;">Share</p>
                <h3 style="margin: 0; font-size: 14px; font-weight: 600; color: var(--text-primary);">Share contract for signing</h3>
            </div>
            <div class="delete-modal-body">
                <label class="form-field">
                    <span>Signing link</span>
                    <input type="text" id="shareLink" class="field-input" readonly value="<?= isset($shareLink) ? h($shareLink) : '' ?>" <?= empty($shareLink) ? 'placeholder="Signing link not available yet"' : '' ?>>
                </label>
                <?php if (isset($shareLink) && empty($shareLink)): ?>
                    <p class="info-panel__hint" style="margin: 0;">This contract doesn’t have a signing token yet. Try refreshing the page or regenerating the contract PDF.</p>
                <?php endif; ?>
                <div class="delete-modal-footer">
                    <button type="button" class="btn-secondary" onclick="closeSharePopup()">Cancel</button>
                    <button type="button" class="btn-primary" id="copyShareBtn" onclick="copyShareLink(event)" <?= empty($shareLink) ? 'disabled' : '' ?>>Copy link</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Proposal Selection Modal (same pattern as invoice_create) -->
    <div class="delete-modal-overlay" style="position: fixed; inset: 0; z-index: 100; display: none; align-items: center; justify-content: center; padding: 16px;" id="proposalSelectorModal">
        <div class="delete-modal-content" style="max-width: 760px;">
            <div class="delete-modal-header">
                <div style="display: flex; align-items: center; justify-content: space-between; gap: 12px;">
                    <div>
                        <p style="font-size: 11px; font-weight: 500; text-transform: uppercase; letter-spacing: 0.03em; color: var(--text-tertiary); margin: 0 0 8px;">Link proposal</p>
                        <h3 style="margin: 0; font-size: 14px; font-weight: 600; color: var(--text-primary);">Select proposal</h3>
                    </div>
                    <button type="button" onclick="closeProposalSelector()" class="btn-secondary" style="padding: 6px 10px;">Close</button>
                </div>
            </div>
            <div class="delete-modal-body">
                <label class="form-field">
                    <span>Search</span>
                    <input type="text" id="proposalSearch" class="field-input" placeholder="Search proposals...">
                </label>

                <div id="proposalList" style="display: flex; flex-direction: column; gap: 10px;">
                    <?php foreach ($allProposals as $proposal): ?>
                        <div class="proposal-row proposal-download-card" data-proposal-id="<?= (int) $proposal['id'] ?>" data-proposal-title="<?= h($proposal['title']) ?>">
                            <div class="proposal-download-card__content" style="flex: 1; min-width: 0;">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                    <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 style="min-width: 0;">
                                    <p class="proposal-download-card__title" style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"><?= h($proposal['title']) ?></p>
                                    <p class="proposal-download-card__subtitle">ID: <?= (int) $proposal['id'] ?> · Created: <?= date('M j, Y', strtotime($proposal['created_at'])) ?><?= !empty($proposal['status']) ? ' · Status: ' . h($proposal['status']) : '' ?></p>
                                </div>
                            </div>
                            <button type="button" class="proposal-download-card__action" onclick="selectProposal(<?= (int) $proposal['id'] ?>)">Select</button>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

<script>

function initializeVariables() {
    const variablesSection = document.getElementById('variables-section');
    if (!variablesSection) return;

    const partyPrefill = {
        party1_name: (document.querySelector('input[name="party1_name"]') || {}).value || '',
        party1_email: (document.querySelector('input[name="party1_email"]') || {}).value || '',
        party1_company: (document.querySelector('input[name="party1_company"]') || {}).value || '',
        party1_phone: (document.querySelector('input[name="party1_phone"]') || {}).value || '',
        party2_name: (document.querySelector('input[name="party2_name"]') || {}).value || '',
        party2_email: (document.querySelector('input[name="party2_email"]') || {}).value || '',
        party2_title: (document.querySelector('input[name="party2_title"]') || {}).value || '',
        party2_company: (document.querySelector('input[name="party2_company"]') || {}).value || '',
    };

    const existingValues = {};
    variablesSection.querySelectorAll('input[data-variable-key]').forEach(input => {
        const key = input.getAttribute('data-variable-key');
        if (key) existingValues[key] = input.value;
    });

    const variables = {};
    const moduleCards = document.querySelectorAll('.module-card');
    moduleCards.forEach(card => {
        const checkbox = card.querySelector('.module-enabled');
        if (checkbox && !checkbox.checked) {
            return;
        }

        const moduleId = card.getAttribute('data-module-id');
        const textarea = moduleId ? document.getElementById(`rich_${moduleId}`) : null;
        if (!textarea) return;

        let content = textarea.value || '';
        if (window.tinymce && tinymce.get(textarea.id)) {
            content = tinymce.get(textarea.id).getContent();
        }

        const placeholders = extractPlaceholders(content);
        placeholders.forEach(placeholder => {
            variables[placeholder] = existingValues[placeholder] ?? partyPrefill[placeholder] ?? '';
        });
    });

    variablesSection.innerHTML = '';
    const keys = Object.keys(variables);
    if (!keys.length) {
        variablesSection.innerHTML = '<p class="info-panel__hint" style="margin: 0;">No dynamic variables detected in selected modules.</p>';
        return;
    }

    const chipRow = document.createElement('div');
    chipRow.className = 'chip-group';
    keys.forEach(variable => {
        const chip = document.createElement('button');
        chip.type = 'button';
        chip.className = 'variable-chip';
        chip.textContent = `{{${variable}}}`;
        chip.addEventListener('click', () => insertVariable(`{{${variable}}}`));
        chipRow.appendChild(chip);
    });
    variablesSection.appendChild(chipRow);

    const grid = document.createElement('div');
    grid.className = 'form-grid';
    keys.forEach(variable => {
        const label = document.createElement('label');
        label.className = 'form-field';
        label.innerHTML = `
            <span>${variable}</span>
            <input type="text" class="field-input" id="var-${variable}" data-variable-key="${variable}" placeholder="Enter value..." value="${escapeHtml(variables[variable] ?? '')}">
        `;
        grid.appendChild(label);
    });
    variablesSection.appendChild(grid);
}

function escapeHtml(unsafe) {
    return String(unsafe)
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/\"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

function extractPlaceholders(text) {
    const matches = text.match(/\{\{([^}]+)\}\}/g);
    return matches ? matches.map(match => match.slice(2, -2)) : [];
}

function toggleModuleState(checkbox) {
    if (!checkbox) return;
    const card = checkbox.closest('.module-card');
    if (!card) return;

    const targetId = checkbox.getAttribute('data-target');
    const body = targetId ? document.getElementById(targetId) : null;
    const label = card.querySelector('.module-toggle__label');

    if (checkbox.checked) {
        card.classList.remove('module-card--disabled');
        if (body) body.classList.remove('is-disabled');
        if (label) {
            label.textContent = 'Enabled';
            label.classList.remove('is-disabled');
        }
    } else {
        card.classList.add('module-card--disabled');
        if (body) body.classList.add('is-disabled');
        if (label) {
            label.textContent = 'Disabled';
            label.classList.add('is-disabled');
        }
    }

    initializeVariables();
}

// Proposal selector functions (same flow as invoice_create)
function showProposalSelector() {
    const modal = document.getElementById('proposalSelectorModal');
    if (modal) {
        modal.style.display = 'flex';
        const search = document.getElementById('proposalSearch');
        if (search) {
            search.value = '';
            setTimeout(() => search.focus(), 0);
        }
        filterProposals();
    }
}

function closeProposalSelector() {
    const modal = document.getElementById('proposalSelectorModal');
    if (modal) modal.style.display = 'none';
}

function selectProposal(proposalId) {
    const row = document.querySelector(`.proposal-row[data-proposal-id="${proposalId}"]`);
    if (!row) return;

    const title = row.getAttribute('data-proposal-title') || `Proposal #${proposalId}`;

    const displayInput = document.getElementById('proposalDisplay');
    const hiddenInput = document.getElementById('proposalId');

    if (displayInput) displayInput.value = title;
    if (hiddenInput) hiddenInput.value = proposalId;

    closeProposalSelector();
}

function filterProposals() {
    const searchTerm = (document.getElementById('proposalSearch')?.value || '').toLowerCase();
    document.querySelectorAll('.proposal-row').forEach(row => {
        const title = (row.getAttribute('data-proposal-title') || '').toLowerCase();
        row.style.display = title.includes(searchTerm) ? '' : 'none';
    });
}

document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('proposalSearch');
    if (searchInput) {
        searchInput.addEventListener('input', filterProposals);
    }

    const modal = document.getElementById('proposalSelectorModal');
    if (modal) {
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                closeProposalSelector();
            }
        });
    }

    if (typeof window.initializeRichEditors === 'function') {
        window.initializeRichEditors();
    }

    initializeVariables();

    const shareModal = document.getElementById('shareModal');
    if (shareModal) {
        shareModal.addEventListener('click', function(e) {
            if (e.target === shareModal) {
                closeSharePopup();
            }
        });
    }
});

// Form submission
const contractForm = document.getElementById('contract-form');
if (contractForm) contractForm.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const modules = [];
    const moduleCards = document.querySelectorAll('.module-card');
    moduleCards.forEach(card => {
        const moduleId = card.getAttribute('data-module-id');
        const checkbox = card.querySelector('.module-enabled');
        if (!moduleId || !checkbox || !checkbox.checked) return;

        const textarea = document.getElementById(`rich_${moduleId}`);
        let content = '';
        if (textarea) {
            if (window.tinymce && tinymce.get(textarea.id)) {
                content = tinymce.get(textarea.id).getContent();
            } else {
                content = textarea.value;
            }
        }

        modules.push({
            id: parseInt(moduleId, 10),
            name: card.getAttribute('data-module-name') || '',
            type: 'rich',
            content: content,
            price: parseFloat(card.getAttribute('data-module-price') || '0') || 0,
        });
    });
    
    // Collect variables
    const variables = {};
    document.querySelectorAll('#variables-section input[data-variable-key]').forEach(input => {
        const variableName = input.id.replace('var-', '');
        variables[variableName] = input.value;
    });
    
    // Update form data
    document.getElementById('modules-json').value = JSON.stringify(modules);
    document.getElementById('variables-json').value = JSON.stringify(variables);
    document.getElementById('pricing-json').value = JSON.stringify([]);
    
    // Submit form
    this.submit();
});

function showSharePopup() {
    const modal = document.getElementById('shareModal');
    if (modal) modal.style.display = 'flex';
}

function closeSharePopup() {
    const modal = document.getElementById('shareModal');
    if (modal) modal.style.display = 'none';
}

function copyShareLink(event) {
    const shareLink = document.getElementById('shareLink');
    if (!shareLink) return;
    const button = document.getElementById('copyShareBtn') || (event ? event.target : null);

    const onSuccess = () => {
        if (!button) return;
        const originalText = button.textContent;
        button.textContent = 'Copied!';
        setTimeout(() => {
            button.textContent = originalText;
        }, 1600);
    };

    const onError = () => {
        alert('Failed to copy link. Please copy manually.');
    };

    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(shareLink.value).then(onSuccess).catch(onError);
        return;
    }

    try {
        shareLink.select();
        document.execCommand('copy');
        onSuccess();
    } catch (e) {
        onError();
    }
}

// Wire mobile menu button
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>
