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

// Require authentication
AuthManager::requireAuth();

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

// Check permission
requirePermission('proposals_create');

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

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

// Additional fallback: try to get user's default workspace
if (!$companyId) {
    try {
        $pdo = getPDO();
        // Get user's first available workspace
        $stmt = $pdo->prepare('SELECT c.id FROM companies c 
            JOIN user_company_access uca ON c.id = uca.company_id 
            WHERE uca.user_id = ? LIMIT 1');
        $stmt->execute([$_SESSION['user_id'] ?? 0]);
        $company = $stmt->fetch();
        $companyId = $company['id'] ?? null;
    } catch (Exception $e) {
        // Ignore errors, will show proper error message below
    }
}

// Set tenant context for Template class
if ($companyId) {
    TenantDB::setTenant($companyId);
} else {
    // No workspace context available - show error
    http_response_code(400);
    echo '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Workspace Required</title>
    <link rel="stylesheet" href="/assets/styles/app.build.css">
</head>
<body class="bg-neutral-950 min-h-screen flex items-center justify-center text-neutral-50">
    <div class="bg-neutral-900/80 border border-neutral-800 rounded-xl p-8 max-w-md w-full mx-4 shadow-xl">
        <div class="text-center">
            <div class="w-16 h-16 bg-amber-500/10 rounded-full flex items-center justify-center mx-auto mb-4 border border-amber-500/30">
                <svg class="w-8 h-8 text-amber-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"></path>
                </svg>
            </div>
            <h1 class="text-lg font-semibold text-neutral-50 mb-1">Workspace Required</h1>
            <p class="text-sm text-neutral-400 mb-5">Please access this page from within a workspace context.</p>
            <div class="space-y-2">
                <a href="/index.php" class="block w-full px-4 py-2 rounded-lg bg-neutral-50 text-neutral-900 text-sm font-medium hover:bg-neutral-200 transition-colors duration-200">
                    Go to Dashboard
                </a>
                <a href="/proposals.php" class="block w-full px-4 py-2 rounded-lg border border-neutral-700 text-neutral-300 text-sm font-medium hover:bg-neutral-900 transition-colors duration-200">
                    View Proposals
                </a>
            </div>
        </div>
    </div>
</body>
</html>';
    exit;
}
require_once __DIR__ . '/../src/Client.php';
require_once __DIR__ . '/../src/Template.php';
require_once __DIR__ . '/../src/Module.php';
require_once __DIR__ . '/../src/TemplateModule.php';
require_once __DIR__ . '/../src/Proposal.php';
require_once __DIR__ . '/../src/db.php';

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

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

// Load existing proposal data if editing
if ($editMode) {
    $existingProposal = Proposal::find($proposalId);
    if (!$existingProposal) {
        $errors[] = 'Proposal not found.';
        $editMode = false;
    } else {
        $clientId = $existingProposal['client_id'];
        $templateId = $existingProposal['template_id'];
        // Only force step 3 if we're not already on step 4
        if ($step !== 4) {
            $step = 3; // Skip to step 3 for editing
        }
        $proposalData = [
            'modules' => $existingProposal['modules_json'] ?? [],
            'variables' => $existingProposal['variables_json'] ?? [],
            'pricing' => $existingProposal['pricing_json'] ?? [],
            'currency' => $existingProposal['currency'] ?? 'USD',
        ];
    }
}

$client = $clientId > 0 ? Client::find($clientId) : null;
$template = $templateId > 0 ? Template::find($templateId) : null;
$attachedModules = $template ? TemplateModule::forTemplate($templateId) : [];

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

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

    if ($action === 'set_client') {
        $clientId = (int) ($_POST['client_id'] ?? 0);
        $client = Client::find($clientId);
        if (!$client) {
            $errors[] = 'Select a valid client.';
        } else {
            $redirectParams = ['step' => 3, 'client_id' => $clientId, 'template_id' => $templateId];
            if (isset($_GET['workspace'])) {
                $redirectParams['workspace'] = $_GET['workspace'];
            }
            redirect('/generate.php', $redirectParams);
        }
    }

    if ($action === 'set_template') {
        $templateId = (int) ($_POST['template_id'] ?? 0);
        $template = Template::find($templateId);
        if (!$template) {
            $errors[] = 'Select a valid template.';
        } else {
            $redirectParams = ['step' => 2, 'client_id' => $clientId, 'template_id' => $templateId];
            if (isset($_GET['workspace'])) {
                $redirectParams['workspace'] = $_GET['workspace'];
            }
            redirect('/generate.php', $redirectParams);
        }
    }

    if ($action === 'configure_modules') {
        $moduleIds = array_map('intval', $_POST['module_ids'] ?? []);
        $enabled = array_map('boolval', $_POST['module_enabled'] ?? []);
        $contents = $_POST['module_content'] ?? [];

        $proposalData['modules'] = [];
        foreach ($moduleIds as $i => $moduleId) {
            // Keep the full content including base64 images
            $content = $contents[$moduleId] ?? '';
            
            $proposalData['modules'][] = [
                'module_id' => $moduleId,
                'enabled' => $enabled[$i] ?? false,
                'content_html' => $content,
                'sort_order' => $i + 1,
            ];
        }

        $proposalData['variables'] = $_POST['variables'] ?? [];
        $proposalData['currency'] = sanitizeCurrency($_POST['currency'] ?? 'USD');
        $proposalData['labels'] = array_filter(array_map('trim', explode(',', $_POST['labels'] ?? '')));
        $proposalData['title'] = 'Proposal for ' . ($client['name'] ?? 'Client');
        $proposalData['status'] = 'draft';

        if ($editMode) {
            // Update existing proposal
            $oldProposal = $existingProposal ?? Proposal::find($proposalId);
            Proposal::update($proposalId, [
                'modules_json' => $proposalData['modules'] ?? [],
                'variables_json' => $proposalData['variables'] ?? [],
                'pricing_json' => [],
                'currency' => $proposalData['currency'] ?? 'USD',
                'title' => $proposalData['title'],
                'status' => $proposalData['status'],
            ]);
            
            // Delete existing labels and recreate them
            $pdo = getPDO();
            $pdo->prepare("DELETE FROM proposal_labels WHERE proposal_id = ?")->execute([$proposalId]);
        } else {
            // Create new proposal
            $proposalId = Proposal::create([
                'client_id' => $clientId,
                'template_id' => $templateId,
                'modules_json' => $proposalData['modules'] ?? [],
                'variables_json' => $proposalData['variables'] ?? [],
                'pricing_json' => [],
                'currency' => $proposalData['currency'] ?? 'USD',
                'title' => $proposalData['title'],
                'status' => $proposalData['status'],
            ]);
        }

        // Save labels
        if (!empty($proposalData['labels'])) {
            $pdo = getPDO();
            foreach ($proposalData['labels'] as $label) {
                $stmt = $pdo->prepare(
                    "INSERT INTO proposal_labels (proposal_id, label) VALUES (?, ?)"
                );
                $stmt->execute([$proposalId, $label]);
            }
        }

        // Log proposal create/update in workspace activity (best-effort)
        try {
            if ($companyId) {
                $currentUser = AuthManager::getCurrentUser();
                $userId = $currentUser['id'] ?? null;
                $actionType = $editMode ? 'proposal_updated' : 'proposal_created';
                $oldValues = $editMode ? ($oldProposal ?? null) : null;
                $newValues = [
                    'client_id' => $clientId,
                    'template_id' => $templateId,
                    'currency' => $proposalData['currency'] ?? 'USD',
                    'status' => $proposalData['status'] ?? 'draft',
                    'labels' => $proposalData['labels'] ?? [],
                ];
                ActivityLog::log(
                    (int) $companyId,
                    $userId ? (int) $userId : null,
                    $actionType,
                    'proposal',
                    (int) $proposalId,
                    $proposalData['title'] ?? null,
                    $oldValues,
                    $newValues
                );
            }
        } catch (Throwable $e) {
            // ignore logging failures
        }

        $redirectParams = [
            'step' => 4,
            'client_id' => $clientId,
            'template_id' => $templateId,
            'proposal_id' => $proposalId,
            'data' => base64_encode(json_encode($proposalData)),
            'edit' => $editMode ? '1' : '0',
        ];
        if (isset($_GET['workspace'])) {
            $redirectParams['workspace'] = $_GET['workspace'];
        }
        redirect('/generate.php', $redirectParams);
    }
}

if (isset($_GET['data'])) {
    $decoded = json_decode(base64_decode($_GET['data'] ?? ''), true);
    if (is_array($decoded)) {
        $proposalData = array_merge($proposalData, $decoded);
    }
}

$clients = Client::all();
$templates = Template::all();

// Get existing labels for quick add
$existingLabels = [];
try {
    $pdo = getPDO();
    $existingLabels = $pdo->query("SELECT label FROM labels ORDER BY label")->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
    // Table doesn't exist yet
    $existingLabels = [];
}

$allHtmlBlocks = [];
if ($template) {
    $allHtmlBlocks[] = $template['header_html'] ?? '';
    $allHtmlBlocks[] = $template['footer_html'] ?? '';
    foreach ($attachedModules as $m) {
        $allHtmlBlocks[] = $m['content_html'] ?? '';
    }
}
$placeholders = extractPlaceholders($allHtmlBlocks);
$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 Proposal' : 'Create Proposal' ?> · 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 = tinymce.activeEditor;
            if (activeEditor) {
                activeEditor.insertContent(variable);
            }
        }
    </script>
    </head>
<body>
<?php require_once __DIR__ . '/navigation.php'; renderNavigationNew('Proposals', $currentTheme); ?>

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

    $actions = [
        [
            'label' => 'All proposals',
            'url' => '/proposals.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' => 'Proposals', 'url' => '/proposals.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 proposal' : 'Create proposal',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

    <div class="dash-container proposal-wizard">
    <!-- Wizard Header -->
    <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">Proposal builder</p>
                        <h2 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 4px 0;">
                            <?= $editMode ? 'Edit proposal' : 'Create proposal' ?>
                        </h2>
                        <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Generate a new proposal in 4 compact steps.</p>
                    </div>
                </div>
            </div>
        </section>
    </div>

    <!-- Progress Steps -->
    <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 proposal 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 proposal</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">
                <svg style="width: 14px; height: 14px;" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                </svg>
                <span><?= h($successMessage) ?></span>
            </div>
        </div>
    <?php endif; ?>

    <?php if ($errors): ?>
        <div class="dash-section">
            <div class="status-banner error">
                <svg style="width: 14px; height: 14px;" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9 7a1 1 0 112 0v4a1 1 0 11-2 0V7zm1 6a1.25 1.25 0 100 2.5A1.25 1.25 0 0010 13z" clip-rule="evenodd"></path>
                </svg>
                <ul class="status-list">
                    <?php foreach ($errors as $error): ?>
                        <li><?= h($error) ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
    <?php endif; ?>

    <?php if ($step === 1): ?>
        <div class="dash-section">
        <section class="card">
            <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 proposal.</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 scope, pricing, and next steps.') ?></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(getTemplateModules($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 templates yet</h3>
                            <p class="empty-desc" style="max-width: 360px; margin: 0 auto 16px;">Create your first template to start generating professional proposals.</p>
                            <a href="/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 endif; ?>

    <?php if ($step === 2): ?>
        <div class="dash-section">
        <section class="card">
            <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 proposal</p>
            </div>
            <div class="p-4 md:p-6">
                <!-- Search Bar -->
                <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>

                <!-- Client Grid -->
                <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);" 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; ?>
                    <?php if (!$clients): ?>
                        <div class="col-span-full text-center py-10 bg-neutral-900 rounded-xl border-2 border-dashed border-neutral-800">
                            <div class="w-16 h-16 bg-neutral-900 rounded-xl flex items-center justify-center mx-auto mb-4 border border-neutral-800">
                                <svg class="w-8 h-8 text-neutral-400" 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>
                            <h3 class="text-sm font-semibold text-neutral-50 mb-1">No clients yet</h3>
                            <p class="text-xs text-neutral-400 mb-4 max-w-md mx-auto">Add your first client to start creating proposals</p>
                            <a href="/clients.php<?= isset($_GET['workspace']) ? '?workspace=' . urlencode($_GET['workspace']) : '' ?>" class="inline-flex items-center px-5 py-2.5 rounded-lg bg-neutral-50 text-neutral-900 text-sm font-medium hover:bg-neutral-200 transition-colors duration-200">
                                <svg class="w-5 h-5 mr-2" 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>
                                Add Client
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="mt-6 border-t border-neutral-800 pt-4 flex items-center justify-between gap-3">
                    <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>
                    <span style="font-size: 11px; color: var(--text-tertiary);" class="hidden sm:inline">Choose a client to continue</span>
                </div>
            </div>
        </section>
        
        <script>
        const clients = <?= json_encode($clients) ?>;
        const clientSearch = document.getElementById('clientSearch');
        const clientList = document.getElementById('clientList');
        const searchHint = document.getElementById('searchHint');
        const searchCount = document.getElementById('searchCount');
        
        if (clientSearch && clientList) {
            clientSearch.addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase().trim();
                const clientItems = clientList.querySelectorAll('.client-item');
                let visibleCount = 0;
                
                clientItems.forEach(item => {
                    const name = item.dataset.clientName || '';
                    const company = item.dataset.clientCompany || '';
                    const email = item.dataset.clientEmail || '';
                    const matches = name.includes(searchTerm) || company.includes(searchTerm) || email.includes(searchTerm);
                    
                    item.style.display = matches ? 'block' : 'none';
                    if (matches) visibleCount++;
                });
                
                // Update search hints
                if (searchTerm) {
                    searchHint.classList.add('hidden');
                    searchCount.classList.remove('hidden');
                    searchCount.textContent = `${visibleCount} ${visibleCount === 1 ? 'client' : 'clients'} found`;
                } else {
                    searchHint.classList.remove('hidden');
                    searchCount.classList.add('hidden');
                }
            });
            
            // Clear search on escape key
            clientSearch.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    this.value = '';
                    this.dispatchEvent(new Event('input'));
                }
            });
        }
        
        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}">
                <?php if (isset($_GET['workspace'])): ?>
                    <input type="hidden" name="workspace" value="<?= h($_GET['workspace']) ?>">
                <?php endif; ?>
            `;
            document.body.appendChild(form);
            form.submit();
        }
        </script>
    <?php endif; ?>

    <?php if ($step === 3 && $template && $client): ?>
        <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 add proposal labels.</p>
                    </div>
                </div>
                <span class="step-tag">Step 3 of 4</span>
            </div>
            <div class="p-4 md:p-6">
                <form method="POST" id="step3Form" onsubmit="updateLabelsInput()">
                    <input type="hidden" name="action" value="configure_modules">
                    <?php if (isset($_GET['workspace'])): ?>
                        <input type="hidden" name="workspace" value="<?= h($_GET['workspace']) ?>">
                    <?php endif; ?>

                    <?php 
                    $variableTokens = [
                        ['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}}'],
                    ];
                    ?>

                    <div class="module-stack">
                        <?php foreach ($attachedModules as $index => $m): ?>
                            <?php 
                            $existingModule = null;
                            if ($editMode) {
                                foreach ($proposalData['modules'] as $existingMod) {
                                    if ($existingMod['module_id'] == $m['id']) {
                                        $existingModule = $existingMod;
                                        break;
                                    }
                                }
                            }
                            $isEnabled = $existingModule ? ($existingModule['enabled'] ?? true) : true;
                            $content = $existingModule ? ($existingModule['content_html'] ?? $m['content_html']) : $m['content_html'];
                            ?>
                            <div class="module-card<?= $isEnabled ? '' : ' module-card--disabled' ?>">
                                <div class="module-card__head">
                                    <div>
                                        <p class="eyebrow">Module <?= $index + 1 ?></p>
                                        <h3><?= h($m['title']) ?></h3>
                                    </div>
                                    <label class="module-toggle">
                                        <input
                                            type="checkbox"
                                            name="module_enabled[]"
                                            value="1"
                                            <?= $isEnabled ? 'checked' : '' ?>
                                            onchange="toggleModuleState(this)"
                                            data-target="module-<?= (int) $m['id'] ?>"
                                        >
                                        <span class="module-toggle__control"></span>
                                        <span class="module-toggle__label<?= $isEnabled ? '' : ' is-disabled' ?>"><?= $isEnabled ? 'Enabled' : 'Disabled' ?></span>
                                    </label>
                                </div>
                                <input type="hidden" name="module_ids[]" value="<?= (int) $m['id'] ?>">
                                <div class="module-card__body<?= $isEnabled ? '' : ' is-disabled' ?>" id="module-<?= (int) $m['id'] ?>">
                                    <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
                                        name="module_content[<?= (int) $m['id'] ?>]"
                                        id="rich_<?= (int) $m['id'] ?>"
                                        class="editor-area rich"
                                        rows="12"
                                        placeholder="Describe the scope, deliverables, and value for this section."
                                    ><?= h($content) ?></textarea>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <?php if ($placeholders): ?>
                        <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="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 that appear inside this template.</p>
                                </div>
                            </div>
                            <div class="form-grid">
                                <?php foreach ($placeholders as $key): ?>
                                    <label class="form-field">
                                        <span><?= h($key) ?></span>
                                        <input
                                            type="text"
                                            name="variables[<?= h($key) ?>]"
                                            value="<?= h($proposalData['variables'][$key] ?? '') ?>"
                                            class="field-input"
                                            placeholder="Enter value..."
                                        >
                                    </label>
                                <?php endforeach; ?>
                            </div>
                            <p class="info-panel__hint">Suggestions from client profile: <?= h(implode(', ', array_keys(clientVariableSuggestions($client)))) ?></p>
                        </div>
                    <?php endif; ?>

                    <!-- Labels Section -->
                    <div class="label-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="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>
                            </div>
                            <div>
                                <p class="info-panel__title">Proposal labels</p>
                                <p class="info-panel__subtitle">Tag the proposal for faster filtering in your pipeline.</p>
                            </div>
                        </div>
                        <div class="label-panel__composer">
                            <input type="text" id="labelInput" class="label-input" placeholder="Type a label and press Enter">
                            <button type="button" class="btn-secondary" style="font-size: 12px;" onclick="addLabel()">
                                <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>
                                Add
                            </button>
                        </div>
                        <div class="label-panel__quick">
                            <p>Quick add</p>
                            <div class="chip-group">
                                <?php 
                                $predefinedLabels = ['AMC', 'Web Design', 'Marketing', 'Graphic Design', 'Development', 'Consulting', 'SEO', 'Mobile App'];
                                $allQuickLabels = array_unique(array_merge($predefinedLabels, $existingLabels ?? []));
                                sort($allQuickLabels);
                                ?>
                                <?php foreach ($allQuickLabels as $label): ?>
                                    <button type="button" class="label-chip" onclick="quickAddLabel('<?= h($label) ?>')">
                                        <?= h($label) ?>
                                    </button>
                                <?php endforeach; ?>
                                <?php if (empty($allQuickLabels)): ?>
                                    <span class="info-panel__hint">No labels available yet. Create a proposal to seed recent labels.</span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="labels-selected" id="selectedLabels">
                            <!-- Labels populated via JS -->
                        </div>
                        <input type="hidden" name="labels" id="labelsInput" value="">
                    </div>
                    
                    <?php if ($editMode): ?>
                        <script>
                            <?php 
                            $pdo = getPDO();
                            $labelsStmt = $pdo->prepare("SELECT label FROM proposal_labels WHERE proposal_id = ?");
                            $labelsStmt->execute([$proposalId]);
                            $existingLabels = $labelsStmt->fetchAll(PDO::FETCH_COLUMN);
                            ?>
                            window.initialProposalLabels = <?= json_encode($existingLabels) ?>;
                        </script>
                    <?php endif; ?>

                    <div class="mt-6 border-top flex items-center justify-between gap-3" style="padding-top: 12px; border-top: 1px solid var(--border-subtle);">
                        <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 class="flex items-center gap-2">
                            <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>Generate proposal</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>
    <?php endif; ?>

    <?php if ($step === 4 && isset($_GET['proposal_id'])):
        $proposal = Proposal::find((int) ($_GET['proposal_id'] ?? 0));
        $isEdit = ($_GET['edit'] ?? '0') === '1';
        
        // Auto-generate PDF if it doesn't exist OR if we're editing (force regeneration)
        if ($proposal && (!$proposal['pdf_path'] || !file_exists(__DIR__ . '/..' . $proposal['pdf_path']) || $isEdit)) {
            try {
                $pdfPath = Proposal::generatePdf((int) $_GET['proposal_id']);
                // Reload proposal to get updated PDF path
                $proposal = Proposal::find((int) $_GET['proposal_id']);
            } catch (Exception $e) {
                // If PDF generation fails, continue without it
            }
        }
        
        // Generate view link with timestamp for cache busting
        $timestamp = time();
        $viewLink = "/download.php?action=view&proposal_id=" . (int) ($_GET['proposal_id'] ?? 0) . "&t={$timestamp}&force=1" . (isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '');
        ?>
        <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"><?= $isEdit ? 'Proposal updated' : 'Proposal ready' ?></p>
                    <p class="wizard-complete-card__subtitle">
                        <?= $isEdit ? 'Your proposal is refreshed with the latest modules.' : '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>Proposal ID: <?= h($proposal['proposal_number'] ?? 'PRO-' . ($_GET['proposal_id'] ?? 0)) ?></span>
                </div>
            </div>

            <div class="wizard-complete-card__actions">
                <?php if ($proposal && $proposal['pdf_path']): ?>
                    <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>
                <?php else: ?>
                    <span class="proposal-download-card proposal-download-card--pending" style="justify-content:center;">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" class="animate-spin" style="width: 16px; height: 16px;">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                        </svg>
                        <span style="font-size: 12px;">Generating PDF...</span>
                    </span>
                <?php endif; ?>

                <a href="/generate.php?proposal_id=<?= (int) ($_GET['proposal_id'] ?? 0) ?>&action=edit<?= isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '' ?>" 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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                    </svg>
                    Edit proposal
                </a>
                <a href="/proposals.php?success=updated<?= isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '' ?>" class="btn-secondary">
                    All proposals
                </a>
            </div>

            <div class="wizard-complete-card__downloads">
                <?php if ($proposal && $proposal['pdf_path']): ?>
                    <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 Proposal PDF</p>
                                <p class="proposal-download-card__subtitle">Get the latest version with current content</p>
                            </div>
                        </div>
                        <a href="<?= $viewLink ?>" target="_blank" class="proposal-download-card__action is-primary">
                            <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>
                            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">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                <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>
                            Preview
                        </a>
                    </div>
                <?php else: ?>
                    <div class="proposal-download-card proposal-download-card--pending">
                        <div class="proposal-download-card__content">
                            <svg class="animate-spin" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                            </svg>
                            <div>
                                <p class="proposal-download-card__title">Generating PDF...</p>
                                <p class="proposal-download-card__subtitle">Please wait while we prepare your document</p>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <?php if ($proposal): ?>
                <div class="proposal-details-card">
                    <h3>Proposal details</h3>
                    <div class="proposal-details-grid">
                        <div>
                            <p class="proposal-details-label">Proposal title</p>
                            <p class="proposal-details-value"><?= h($proposal['title']) ?></p>
                        </div>
                        <div>
                            <p class="proposal-details-label">Status</p>
                            <p class="proposal-details-value"><?= h($proposal['status']) ?></p>
                        </div>
                        <div>
                            <p class="proposal-details-label">Created</p>
                            <p class="proposal-details-value"><?= date('M j, Y', strtotime($proposal['created_at'])) ?></p>
                        </div>
                        <div>
                            <p class="proposal-details-label">Last updated</p>
                            <p class="proposal-details-value">
                                <?= !empty($proposal['updated_at']) ? date('M j, Y', strtotime($proposal['updated_at'])) : date('M j, Y', strtotime($proposal['created_at'])) ?>
                            </p>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </section>
        </div>
    <?php endif; ?>
    </div>
</div>

<!-- Labels & module management -->
<script>
let selectedLabels = Array.isArray(window.initialProposalLabels) ? [...window.initialProposalLabels] : [];

function addLabel() {
    const input = document.getElementById('labelInput');
    if (!input) return;
    const label = input.value.trim();
    if (label && !selectedLabels.includes(label)) {
        selectedLabels.push(label);
        input.value = '';
        input.focus();
        renderSelectedLabels();
    }
}

function quickAddLabel(label) {
    if (!selectedLabels.includes(label)) {
        selectedLabels.push(label);
        renderSelectedLabels();
    }
}

function removeLabel(label) {
    selectedLabels = selectedLabels.filter(l => l !== label);
    renderSelectedLabels();
}

function escapeHtml(value) {
    return value
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
}

function renderSelectedLabels() {
    const container = document.getElementById('selectedLabels');
    const hiddenInput = document.getElementById('labelsInput');
    if (!container || !hiddenInput) return;

    if (selectedLabels.length === 0) {
        container.innerHTML = '<span class="info-panel__hint">No labels yet. Add one to keep proposals organized.</span>';
    } else {
        container.innerHTML = selectedLabels.map(label => {
            const safe = escapeHtml(label);
            return `
                <span class="label-pill">
                    ${safe}
                    <button type="button" data-label="${safe}" onclick="removeLabel(this.dataset.label)">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    </button>
                </span>
            `;
        }).join('');
    }

    hiddenInput.value = selectedLabels.join(',');
}

function toggleModuleState(input) {
    const card = input.closest('.module-card');
    const label = input.parentElement?.querySelector('.module-toggle__label');
    const targetBody = document.getElementById(input.dataset.target || '');
    const isEnabled = input.checked;

    if (card) card.classList.toggle('module-card--disabled', !isEnabled);
    if (label) {
        label.textContent = isEnabled ? 'Enabled' : 'Disabled';
        label.classList.toggle('is-disabled', !isEnabled);
    }
    if (targetBody) targetBody.classList.toggle('is-disabled', !isEnabled);
}

document.addEventListener('DOMContentLoaded', function() {
    const labelInput = document.getElementById('labelInput');
    if (labelInput) {
        labelInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                addLabel();
            }
        });
    }

    renderSelectedLabels();
});
</script>
</body>
</html>

