import re

with open('app/Views/admin/certificate_add.php', 'r', encoding='utf-8') as f:
    content = f.read()

start_marker = "<!-- Creation Mode Toggle -->"
end_marker = "<!-- Cropper Modal -->"

start_idx = content.find(start_marker)
end_idx = content.find(end_marker)

if start_idx == -1 or end_idx == -1:
    print("Markers not found!")
    exit(1)

new_html = """<!-- Main Form -->
<form action="<?= base_url('admin/certificates/add') ?>" method="POST" enctype="multipart/form-data" id="mainCertForm">
    <?= csrf_field() ?>
    <input type="hidden" name="creation_mode" id="creationModeInput" value="manual">
    <input type="hidden" name="template_id" id="selectedTemplateId" value="">
    <input type="hidden" name="field_adjustments" id="fieldAdjustments" value="{}">

    <!-- ===== GLOBAL NURSE DETAILS & CUSTOM FIELDS ===== -->
    <div class="card mb-lg" style="margin-bottom: var(--space-lg);">
        <div class="card-body">
            <h3 style="margin-bottom: var(--space-lg); color: var(--accent-gold); display: flex; align-items: center; gap: 8px;">
                <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="stroke: var(--accent-gold);"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
                Nurse Details
            </h3>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-lg);">
                <div class="form-group">
                    <label for="name">Full Name</label>
                    <input type="text" id="name" name="name" class="form-control" placeholder="Enter nurse's full name" value="<?= old('name') ?>">
                </div>
                <div class="form-group">
                    <label for="certificate_number">Certificate Number</label>
                    <input type="text" id="certificate_number" name="certificate_number" class="form-control" placeholder="e.g., NRS-2024-001" value="<?= old('certificate_number') ?>">
                </div>
                <div class="form-group">
                    <label for="phone">Phone Number</label>
                    <input type="tel" id="phone" name="phone" class="form-control" placeholder="+91 98765 43210" value="<?= old('phone') ?>">
                </div>
                <div class="form-group">
                    <label for="email">Email Address</label>
                    <input type="email" id="email" name="email" class="form-control" placeholder="nurse@example.com" value="<?= old('email') ?>">
                </div>
            </div>

            <?php if (!empty($customFields)): ?>
                <h3 style="margin: var(--space-xl) 0 var(--space-lg); color: var(--accent-violet); display: flex; align-items: center; gap: 8px;">
                    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="stroke: var(--accent-violet);"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><line x1="9" y1="9" x2="15" y2="9"></line><line x1="9" y1="13" x2="15" y2="13"></line><line x1="9" y1="17" x2="15" y2="17"></line></svg>
                    Additional Details
                </h3>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-lg);">
                    <?php foreach ($customFields as $field): ?>
                        <div class="form-group">
                            <label for="custom_<?= esc($field['field_name']) ?>"><?= esc($field['field_label']) ?></label>
                            <input
                                type="<?= $field['field_type'] === 'number' ? 'number' : ($field['field_type'] === 'date' ? 'date' : 'text') ?>"
                                id="custom_<?= esc($field['field_name']) ?>"
                                name="custom_<?= esc($field['field_name']) ?>"
                                class="form-control"
                                placeholder="Enter <?= esc(strtolower($field['field_label'])) ?>"
                                value="<?= old('custom_' . $field['field_name']) ?>"
                            >
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <h3 style="margin: var(--space-xl) 0 var(--space-lg); color: var(--accent-gold); display: flex; align-items: center; gap: 8px;">
                <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="stroke: var(--accent-gold);"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="16"></line><line x1="8" y1="12" x2="16" y2="12"></line></svg>
                Extra Custom Details
            </h3>

            <div id="dynamicFields" style="display: flex; flex-direction: column; gap: var(--space-md);"></div>

            <button type="button" class="btn btn-secondary btn-sm" onclick="addCustomFieldRow()" style="margin-top: var(--space-md); display: inline-flex; align-items: center; gap: 6px;">
                <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
                Add Custom Detail Field
            </button>
        </div>
    </div>

    <!-- Creation Mode Toggle -->
    <div class="card mb-lg" style="margin-bottom: var(--space-lg);">
        <div class="card-body" style="padding: var(--space-md);">
            <div style="display: flex; align-items: center; gap: var(--space-lg);">
                <span style="font-weight: 600; color: var(--text-secondary); font-size: 0.85rem;">CERTIFICATE MODE:</span>
                <div class="mode-toggle" style="display: flex; background: var(--bg-glass); border-radius: var(--radius-md); padding: 4px; border: 1px solid var(--border-light);">
                    <button type="button" class="mode-btn active" data-mode="manual" onclick="switchCreationMode('manual')" style="padding: 8px 20px; border-radius: var(--radius-sm); border: none; cursor: pointer; font-weight: 600; font-size: 0.85rem; display: flex; align-items: center; gap: 6px; transition: all 0.2s;">
                        <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>
                        Manual Upload
                    </button>
                    <button type="button" class="mode-btn" data-mode="template" onclick="switchCreationMode('template')" style="padding: 8px 20px; border-radius: var(--radius-sm); border: none; cursor: pointer; font-weight: 600; font-size: 0.85rem; display: flex; align-items: center; gap: 6px; transition: all 0.2s;">
                        <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><line x1="3" y1="9" x2="21" y2="9"></line><line x1="9" y1="21" x2="9" y2="9"></line></svg>
                        Use Template
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- ===== MANUAL UPLOAD SECTION ===== -->
    <div id="manualSection">
        <div class="card mb-lg">
            <div class="card-body">
                <h3 style="margin-bottom: var(--space-lg); color: var(--accent-blue); display: flex; align-items: center; gap: 8px;">
                    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="stroke: var(--accent-blue);"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="12" y1="18" x2="12" y2="12"></line><line x1="9" y1="15" x2="15" y2="15"></line></svg>
                    Certificate File
                </h3>

                <div class="form-group">
                    <div class="file-upload" id="fileUploadBox">
                        <input type="file" name="certificate_file" id="certificate_file" accept=".jpg,.jpeg,.png,.pdf">
                        <div class="upload-instructions" id="uploadInstructions">
                            <div class="upload-icon">
                                <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>
                            </div>
                            <div class="upload-text">
                                <strong>Click to upload</strong> or drag and drop<br>
                                <span style="font-size: 0.75rem; color: var(--text-muted);">JPG, PNG, or PDF • Max 10MB</span>
                            </div>
                        </div>
                        <div class="file-upload-preview-container" id="previewContainer">
                            <img src="" alt="Preview" id="previewImg" style="display: none;">
                            <iframe src="" id="previewPdf" style="display: none;" title="PDF Preview"></iframe>
                        </div>
                    </div>
                    <div class="file-upload-preview" id="fileUploadInfo" style="display: none; margin-top: var(--space-md);">
                        <div class="file-info" style="display: flex; align-items: center; justify-content: space-between; width: 100%;">
                            <div>
                                <div class="file-name" style="font-weight: 600; color: var(--text-primary);"></div>
                                <div class="file-size" style="font-size: 0.75rem; color: var(--text-muted);"></div>
                            </div>
                            <span class="btn btn-secondary btn-sm" style="pointer-events: none;">Change File</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ===== TEMPLATE MODE SECTION ===== -->
    <div id="templateSection" style="display: none;">
        <div class="card mb-lg" style="margin-bottom: var(--space-lg);">
            <div class="card-body">
                <h3 style="margin-bottom: var(--space-lg); color: var(--accent-gold); display: flex; align-items: center; gap: 8px;">
                    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" style="stroke: var(--accent-gold);"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><line x1="3" y1="9" x2="21" y2="9"></line><line x1="9" y1="21" x2="9" y2="9"></line></svg>
                    Select Template
                </h3>

                <?php if (empty($templates)): ?>
                    <div class="empty-state" style="padding: var(--space-xl);">
                        <p style="color: var(--text-muted);">No templates available. <a href="<?= base_url('admin/templates/add') ?>" style="color: var(--accent-gold);">Create one first</a>.</p>
                    </div>
                <?php else: ?>
                    <div class="template-select-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: var(--space-md);">
                        <?php foreach ($templates as $tpl): ?>
                            <div class="template-select-card"
                                 data-template-id="<?= $tpl['id'] ?>"
                                 onclick="selectTemplate(<?= $tpl['id'] ?>)"
                                 style="border: 2px solid var(--border-light); border-radius: var(--radius-lg); overflow: hidden; cursor: pointer; transition: all 0.2s; background: var(--bg-glass);">
                                <div style="height: 120px; background: rgba(0,0,0,0.3); display: flex; align-items: center; justify-content: center; overflow: hidden;">
                                    <img src="<?= base_url('admin/templates/image/' . $tpl['id']) ?>" style="max-width: 100%; max-height: 100%; object-fit: contain;" alt="<?= esc($tpl['name']) ?>">
                                </div>
                                <div style="padding: 10px; text-align: center;">
                                    <div style="font-weight: 600; font-size: 0.85rem; color: var(--text-primary);"><?= esc($tpl['name']) ?></div>
                                    <?php $fc = json_decode($tpl['fields_config'] ?? '[]', true) ?: []; ?>
                                    <div style="font-size: 0.7rem; color: var(--text-muted);"><?= count($fc) ?> fields</div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Template-specific fields (dynamically loaded) -->
        <div id="templateFieldsContainer" style="display: none;">
            <div class="card mb-lg" style="margin-bottom: var(--space-lg);">
                <div class="card-body">
                    <h3 style="margin-bottom: var(--space-lg); color: var(--accent-violet); display: flex; align-items: center; gap: 8px;">
                        <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" style="stroke: var(--accent-violet);"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><line x1="9" y1="9" x2="15" y2="9"></line><line x1="9" y1="13" x2="15" y2="13"></line><line x1="9" y1="17" x2="15" y2="17"></line></svg>
                        Template Fields
                    </h3>
                    <div id="templateFieldsForm" style="display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-lg);"></div>
                </div>
            </div>
        </div>

        <!-- Preview -->
        <div id="templatePreviewSection" style="display: none;">
            <div class="card mb-lg" style="margin-bottom: var(--space-lg);">
                <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
                    <h3 style="display: flex; align-items: center; gap: 8px; font-size: 0.95rem;">
                        <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                        Certificate Preview
                    </h3>
                    <span style="font-size: 0.75rem; color: var(--text-muted);">Drag fields to adjust for this certificate only</span>
                </div>
                <div class="card-body">
                    <div id="templatePreviewCanvas" style="position: relative; display: inline-block; border: 2px dashed var(--border-light); border-radius: var(--radius-md); overflow: hidden; max-width: 100%;">
                        <img id="previewBgImage" src="" style="display: block; max-width: 100%; height: auto; user-select: none;" draggable="false">
                        <div id="previewFieldsOverlay" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ===== SUBMIT BUTTON ===== -->
    <div style="display: flex; gap: var(--space-md); margin-top: var(--space-xl); margin-bottom: var(--space-xl);">
        <button type="submit" class="btn btn-primary btn-lg" id="generateCertBtn" style="display: inline-flex; align-items: center; gap: 8px;">
            <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"></polyline></svg>
            Save Certificate
        </button>
        <a href="<?= base_url('admin/certificates') ?>" class="btn btn-secondary btn-lg">Cancel</a>
    </div>
</form>
\n"""

new_content = content[:start_idx] + new_html + content[end_idx:]

with open('app/Views/admin/certificate_add.php', 'w', encoding='utf-8') as f:
    f.write(new_content)
