<?php

declare(strict_types=1);

$form = $form ?? [];
$sections = $sections ?? [];
$fields = $fields ?? [];
$fieldOptions =
    $fieldOptions
    ?? [];
ob_start();

$formId = (int) ($form['id'] ?? 0);
$formStatus = (string) ($form['status'] ?? 'draft');

$fieldsBySection = [];
foreach ($fields as $field) {
    $sectionId = (int) ($field['section_id'] ?? 0);
    $fieldsBySection[$sectionId][] = $field;
}
?>

<style>
.form-designer-page{--designer-border:#e5eaf0;--designer-muted:#718096;--designer-bg:#f5f7fa}
.designer-topbar,.designer-panel,.canvas-form-header,.canvas-section{background:#fff;border:1px solid var(--designer-border);border-radius:16px}
.designer-topbar{padding:18px 20px;margin-bottom:20px}
.designer-code{display:inline-flex;padding:5px 9px;border-radius:7px;background:#f1f5f9;font-family:monospace;font-size:12px;font-weight:700}
.designer-status{display:inline-flex;padding:5px 10px;border-radius:999px;font-size:12px;font-weight:600}
.designer-status-draft{background:rgba(255,193,7,.16);color:#8a6700}.designer-status-published{background:rgba(25,135,84,.12);color:#198754}.designer-status-archived{background:#edf1f5;color:#667085}
.designer-panel{overflow:hidden}.designer-panel-header{padding:16px 18px;border-bottom:1px solid var(--designer-border)}.designer-panel-title{font-size:14px;font-weight:700;margin:0}.designer-panel-subtitle{font-size:12px;color:var(--designer-muted);margin-top:3px}
.toolbox-body{padding:14px}.toolbox-group-title{font-size:10px;font-weight:700;letter-spacing:.7px;color:#8a96a6;text-transform:uppercase;margin:8px 4px 10px}
.toolbox-item{width:100%;min-height:44px;display:flex;align-items:center;gap:10px;padding:10px 12px;margin-bottom:8px;border:1px solid #e5eaf0;border-radius:10px;background:#fff;color:#344054;font-size:13px;text-align:left;cursor:pointer}
.toolbox-item:hover{border-color:#b8c8df;box-shadow:0 6px 18px rgba(20,35,60,.06)}
.toolbox-item i{width:26px;height:26px;display:inline-flex;align-items:center;justify-content:center;border-radius:7px;background:rgba(13,110,253,.08);color:var(--bs-primary)}
.canvas-shell{background:var(--designer-bg);min-height:680px;padding:22px}.form-canvas{max-width:850px;margin:0 auto}.canvas-form-header{padding:22px;margin-bottom:16px}.canvas-section{margin-bottom:16px;overflow:hidden}
.canvas-section-header{padding:16px 18px;border-bottom:1px solid #edf1f5;display:flex;justify-content:space-between;align-items:flex-start;gap:15px}
.section-order{width:30px;height:30px;flex:0 0 30px;display:inline-flex;align-items:center;justify-content:center;border-radius:8px;background:#f1f5f9;font-size:12px;font-weight:700}
.section-title{font-size:15px;font-weight:700;color:#1f2937}.section-description{font-size:12px;color:var(--designer-muted);margin-top:3px}.section-empty{

    padding:28px 18px;

    text-align:center;

    color:#98a2b3;

    font-size:13px;

    border:2px dashed #d8e0e9;

    border-radius:10px;

    background:#fafbfd;

}

.empty-drop-zone{

    min-height:90px;

}
.empty-canvas{background:#fff;border:2px dashed #d8e0e9;border-radius:14px;padding:55px 25px;text-align:center}.empty-canvas-icon{width:64px;height:64px;margin:0 auto 14px;border-radius:18px;display:flex;align-items:center;justify-content:center;background:rgba(13,110,253,.08);color:var(--bs-primary);font-size:28px}
.properties-empty{padding:35px 20px;text-align:center;color:#98a2b3}.properties-empty i{display:block;font-size:30px;margin-bottom:10px}.designer-column-sticky{position:sticky;top:20px}
.section-action-group{display:inline-flex;gap:6px}.section-action-group .btn{width:32px;height:32px;padding:0;display:inline-flex;align-items:center;justify-content:center;border-radius:8px}
.section-fields{
    padding:18px;
}

.sortable-fields{

    display:grid;

    grid-template-columns:repeat(12,minmax(0,1fr));

    gap:16px;

}

.sortable-field[data-width="12"]{grid-column:span 12;}
.sortable-field[data-width="9"]{grid-column:span 9;}
.sortable-field[data-width="8"]{grid-column:span 8;}
.sortable-field[data-width="6"]{
    grid-column: span 6;
}
.sortable-field[data-width="4"]{grid-column:span 4;}
.sortable-field[data-width="3"]{grid-column:span 3;}

@media(max-width:992px){

    .sortable-field{
        grid-column:span 12 !important;
    }

}
.designer-field-card{height:100%;padding:16px;border:1px solid #e5eaf0;border-radius:12px;background:#fff}.designer-field-card:hover{border-color:#b9c9df;box-shadow:0 6px 20px rgba(20,35,60,.06)}
.sortable-ghost{
    opacity:.45;
}

.sortable-chosen{
    cursor:grabbing;
}

.field-card-toolbar{
    cursor:grab;
}

.canvas-section-header{
    cursor:grab;
}
.field-card-toolbar{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px}.field-type-badge{padding:4px 7px;border-radius:6px;background:#f1f5f9;color:#64748b;font-size:9px;font-weight:700;letter-spacing:.5px}.field-preview-label{font-size:13px;font-weight:600;color:#344054}
.modal-content{border:0;border-radius:16px}.modal-header,.modal-footer{border-color:#edf1f5}
@media(max-width:1199.98px){.designer-column-sticky{position:static}}
</style>

<div class="container-fluid py-4 form-designer-page">
<div class="designer-topbar"><div class="row align-items-center g-3">
<div class="col-lg-8"><div class="d-flex align-items-center gap-3">
<a href="/public/dynamic-forms" class="btn btn-light"><i class="bi bi-arrow-left"></i></a>
<div><div class="d-flex align-items-center gap-2 mb-1">
<span class="designer-code"><?= htmlspecialchars((string)($form['form_code']??''),ENT_QUOTES,'UTF-8') ?></span>
<span class="designer-status designer-status-<?= htmlspecialchars($formStatus,ENT_QUOTES,'UTF-8') ?>"><?= htmlspecialchars(ucfirst($formStatus),ENT_QUOTES,'UTF-8') ?></span>
</div><h3 class="mb-1"><?= htmlspecialchars((string)($form['form_name']??'Form Designer'),ENT_QUOTES,'UTF-8') ?></h3>
<div class="text-muted small">Build sections and fields for this form.</div></div></div></div>
<div class="col-lg-4 text-lg-end">

    <div class="d-flex justify-content-lg-end gap-2">

        <a
            href="/public/dynamic-forms/preview?id=<?= (int) $form['id'] ?>"
            class="btn btn-outline-secondary"
            target="_blank">

            <i class="bi bi-eye me-1"></i>
            Preview

        </a>

        <button
            type="button"
            class="btn btn-primary"
            data-bs-toggle="modal"
            data-bs-target="#addSectionModal">

            <i class="bi bi-plus-lg me-1"></i>
            Add Section

        </button>

    </div>

</div>
</div></div>

<?php foreach ([['sectionCreated','Section created successfully.'],['sectionUpdated','Section updated successfully.'],['fieldCreated','Field created successfully.'],['fieldUpdated','Field updated successfully.']] as [$flag,$message]): ?>
<?php if (!empty($$flag)): ?><div class="alert alert-success alert-dismissible fade show"><?= $message ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
<?php endforeach; ?>
<?php if (!empty($error)): ?><div class="alert alert-danger alert-dismissible fade show"><?= htmlspecialchars((string)$error,ENT_QUOTES,'UTF-8') ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

<div class="row g-4">
<div class="col-xl-2 col-lg-3"><div class="designer-column-sticky"><div class="designer-panel">
<div class="designer-panel-header"><h6 class="designer-panel-title">Field Toolbox</h6><div class="designer-panel-subtitle">Click a field type to add it.</div></div>
<div class="toolbox-body">
<?php
$groups=[
'Basic Fields'=>[['text','Text','bi-input-cursor-text'],['textarea','Textarea','bi-textarea-t'],['number','Number','bi-123'],['date','Date','bi-calendar3'],['time','Time','bi-clock']],
'Choice Fields'=>[['select','Select','bi-menu-button-wide'],['radio','Radio','bi-record-circle'],['checkbox','Checkbox','bi-check2-square']],
'Advanced'=>[['email','Email','bi-envelope'],['phone','Phone','bi-telephone'],['file','File Upload','bi-paperclip']]
];
foreach($groups as $group=>$items): ?>
<div class="toolbox-group-title <?= $group!=='Basic Fields'?'mt-4':'' ?>"><?= $group ?></div>
<?php foreach($items as [$type,$label,$icon]): ?>
<button type="button" class="toolbox-item add-field-btn" data-field-type="<?= $type ?>" data-field-type-label="<?= $label ?>"><i class="bi <?= $icon ?>"></i><?= $label ?></button>
<?php endforeach; endforeach; ?>
</div></div></div></div>

<div class="col-xl-7 col-lg-9"><div class="designer-panel">
<div class="designer-panel-header"><h6 class="designer-panel-title">Form Canvas</h6><div class="designer-panel-subtitle">Form sections and fields appear here in display order.</div></div>
<div class="canvas-shell"><div class="form-canvas">
<div class="canvas-form-header"><h4 class="mb-2"><?= htmlspecialchars((string)($form['form_name']??''),ENT_QUOTES,'UTF-8') ?></h4>
<?php if(!empty($form['description'])): ?><div class="text-muted"><?= htmlspecialchars((string)$form['description'],ENT_QUOTES,'UTF-8') ?></div><?php endif; ?></div>

<?php if(empty($sections)): ?>
<div class="empty-canvas"><div class="empty-canvas-icon"><i class="bi bi-layout-text-window-reverse"></i></div><h5>Start with a section</h5><p class="text-muted">Sections organize related fields inside your dynamic form.</p>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addSectionModal"><i class="bi bi-plus-lg me-1"></i>Add First Section</button></div>
<?php else: ?>

<div id="sortableSections">

<?php foreach($sections as $index=>$section): ?><?php $sid=(int)($section['id']??0); $sectionFields=$fieldsBySection[$sid]??[]; ?>
<div
    class="canvas-section"
    data-section-id="<?= (int) $section['id'] ?>">

<div class="canvas-section-header"><div class="d-flex gap-3"><div class="section-order"><?= $index+1 ?></div><div>
<div class="section-title"><?= htmlspecialchars((string)($section['section_title']??''),ENT_QUOTES,'UTF-8') ?></div>
<?php if(!empty($section['section_description'])): ?><div class="section-description"><?= htmlspecialchars((string)$section['section_description'],ENT_QUOTES,'UTF-8') ?></div><?php endif; ?>
</div></div>
<div class="section-action-group"><button type="button" class="btn btn-outline-warning edit-section-btn" data-bs-toggle="modal" data-bs-target="#editSectionModal"
data-id="<?= (int)$section['id'] ?>" data-title="<?= htmlspecialchars((string)($section['section_title']??''),ENT_QUOTES,'UTF-8') ?>" data-description="<?= htmlspecialchars((string)($section['section_description']??''),ENT_QUOTES,'UTF-8') ?>"><i class="bi bi-pencil"></i></button></div></div>


<div class="section-fields">

    <div
        class="row g-3 sortable-fields"
        data-section-id="<?= (int) $section['id'] ?>">

<?php if (empty($sectionFields)): ?>

<div class="col-12 empty-drop-zone">

    <div class="section-empty">

        <i class="bi bi-plus-circle me-1"></i>

        Drop fields here or click the toolbox to add one.

    </div>

</div>

<?php else: ?>

<?php foreach($sectionFields as $field):

$type = (string) ($field['field_type'] ?? 'text');

$width = (int) ($field['column_width'] ?? 12);

if (!in_array($width, [3,4,6,8,9,12], true)) {
    $width = 12;
}
?>

<div
    class="sortable-field"
    data-field-id="<?= (int) $field['id'] ?>"
    data-width="<?= $width ?>">

        <div
            class="designer-field-card"
            data-width="<?= $width ?>">

<div class="field-card-toolbar">

    <span class="field-type-badge">

        <?= htmlspecialchars(
            strtoupper($type),
            ENT_QUOTES,
            'UTF-8'
        ) ?>

    </span>


    <div class="d-flex align-items-center gap-1">

        <button
            type="button"
            class="btn btn-sm btn-light edit-field-btn"
            data-bs-toggle="modal"
            data-bs-target="#editFieldModal"

            data-id="<?= (int) $field['id'] ?>"

            data-label="<?= htmlspecialchars(
                (string) (
                    $field['field_label']
                    ?? ''
                ),
                ENT_QUOTES,
                'UTF-8'
            ) ?>"

            data-placeholder="<?= htmlspecialchars(
                (string) (
                    $field['placeholder']
                    ?? ''
                ),
                ENT_QUOTES,
                'UTF-8'
            ) ?>"

            data-help-text="<?= htmlspecialchars(
                (string) (
                    $field['help_text']
                    ?? ''
                ),
                ENT_QUOTES,
                'UTF-8'
            ) ?>"

            data-default-value="<?= htmlspecialchars(
                (string) (
                    $field['default_value']
                    ?? ''
                ),
                ENT_QUOTES,
                'UTF-8'
            ) ?>"

            data-required="<?= (int) (
                $field['is_required']
                ?? 0
            ) ?>"

            data-validation-rules="<?= htmlspecialchars(
                (string) (
                    $field['validation_rules']
                    ?? ''
                ),
                ENT_QUOTES,
                'UTF-8'
            ) ?>"

            data-column-width="<?= $width ?>"

            data-field-type="<?= htmlspecialchars(
                $type,
                ENT_QUOTES,
                'UTF-8'
            ) ?>"

            title="Edit Field">

            <i class="bi bi-pencil"></i>

        </button>


        <form
            method="POST"
            action="/public/dynamic-forms/fields/deactivate"
            class="d-inline m-0"
            onsubmit="return confirm('Remove this field from the form?');">

            <input
                type="hidden"
                name="id"
                value="<?= (int) $field['id'] ?>">

            <input
                type="hidden"
                name="form_id"
                value="<?= $formId ?>">

            <button
                type="submit"
                class="btn btn-sm btn-outline-danger"
                title="Remove Field">

                <i class="bi bi-trash"></i>

            </button>

        </form>

    </div>

</div>
<label class="form-label field-preview-label"><?= htmlspecialchars((string)($field['field_label']??''),ENT_QUOTES,'UTF-8') ?><?php if((int)($field['is_required']??0)===1): ?><span class="text-danger">*</span><?php endif; ?></label>
<?php
$currentOptions =
    $fieldOptions[
        (int) $field['id']
    ]
    ?? [];
?>


<?php if ($type === 'textarea'): ?>

    <textarea
        class="form-control"
        rows="3"
        disabled
        placeholder="<?= htmlspecialchars(
            (string) (
                $field['placeholder']
                ?? ''
            ),
            ENT_QUOTES,
            'UTF-8'
        ) ?>"></textarea>


<?php elseif ($type === 'select'): ?>

    <select
        class="form-select"
        disabled>

        <option value="">
            Select an option
        </option>

        <?php foreach (
            $currentOptions
            as $option
        ): ?>

            <option
                value="<?= htmlspecialchars(
                    (string) (
                        $option['option_value']
                        ?? ''
                    ),
                    ENT_QUOTES,
                    'UTF-8'
                ) ?>">

                <?= htmlspecialchars(
                    (string) (
                        $option['option_label']
                        ?? ''
                    ),
                    ENT_QUOTES,
                    'UTF-8'
                ) ?>

            </option>

        <?php endforeach; ?>

    </select>


<?php elseif ($type === 'radio'): ?>

    <?php if (empty($currentOptions)): ?>

        <div class="small text-muted">
            No options configured.
        </div>

    <?php else: ?>

        <?php foreach (
            $currentOptions
            as $option
        ): ?>

            <div class="form-check mb-1">

                <input
                    class="form-check-input"
                    type="radio"
                    disabled>

                <label class="form-check-label">

                    <?= htmlspecialchars(
                        (string) (
                            $option['option_label']
                            ?? ''
                        ),
                        ENT_QUOTES,
                        'UTF-8'
                    ) ?>

                </label>

            </div>

        <?php endforeach; ?>

    <?php endif; ?>


<?php elseif ($type === 'checkbox'): ?>

    <?php if (empty($currentOptions)): ?>

        <div class="small text-muted">
            No options configured.
        </div>

    <?php else: ?>

        <?php foreach (
            $currentOptions
            as $option
        ): ?>

            <div class="form-check mb-1">

                <input
                    class="form-check-input"
                    type="checkbox"
                    disabled>

                <label class="form-check-label">

                    <?= htmlspecialchars(
                        (string) (
                            $option['option_label']
                            ?? ''
                        ),
                        ENT_QUOTES,
                        'UTF-8'
                    ) ?>

                </label>

            </div>

        <?php endforeach; ?>

    <?php endif; ?>


<?php elseif ($type === 'number'): ?>

    <input
        type="number"
        class="form-control"
        disabled
        placeholder="<?= htmlspecialchars(
            (string) (
                $field['placeholder']
                ?? 'Enter number'
            ),
            ENT_QUOTES,
            'UTF-8'
        ) ?>">


<?php elseif ($type === 'date'): ?>

    <input
        type="date"
        class="form-control"
        disabled>


<?php elseif ($type === 'time'): ?>

    <input
        type="time"
        class="form-control"
        disabled>


<?php elseif ($type === 'email'): ?>

    <input
        type="email"
        class="form-control"
        disabled
        placeholder="<?= htmlspecialchars(
            (string) (
                $field['placeholder']
                ?? 'name@example.com'
            ),
            ENT_QUOTES,
            'UTF-8'
        ) ?>">


<?php elseif ($type === 'phone'): ?>

    <input
        type="tel"
        class="form-control"
        disabled
        placeholder="<?= htmlspecialchars(
            (string) (
                $field['placeholder']
                ?? 'Enter phone number'
            ),
            ENT_QUOTES,
            'UTF-8'
        ) ?>">


<?php elseif ($type === 'file'): ?>

    <input
        type="file"
        class="form-control"
        disabled>


<?php else: ?>

    <input
        type="text"
        class="form-control"
        disabled
        placeholder="<?= htmlspecialchars(
            (string) (
                $field['placeholder']
                ?? ''
            ),
            ENT_QUOTES,
            'UTF-8'
        ) ?>">

<?php endif; ?>
<?php if(!empty($field['help_text'])): ?><div class="form-text"><?= htmlspecialchars((string)$field['help_text'],ENT_QUOTES,'UTF-8') ?></div><?php endif; ?>
        </div>

    

</div>


</div>

<?php endforeach; ?>

    </div>

<?php endif; ?>
</div></div>
<?php endforeach; ?>

</div>

<?php endif; ?>
</div></div></div></div>

<div class="col-xl-3"><div class="designer-column-sticky"><div class="designer-panel">
<div class="designer-panel-header"><h6 class="designer-panel-title">Properties</h6><div class="designer-panel-subtitle">Configure fields using their edit button.</div></div>
<div class="properties-empty"><i class="bi bi-sliders"></i>Select a field from the canvas to edit its properties.</div>
</div></div></div>
</div></div>

<!-- SECTION MODALS -->
<div class="modal fade" id="addSectionModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-lg modal-dialog-centered"><div class="modal-content">
<form method="POST" action="/public/dynamic-forms/sections/create"><input type="hidden" name="form_id" value="<?= $formId ?>">
<div class="modal-header"><div><h5 class="modal-title">Add Form Section</h5><div class="small text-muted">Group related form fields into a section.</div></div><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
<div class="modal-body"><div class="mb-3"><label class="form-label">Section Title <span class="text-danger">*</span></label><input type="text" name="section_title" class="form-control" required></div>
<label class="form-label">Description</label><textarea name="section_description" class="form-control" rows="4"></textarea></div>
<div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary">Add Section</button></div>
</form></div></div></div>

<div class="modal fade" id="editSectionModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-lg modal-dialog-centered"><div class="modal-content">
<form method="POST" action="/public/dynamic-forms/sections/update"><input type="hidden" name="id" id="editSectionId"><input type="hidden" name="form_id" value="<?= $formId ?>">
<div class="modal-header"><h5 class="modal-title">Edit Form Section</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
<div class="modal-body"><div class="mb-3"><label class="form-label">Section Title</label><input type="text" name="section_title" id="editSectionTitle" class="form-control" required></div>
<label class="form-label">Description</label><textarea name="section_description" id="editSectionDescription" class="form-control" rows="4"></textarea></div>
<div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary">Update Section</button></div>
</form></div></div></div>

<!-- FIELD MODALS -->
<div class="modal fade" id="addFieldModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable"><div class="modal-content">
<form method="POST" action="/public/dynamic-forms/fields/create"><input type="hidden" name="form_id" value="<?= $formId ?>"><input type="hidden" name="field_type" id="addFieldType">
<div class="modal-header"><div><h5 class="modal-title">Add <span id="addFieldTypeLabel">Field</span></h5><div class="small text-muted">Configure the new form field.</div></div><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
<div class="modal-body"><div class="row g-3">
<div class="col-md-6"><label class="form-label">Target Section <span class="text-danger">*</span></label><select name="section_id" class="form-select" required><option value="">Select section</option><?php foreach($sections as $section): ?><option value="<?= (int)$section['id'] ?>"><?= htmlspecialchars((string)($section['section_title']??''),ENT_QUOTES,'UTF-8') ?></option><?php endforeach; ?></select></div>
<div class="col-md-6"><label class="form-label">Field Label <span class="text-danger">*</span></label><input type="text" name="field_label" class="form-control" required></div>
<div class="col-md-6"><label class="form-label">Placeholder</label><input type="text" name="placeholder" class="form-control"></div>
<div class="col-md-6"><label class="form-label">Column Width</label><select name="column_width" class="form-select"><option value="12">Full Width</option><option value="9">Three Quarters</option><option value="8">Two Thirds</option><option value="6">Half Width</option><option value="4">One Third</option><option value="3">One Quarter</option></select></div>
<div class="col-md-6"><label class="form-label">Default Value</label><input type="text" name="default_value" class="form-control"></div>
<div
    id="numberSettings"
    class="d-none">

    <hr>

    <h6 class="text-primary">
        Number Settings
    </h6>

    <div class="row">

        <div class="col-md-4">

            <label class="form-label">
                Minimum
            </label>

            <input
                type="number"
                name="number_min"
                class="form-control">

        </div>

        <div class="col-md-4">

            <label class="form-label">
                Maximum
            </label>

            <input
                type="number"
                name="number_max"
                class="form-control">

        </div>

        <div class="col-md-4">

            <label class="form-label">
                Step
            </label>

            <input
                type="number"
                value="1"
                name="number_step"
                class="form-control">

        </div>

    </div>

</div>
<div
    id="dateSettings"
    class="d-none">

    <hr>

    <h6 class="text-primary">
        Date Settings
    </h6>

    <div class="row">

        <div class="col-md-6">

            <label class="form-label">
                Minimum Date
            </label>

            <input
                type="date"
                name="date_min"
                class="form-control">

        </div>

        <div class="col-md-6">

            <label class="form-label">
                Maximum Date
            </label>

            <input
                type="date"
                name="date_max"
                class="form-control">

        </div>

    </div>

</div>
<div
    id="timeSettings"
    class="d-none">

    <hr>

    <h6 class="text-primary">
        Time Settings
    </h6>

    <div class="row">

        <div class="col-md-6">

            <label class="form-label">
                Minimum Time
            </label>

            <input
                type="time"
                name="time_min"
                class="form-control">

        </div>

        <div class="col-md-6">

            <label class="form-label">
                Maximum Time
            </label>

            <input
                type="time"
                name="time_max"
                class="form-control">

        </div>

    </div>

</div>
<div
    id="fileSettings"
    class="d-none">

    <hr>

    <h6 class="text-primary">

        File Upload Settings

    </h6>

    <div class="mb-3">

        <label class="form-label">

            Allowed Extensions

        </label>

        <select
            multiple
            name="allowed_extensions[]"
            class="form-select">

            <option value="pdf">PDF</option>

            <option value="doc">DOC</option>

            <option value="docx">DOCX</option>

            <option value="jpg">JPG</option>

            <option value="jpeg">JPEG</option>

            <option value="png">PNG</option>

            <option value="xlsx">XLSX</option>

        </select>

    </div>

    <div class="row">

        <div class="col-md-6">

            <label class="form-label">

                Maximum Size (MB)

            </label>

            <input
                type="number"
                value="5"
                name="max_file_size"
                class="form-control">

        </div>

        <div class="col-md-6 d-flex align-items-end">

            <div class="form-check">

                <input
                    type="checkbox"
                    name="multiple_upload"
                    class="form-check-input"
                    value="1">

                <label
                    class="form-check-label">

                    Multiple Upload

                </label>

            </div>

        </div>

    </div>

</div>


<div class="col-12"><label class="form-label">Help Text</label><textarea name="help_text" class="form-control" rows="3"></textarea></div>
<div
    class="col-12 d-none"
    id="addChoiceOptions">

    <div class="border rounded-3 p-3 bg-light">

        <div
            class="d-flex justify-content-between
                   align-items-center mb-3">

            <div>
                <div class="fw-semibold">
                    Choice Options
                </div>

                <div class="small text-muted">
                    Add options for this field.
                </div>
            </div>

            <button
                type="button"
                class="btn btn-sm btn-outline-primary"
                id="addOptionRow">

                <i class="bi bi-plus-lg me-1"></i>
                Add Option

            </button>

        </div>


        <div id="optionRows">

            <div
                class="input-group mb-2 option-row">

                <span class="input-group-text">
                    1
                </span>

                <input
                    type="text"
                    name="options[]"
                    class="form-control"
                    placeholder="Option label">

                <button
                    type="button"
                    class="btn btn-outline-danger remove-option">

                    <i class="bi bi-trash"></i>

                </button>

            </div>


            <div
                class="input-group mb-2 option-row">

                <span class="input-group-text">
                    2
                </span>

                <input
                    type="text"
                    name="options[]"
                    class="form-control"
                    placeholder="Option label">

                <button
                    type="button"
                    class="btn btn-outline-danger remove-option">

                    <i class="bi bi-trash"></i>

                </button>

            </div>

        </div>

    </div>

</div>


<div class="col-12"><div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="is_required" value="1" id="addFieldRequired"><label class="form-check-label" for="addFieldRequired">Required field</label></div></div>
</div></div>
<div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary">Add Field</button></div>
</form></div></div></div>

<div class="modal fade" id="editFieldModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable"><div class="modal-content">
    
    
<form method="POST" action="/public/dynamic-forms/fields/update"><input type="hidden" name="form_id" value="<?= $formId ?>"><input type="hidden" name="id" id="editFieldId">
<div class="modal-header"><h5 class="modal-title">Edit Field</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
<div class="modal-body"><div class="row g-3">
<div class="col-md-8"><label class="form-label">Field Label</label><input type="text" name="field_label" id="editFieldLabel" class="form-control" required></div>
<div class="col-md-4"><label class="form-label">Column Width</label><select name="column_width" id="editFieldColumnWidth" class="form-select"><option value="12">Full Width</option><option value="9">Three Quarters</option><option value="8">Two Thirds</option><option value="6">Half Width</option><option value="4">One Third</option><option value="3">One Quarter</option></select></div>
<div class="col-md-6"><label class="form-label">Placeholder</label><input type="text" name="placeholder" id="editFieldPlaceholder" class="form-control"></div>
<div class="col-md-6"><label class="form-label">Default Value</label><input type="text" name="default_value" id="editFieldDefaultValue" class="form-control"></div>

<div id="editNumberSettings" class="d-none">

    <hr>

    <h6 class="text-primary">
        Number Settings
    </h6>

    <div class="row">

        <div class="col-md-4">

            <label class="form-label">
                Minimum
            </label>

            <input
                id="editNumberMin"
                type="number"
                name="number_min"
                class="form-control">

        </div>

        <div class="col-md-4">

            <label class="form-label">
                Maximum
            </label>

            <input
                id="editNumberMax"
                type="number"
                name="number_max"
                class="form-control">

        </div>

        <div class="col-md-4">

            <label class="form-label">
                Step
            </label>

            <input
                id="editNumberStep"
                type="number"
                name="number_step"
                class="form-control">

        </div>

    </div>

</div>
<div id="editDateSettings" class="d-none">

    <hr>

    <h6 class="text-primary">
        Date Settings
    </h6>

    <div class="row">

        <div class="col-md-6">

            <label class="form-label">
                Minimum Date
            </label>

            <input
                id="editDateMin"
                type="date"
                name="date_min"
                class="form-control">

        </div>

        <div class="col-md-6">

            <label class="form-label">
                Maximum Date
            </label>

            <input
                id="editDateMax"
                type="date"
                name="date_max"
                class="form-control">

        </div>

    </div>

</div>

<div id="editTimeSettings" class="d-none">

    <hr>

    <h6 class="text-primary">
        Time Settings
    </h6>

    <div class="row">

        <div class="col-md-6">

            <label class="form-label">
                Minimum Time
            </label>

            <input
                id="editTimeMin"
                type="time"
                name="time_min"
                class="form-control">

        </div>

        <div class="col-md-6">

            <label class="form-label">
                Maximum Time
            </label>

            <input
                id="editTimeMax"
                type="time"
                name="time_max"
                class="form-control">

        </div>

    </div>

</div>

<div id="editFileSettings" class="d-none">

    <hr>

    <h6 class="text-primary">
        File Upload Settings
    </h6>

    <div class="mb-3">

        <label class="form-label">
            Allowed Extensions
        </label>

        <select
            id="editAllowedExtensions"
            name="allowed_extensions[]"
            multiple
            class="form-select">

            <option value="pdf">PDF</option>
            <option value="doc">DOC</option>
            <option value="docx">DOCX</option>
            <option value="jpg">JPG</option>
            <option value="jpeg">JPEG</option>
            <option value="png">PNG</option>
            <option value="xlsx">XLSX</option>

        </select>

    </div>

    <div class="row">

        <div class="col-md-6">

            <label class="form-label">
                Maximum Size (MB)
            </label>

            <input
                id="editMaxFileSize"
                type="number"
                name="max_file_size"
                class="form-control">

        </div>

        <div class="col-md-6 d-flex align-items-end">

            <div class="form-check">

                <input
                    id="editMultipleUpload"
                    type="checkbox"
                    name="multiple_upload"
                    class="form-check-input"
                    value="1">

                <label class="form-check-label">
                    Multiple Upload
                </label>

            </div>

        </div>

    </div>

</div>





<div class="col-12"><label class="form-label">Help Text</label><textarea name="help_text" id="editFieldHelpText" class="form-control" rows="3"></textarea></div>

<div class="col-12 d-none" id="editChoiceOptions">
    <div class="border rounded-3 p-3 bg-light">
<div class="d-flex justify-content-between align-items-center mb-3">

    <div>
        <div class="fw-semibold">
            Choice Options
        </div>

        <div class="small text-muted">
            Edit, remove, or add choices for this field.
        </div>
    </div>

    <button
        type="button"
        class="btn btn-sm btn-outline-primary"
        id="editAddOptionRow">

        <i class="bi bi-plus-lg me-1"></i>
        Add Option

    </button>

</div>
        <div id="editOptionRows"></div>
    </div>
</div>
<div class="col-12"><div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="is_required" value="1" id="editFieldRequired"><label class="form-check-label" for="editFieldRequired">Required field</label></div></div>
</div></div>
<div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary">Update Field</button></div>
</form></div></div></div>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.6/Sortable.min.js"></script>

<script>
window.dynamicFieldOptions = <?= json_encode(
    $fieldOptions ?? [],
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
) ?>;

document.addEventListener('DOMContentLoaded', function () {
    const choiceTypes = ['select', 'radio', 'checkbox'];

    document.querySelectorAll('.add-field-btn').forEach(function (button) {
        button.addEventListener('click', function () {
            const available = <?= !empty($sections) ? 'true' : 'false' ?>;

            if (!available) {
                alert('Create a section before adding fields.');
                return;
            }

            const fieldType = this.dataset.fieldType || '';
            // Hide every smart panel first
document.getElementById('numberSettings')
    ?.classList.add('d-none');

document.getElementById('dateSettings')
    ?.classList.add('d-none');

document.getElementById('timeSettings')
    ?.classList.add('d-none');

document.getElementById('fileSettings')
    ?.classList.add('d-none');


// Show only the correct panel
if (fieldType === 'number') {

    document
        .getElementById('numberSettings')
        ?.classList.remove('d-none');

}

if (fieldType === 'date') {

    document
        .getElementById('dateSettings')
        ?.classList.remove('d-none');

}

if (fieldType === 'time') {

    document
        .getElementById('timeSettings')
        ?.classList.remove('d-none');

}

if (fieldType === 'file') {

    document
        .getElementById('fileSettings')
        ?.classList.remove('d-none');

}
            
            
            const fieldTypeLabel = this.dataset.fieldTypeLabel || 'Field';

            document.getElementById('addFieldType').value = fieldType;
            document.getElementById('addFieldTypeLabel').textContent = fieldTypeLabel;

            const choiceArea = document.getElementById('addChoiceOptions');

            if (choiceArea) {
                choiceArea.classList.toggle(
                    'd-none',
                    !choiceTypes.includes(fieldType)
                );
            }

            bootstrap.Modal
                .getOrCreateInstance(document.getElementById('addFieldModal'))
                .show();
        });
    });

    const optionRows = document.getElementById('optionRows');
    const addOptionButton = document.getElementById('addOptionRow');

    function refreshOptionNumbers() {
        if (!optionRows) {
            return;
        }

        optionRows.querySelectorAll('.option-row').forEach(function (row, index) {
            const number = row.querySelector('.input-group-text');

            if (number) {
                number.textContent = index + 1;
            }
        });
    }

    if (optionRows && addOptionButton) {
        addOptionButton.addEventListener('click', function () {
            const row = document.createElement('div');

            row.className = 'input-group mb-2 option-row';
            row.innerHTML = `
                <span class="input-group-text"></span>
                <input
                    type="text"
                    name="options[]"
                    class="form-control"
                    placeholder="Option label">
                <button
                    type="button"
                    class="btn btn-outline-danger remove-option">
                    <i class="bi bi-trash"></i>
                </button>
            `;

            optionRows.appendChild(row);
            refreshOptionNumbers();

            const input = row.querySelector('input');

            if (input) {
                input.focus();
            }
        });

        optionRows.addEventListener('click', function (event) {
            const removeButton = event.target.closest('.remove-option');

            if (!removeButton) {
                return;
            }

            const rows = optionRows.querySelectorAll('.option-row');

            if (rows.length <= 1) {
                const input = rows[0].querySelector('input');

                if (input) {
                    input.value = '';
                }

                return;
            }

            const row = removeButton.closest('.option-row');

            if (row) {
                row.remove();
            }

            refreshOptionNumbers();
        });

        refreshOptionNumbers();
    }

    const editChoiceArea = document.getElementById('editChoiceOptions');
    const editOptionRows = document.getElementById('editOptionRows');
    const editAddOptionButton = document.getElementById('editAddOptionRow');

    function refreshEditOptionNumbers() {
        if (!editOptionRows) {
            return;
        }

        editOptionRows
            .querySelectorAll('.edit-option-row')
            .forEach(function (row, index) {
                const number = row.querySelector('.input-group-text');

                if (number) {
                    number.textContent = index + 1;
                }
            });
    }

    function addEditOptionRow(value = '') {
        if (!editOptionRows) {
            return;
        }

        const row = document.createElement('div');
        row.className = 'input-group mb-2 edit-option-row';

        const number = document.createElement('span');
        number.className = 'input-group-text';

        const input = document.createElement('input');
        input.type = 'text';
        input.name = 'options[]';
        input.className = 'form-control';
        input.placeholder = 'Option label';
        input.value = value;

        const removeButton = document.createElement('button');
        removeButton.type = 'button';
        removeButton.className = 'btn btn-outline-danger remove-edit-option';
        removeButton.innerHTML = '<i class="bi bi-trash"></i>';

        row.appendChild(number);
        row.appendChild(input);
        row.appendChild(removeButton);
        editOptionRows.appendChild(row);

        refreshEditOptionNumbers();
    }

    if (editAddOptionButton && editOptionRows) {
        editAddOptionButton.addEventListener('click', function () {
            addEditOptionRow('');
        });

        editOptionRows.addEventListener('click', function (event) {
            const removeButton = event.target.closest('.remove-edit-option');

            if (!removeButton) {
                return;
            }

            const rows = editOptionRows.querySelectorAll('.edit-option-row');

            if (rows.length <= 1) {
                const input = rows[0] ? rows[0].querySelector('input') : null;

                if (input) {
                    input.value = '';
                }

                return;
            }

            const row = removeButton.closest('.edit-option-row');

            if (row) {
                row.remove();
            }

            refreshEditOptionNumbers();
        });
    }

document.querySelectorAll('.edit-field-btn').forEach(function(button){

    button.addEventListener('click', function(){

const fieldId = this.dataset.id || '';
const fieldType = this.dataset.fieldType || '';

document.getElementById('editFieldId').value = fieldId;
document.getElementById('editFieldLabel').value = this.dataset.label || '';
document.getElementById('editFieldPlaceholder').value = this.dataset.placeholder || '';
document.getElementById('editFieldHelpText').value = this.dataset.helpText || '';
document.getElementById('editFieldDefaultValue').value = this.dataset.defaultValue || '';
document.getElementById('editFieldColumnWidth').value = this.dataset.columnWidth || '12';
document.getElementById('editFieldRequired').checked = this.dataset.required === '1';

const rules =
    this.dataset.validationRules || '{}';

let json = {};

try {

    json = JSON.parse(rules);

} catch (e) {

    json = {};
}
/*
|--------------------------------------------------------------------------
| Hide all smart panels
|--------------------------------------------------------------------------
*/

document.getElementById('editNumberSettings')?.classList.add('d-none');
document.getElementById('editDateSettings')?.classList.add('d-none');
document.getElementById('editTimeSettings')?.classList.add('d-none');
document.getElementById('editFileSettings')?.classList.add('d-none');

if (editChoiceArea) {
    editChoiceArea.classList.add('d-none');
}

/*
|--------------------------------------------------------------------------
| Show panel by type
|--------------------------------------------------------------------------
*/

switch (fieldType) {

    case 'number':

        document
            .getElementById('editNumberSettings')
            ?.classList.remove('d-none');

        document.getElementById('editNumberMin').value =
            json.min ?? '';

        document.getElementById('editNumberMax').value =
            json.max ?? '';

        document.getElementById('editNumberStep').value =
            json.step ?? '';

        break;


    case 'date':

        document
            .getElementById('editDateSettings')
            ?.classList.remove('d-none');

        document.getElementById('editDateMin').value =
            json.min_date ?? '';

        document.getElementById('editDateMax').value =
            json.max_date ?? '';

        break;


    case 'time':

        document
            .getElementById('editTimeSettings')
            ?.classList.remove('d-none');

        document.getElementById('editTimeMin').value =
            json.min_time ?? '';

        document.getElementById('editTimeMax').value =
            json.max_time ?? '';

        break;


    case 'file':

        document
            .getElementById('editFileSettings')
            ?.classList.remove('d-none');

        document.getElementById('editMaxFileSize').value =
            json.max_size ?? '';

        document.getElementById('editMultipleUpload').checked =
            json.multiple === true;

        break;
}
const extensionSelect =
    document.getElementById('editAllowedExtensions');

if (extensionSelect) {

    Array.from(extensionSelect.options).forEach(function(option) {

        option.selected = false;

    });

    (json.allowed_extensions || []).forEach(function(ext) {

        const option = extensionSelect.querySelector(
            'option[value="' + ext + '"]'
        );

        if (option) {
            option.selected = true;
        }

    });

}
/*
|--------------------------------------------------------------------------
| Choice Options
|--------------------------------------------------------------------------
*/

if (editChoiceArea && editOptionRows) {

    editOptionRows.innerHTML = '';

    if (choiceTypes.includes(fieldType)) {

        editChoiceArea.classList.remove('d-none');

        const options =
            window.dynamicFieldOptions[fieldId] || [];

        options.forEach(function (option) {

            addEditOptionRow(
                option.option_label || ''
            );

        });

        if (options.length === 0) {
            addEditOptionRow('');
        }
    }
}
    });

});

//--------------------------------------------------
// Drag Fields
//--------------------------------------------------

document
.querySelectorAll('.sortable-fields')
.forEach(function (container) {

    console.log('Initializing Sortable:', container);

new Sortable(container,{

    group:{
        name:'dynamic-fields',
        pull:true,
        put:true
    },

    animation:200,

    draggable:'.sortable-field',

    handle:'.designer-field-card',

    ghostClass:'sortable-ghost',

    chosenClass:'sortable-chosen',

    emptyInsertThreshold:80,

    onStart(){
        console.log('Drag started');
    },

    onEnd(evt){
        console.log(evt);
    }

});

});


//--------------------------------------------------
// Drag Sections
//--------------------------------------------------

const sortableSections =
    document.getElementById('sortableSections');

if (sortableSections) {

    new Sortable(sortableSections, {

        animation: 200,

        draggable: '.canvas-section',

        handle: '.canvas-section-header',

        ghostClass: 'bg-light'

    });

}

});
</script>

<?php
$content = ob_get_clean();
$title = 'Form Designer';
include APP_PATH . '/Modules/Administration/Views/layouts/admin.php';
