<?php

declare(strict_types=1);

$forms = $forms ?? [];

ob_start();

?>


<div class="container-fluid py-4 dynamic-form-page">

    <!-- =====================================================
         PAGE HERO
    ====================================================== -->

    <div class="form-hero mb-4">

        <div class="row align-items-center g-4">

            <div class="col-lg-8">

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

                    <div class="hero-icon">
                        <i class="bi bi-ui-checks-grid"></i>
                    </div>

                    <div>

                        <div class="hero-eyebrow">
                            FORM WORKSPACE
                        </div>

                        <h2 class="mb-1 fw-bold">
                            Dynamic Form Builder
                        </h2>

                        <p class="mb-0 text-muted">
                            Design, organize, publish and manage
                            data collection forms.
                        </p>

                    </div>

                </div>

            </div>


            <div class="col-lg-4 text-lg-end">

                <button
                    type="button"
                    class="btn btn-primary btn-lg px-4 create-form-btn"
                    data-bs-toggle="modal"
                    data-bs-target="#createFormModal">

                    <i class="bi bi-plus-lg me-2"></i>
                    Create New Form

                </button>

            </div>

        </div>

    </div>

    <?php if (!empty($created)): ?>

        <div class="alert alert-success alert-dismissible fade show">
            Dynamic form created successfully.

            <button
                type="button"
                class="btn-close"
                data-bs-dismiss="alert">
            </button>
        </div>

    <?php endif; ?>


    <?php if (!empty($updated)): ?>

        <div class="alert alert-success alert-dismissible fade show">
            Dynamic form updated successfully.

            <button
                type="button"
                class="btn-close"
                data-bs-dismiss="alert">
            </button>
        </div>

    <?php endif; ?>


    <?php if (!empty($statusUpdated)): ?>

        <div class="alert alert-success alert-dismissible fade show">
            Form status updated successfully.

            <button
                type="button"
                class="btn-close"
                data-bs-dismiss="alert">
            </button>
        </div>

    <?php endif; ?>


    <?php if (!empty($deleted)): ?>

        <div class="alert alert-success alert-dismissible fade show">
            Draft form deleted successfully.

            <button
                type="button"
                class="btn-close"
                data-bs-dismiss="alert">
            </button>
        </div>

    <?php endif; ?>


    <?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; ?>

<?php

$totalForms = count($forms);

$draftForms = count(
    array_filter(
        $forms,
        fn ($form) =>
            ($form['status'] ?? '') === 'draft'
    )
);

$publishedForms = count(
    array_filter(
        $forms,
        fn ($form) =>
            ($form['status'] ?? '') === 'published'
    )
);

$archivedForms = count(
    array_filter(
        $forms,
        fn ($form) =>
            ($form['status'] ?? '') === 'archived'
    )
);

?>


<div class="row g-3 mb-4">

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

        <div class="metric-card">

            <div class="metric-icon">
                <i class="bi bi-files"></i>
            </div>

            <div>
                <div class="metric-label">
                    Total Forms
                </div>

                <div class="metric-value">
                    <?= $totalForms ?>
                </div>
            </div>

        </div>

    </div>


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

        <div class="metric-card">

            <div class="metric-icon">
                <i class="bi bi-pencil-square"></i>
            </div>

            <div>
                <div class="metric-label">
                    Draft Forms
                </div>

                <div class="metric-value">
                    <?= $draftForms ?>
                </div>
            </div>

        </div>

    </div>


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

        <div class="metric-card">

            <div class="metric-icon">
                <i class="bi bi-check2-circle"></i>
            </div>

            <div>
                <div class="metric-label">
                    Published
                </div>

                <div class="metric-value">
                    <?= $publishedForms ?>
                </div>
            </div>

        </div>

    </div>


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

        <div class="metric-card">

            <div class="metric-icon">
                <i class="bi bi-archive"></i>
            </div>

            <div>
                <div class="metric-label">
                    Archived
                </div>

                <div class="metric-value">
                    <?= $archivedForms ?>
                </div>
            </div>

        </div>

    </div>

</div>
<div class="card forms-workspace-card">

    <div class="card-header workspace-header">

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

            <div>

                <h5 class="mb-1 fw-bold">
                    Form Library
                </h5>

                <div class="small text-muted">
                    Manage form structure,
                    lifecycle and publishing status.
                </div>

            </div>


            <div class="form-search-box">

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

                <input
                    type="text"
                    id="formSearchInput"
                    placeholder="Search forms...">

            </div>

        </div>

    </div>

    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table align-middle mb-0">
                <thead><tr><th>Code</th><th>Form Name</th><th>Category</th><th>Version</th><th>Status</th><th>Published</th><th class="text-end">Actions</th></tr></thead>
                <tbody>
                <?php if (empty($forms)): ?>
                    <tr><td colspan="7" class="text-center py-5"><div class="empty-state"><div class="empty-state-icon"><i class="bi bi-ui-checks-grid"></i></div><h5 class="mt-3 mb-1">No forms yet</h5><p class="text-muted mb-3">Create your first dynamic form to begin building data collection workflows.</p><button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createFormModal"><i class="bi bi-plus-lg me-1"></i>Create First Form</button></div></td></tr>
                <?php else: ?>
                    <?php foreach ($forms as $form): $status = (string) ($form['status'] ?? 'draft'); ?>
                    <tr class="form-data-row">
                        <td><span class="form-code"><?= htmlspecialchars((string)($form['form_code'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span></td>
                        <td><div class="form-name"><?= htmlspecialchars((string)($form['form_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></div><?php if (!empty($form['description'])): ?><div class="form-description"><?= htmlspecialchars((string)$form['description'], ENT_QUOTES, 'UTF-8') ?></div><?php endif; ?></td>
                        <td><?= htmlspecialchars((string)($form['form_category'] ?? '—'), ENT_QUOTES, 'UTF-8') ?></td>
                        <td><span class="version-pill">v<?= (int)($form['version'] ?? 1) ?></span></td>
                        <td><?php if ($status === 'published'): ?><span class="status-pill status-published"><i class="bi bi-check-circle-fill"></i> Published</span><?php elseif ($status === 'archived'): ?><span class="status-pill status-archived"><i class="bi bi-archive-fill"></i> Archived</span><?php else: ?><span class="status-pill status-draft"><i class="bi bi-pencil-fill"></i> Draft</span><?php endif; ?></td>
                        <td><?= !empty($form['published_at']) ? htmlspecialchars((string)$form['published_at'], ENT_QUOTES, 'UTF-8') : '—' ?></td>
                        <td class="text-end"><div class="action-group">
                            <a href="/public/dynamic-forms/designer?id=<?= (int)$form['id'] ?>" class="btn btn-sm btn-outline-primary" title="Open Designer"><i class="bi bi-grid-3x3-gap"></i></a>
                            <button
                                type="button"
                                class="btn btn-sm btn-outline-warning edit-form-btn edit-form-action"
                                title="Edit Form"
                                data-bs-toggle="modal"
                                data-bs-target="#editFormModal"
                                data-id="<?= (int) $form['id'] ?>"
                                data-form-name="<?= htmlspecialchars(
                                    (string) ($form['form_name'] ?? ''),
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>"
                                data-form-category="<?= htmlspecialchars(
                                    (string) ($form['form_category'] ?? ''),
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>"
                                data-description="<?= htmlspecialchars(
                                    (string) ($form['description'] ?? ''),
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>">
                                <i class="bi bi-pencil"></i>
                                <span>Edit</span>
                            </button>
                            <?php if ($status === 'draft'): ?>

                                <form method="POST" action="/public/dynamic-forms/publish" class="d-inline">
                                    <input type="hidden" name="id" value="<?= (int) $form['id'] ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-success" title="Publish Form" onclick="return confirm('Publish this form?');">
                                        <i class="bi bi-send-check"></i>
                                    </button>
                                </form>

                                <form method="POST" action="/public/dynamic-forms/delete" class="d-inline" onsubmit="return confirm('Delete this draft form permanently? Sections, fields and options will also be deleted.');">
                                    <input type="hidden" name="id" value="<?= (int) $form['id'] ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-danger" title="Delete Draft Form">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>

                            <?php elseif ($status === 'published'): ?>

                                <form method="POST" action="/public/dynamic-forms/archive" class="d-inline">
                                    <input type="hidden" name="id" value="<?= (int) $form['id'] ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-secondary" title="Archive Form" onclick="return confirm('Archive this form?');">
                                        <i class="bi bi-archive"></i>
                                    </button>
                                </form>

                            <?php endif; ?>
                        </div></td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>


<!-- =========================================================
     CREATE FORM MODAL
========================================================= -->

<div
    class="modal fade"
    id="createFormModal"
    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/create">

                <div class="modal-header">

                    <h5 class="modal-title">
                        Create Dynamic Form
                    </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-4">

                            <label class="form-label">
                                Form Code
                                <span class="text-danger">*</span>
                            </label>

                            <input
                                type="text"
                                name="form_code"
                                class="form-control"
                                placeholder="PERF-EVAL"
                                required>

                            <div class="form-text">
                                Unique code. Example: PERF-EVAL.
                            </div>

                        </div>


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

                            <label class="form-label">
                                Form Name
                                <span class="text-danger">*</span>
                            </label>

                            <input
                                type="text"
                                name="form_name"
                                class="form-control"
                                placeholder="Employee Performance Evaluation"
                                required>

                        </div>


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

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

                            <input
                                type="text"
                                name="form_category"
                                class="form-control"
                                placeholder="Performance">

                        </div>


                        <div class="col-12">

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

                            <textarea
                                name="description"
                                class="form-control"
                                rows="4"
                                placeholder="Describe the purpose of this form."></textarea>

                        </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">

                        <i class="bi bi-save me-1"></i>
                        Create Form

                    </button>

                </div>

            </form>

        </div>

    </div>

</div>


<!-- =========================================================
     EDIT FORM MODAL
========================================================= -->

<div
    class="modal fade"
    id="editFormModal"
    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/update">

                <input
                    type="hidden"
                    name="id"
                    id="editFormId">


                <div class="modal-header">

                    <h5 class="modal-title">
                        Edit Dynamic Form
                    </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-6">

                            <label class="form-label">
                                Form Name
                            </label>

                            <input
                                type="text"
                                name="form_name"
                                id="editFormName"
                                class="form-control"
                                required>

                        </div>


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

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

                            <input
                                type="text"
                                name="form_category"
                                id="editFormCategory"
                                class="form-control">

                        </div>


                        <div class="col-12">

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

                            <textarea
                                name="description"
                                id="editFormDescription"
                                class="form-control"
                                rows="4"></textarea>

                        </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">

                        <i class="bi bi-save me-1"></i>
                        Update Form

                    </button>

                </div>

            </form>

        </div>

    </div>

</div>

<style>
.dynamic-form-page {
    --df-border: #e8edf3;
    --df-muted: #6c7889;
    --df-surface: #ffffff;
}


/* HERO */

.form-hero {
    background:
        linear-gradient(
            135deg,
            rgba(13, 110, 253, 0.08),
            rgba(13, 110, 253, 0.01)
        );

    border: 1px solid var(--df-border);
    border-radius: 20px;
    padding: 28px 30px;
}

.hero-icon {
    width: 58px;
    height: 58px;
    border-radius: 16px;

    display: flex;
    align-items: center;
    justify-content: center;

    font-size: 26px;

    background: rgba(13, 110, 253, 0.12);
    color: var(--bs-primary);
}

.hero-eyebrow {
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 1.4px;
    color: var(--bs-primary);
    margin-bottom: 4px;
}

.create-form-btn {
    border-radius: 12px;
    box-shadow:
        0 8px 20px
        rgba(13, 110, 253, 0.18);
}


/* METRICS */

.metric-card {
    min-height: 105px;

    background: var(--df-surface);

    border: 1px solid var(--df-border);
    border-radius: 16px;

    padding: 20px;

    display: flex;
    align-items: center;
    gap: 16px;

    transition:
        transform 0.2s ease,
        box-shadow 0.2s ease;
}

.metric-card:hover {
    transform: translateY(-2px);

    box-shadow:
        0 10px 30px
        rgba(20, 35, 60, 0.08);
}

.metric-icon {
    width: 48px;
    height: 48px;

    border-radius: 14px;

    display: flex;
    align-items: center;
    justify-content: center;

    background: rgba(13, 110, 253, 0.08);
    color: var(--bs-primary);

    font-size: 21px;
}

.metric-label {
    font-size: 13px;
    color: var(--df-muted);
    margin-bottom: 2px;
}

.metric-value {
    font-size: 26px;
    line-height: 1;
    font-weight: 700;
}


/* WORKSPACE */

.forms-workspace-card {
    border: 1px solid var(--df-border);
    border-radius: 18px;
    overflow: hidden;

    box-shadow:
        0 8px 30px
        rgba(20, 35, 60, 0.05);
}

.workspace-header {
    background: #ffffff;
    border-bottom: 1px solid var(--df-border);
    padding: 20px 22px;
}


/* SEARCH */

.form-search-box {
    min-width: 260px;

    height: 42px;

    display: flex;
    align-items: center;
    gap: 10px;

    padding: 0 14px;

    border: 1px solid var(--df-border);
    border-radius: 12px;

    background: #f8fafc;
}

.form-search-box i {
    color: #8a96a6;
}

.form-search-box input {
    width: 100%;
    border: 0;
    outline: 0;
    background: transparent;
    font-size: 14px;
}


/* TABLE */

.forms-workspace-card .table {
    margin-bottom: 0;
}

.forms-workspace-card thead th {
    background: #f8fafc;

    color: #657184;

    font-size: 11px;
    font-weight: 700;

    letter-spacing: 0.5px;
    text-transform: uppercase;

    border-bottom:
        1px solid var(--df-border);

    padding: 14px 16px;
}

.forms-workspace-card tbody td {
    padding: 16px;
    border-color: #eef2f6;
    vertical-align: middle;
}

.forms-workspace-card tbody tr {
    transition: background 0.15s ease;
}

.forms-workspace-card tbody tr:hover {
    background: #fafcff;
}


/* ACTION BUTTONS */

.forms-workspace-card .btn-sm {
    width: 34px;
    height: 34px;

    display: inline-flex;
    align-items: center;
    justify-content: center;

    padding: 0;

    border-radius: 9px;
}


/* BADGES */

.forms-workspace-card .badge {
    padding: 7px 10px;
    border-radius: 999px;
    font-weight: 600;
}


/* MODALS */

.dynamic-form-page + .modal .modal-content,
.modal .modal-content {
    border: 0;
    border-radius: 18px;

    box-shadow:
        0 24px 70px
        rgba(20, 35, 60, 0.18);
}

.modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid #edf1f5;
}

.modal-body {
    padding: 24px;
}

.modal-footer {
    padding: 16px 24px;
    border-top: 1px solid #edf1f5;
}

.modal .form-control,
.modal .form-select {
    min-height: 44px;
    border-radius: 10px;
    border-color: #dfe5ec;
}

.modal textarea.form-control {
    min-height: auto;
}


.form-code{display:inline-flex;padding:6px 10px;border-radius:8px;background:#f1f5f9;font-family:monospace;font-size:12px;font-weight:700;color:#334155}.form-name{font-weight:700;color:#1e293b;margin-bottom:3px}.form-description{max-width:380px;font-size:12px;color:#8491a3;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.version-pill{display:inline-flex;padding:5px 9px;border-radius:7px;background:#f1f5f9;font-size:12px;font-weight:600}.status-pill{display:inline-flex;align-items:center;gap:5px;padding:6px 10px;border-radius:999px;font-size:12px;font-weight:600}.status-published{background:rgba(25,135,84,.10);color:#198754}.status-draft{background:rgba(255,193,7,.15);color:#946c00}.status-archived{background:#eef1f4;color:#667085}.action-group{display:inline-flex;align-items:center;justify-content:flex-end;gap:6px}.empty-state{max-width:440px;margin:0 auto;padding:25px}.empty-state-icon{width:64px;height:64px;margin:0 auto;border-radius:18px;display:flex;align-items:center;justify-content:center;background:rgba(13,110,253,.08);color:var(--bs-primary);font-size:28px}


.edit-form-action {
    width: auto !important;
    padding: 0 11px !important;
    gap: 6px;
}

.modal-dialog-scrollable .modal-content {
    max-height: calc(100vh - 2rem);
}

.modal-dialog-scrollable .modal-body {
    overflow-y: auto;
}

/* RESPONSIVE */

@media (max-width: 767.98px) {

    .form-hero {
        padding: 22px;
    }

    .form-search-box {
        width: 100%;
        min-width: 0;
    }

    .create-form-btn {
        width: 100%;
    }
}
</style>
<script>
document.addEventListener(
    'DOMContentLoaded',
    function () {

        const editButtons =
            document.querySelectorAll(
                '.edit-form-btn'
            );
const searchInput =
    document.getElementById(
        'formSearchInput'
    );

if (searchInput) {

    searchInput.addEventListener(
        'input',
        function () {

            const keyword =
                this.value
                    .toLowerCase()
                    .trim();

            const rows =
                document.querySelectorAll(
                    '.forms-workspace-card tbody .form-data-row'
                );

            rows.forEach(
                function (row) {

                    const content =
                        row.textContent
                            .toLowerCase();

                    row.style.display =
                        content.includes(keyword)
                            ? ''
                            : 'none';
                }
            );
        }
    );
}
        editButtons.forEach(
            function (button) {

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

                        document.getElementById(
                            'editFormId'
                        ).value =
                            this.dataset.id || '';

                        document.getElementById(
                            'editFormName'
                        ).value =
                            this.dataset.formName || '';

                        document.getElementById(
                            'editFormCategory'
                        ).value =
                            this.dataset.formCategory || '';

                        document.getElementById(
                            'editFormDescription'
                        ).value =
                            this.dataset.description || '';
                    }
                );

            }
        );

    }
);
</script>
<?php

$content = ob_get_clean();

$title = 'Dynamic Form Management';

include APP_PATH .
    '/Modules/Administration/Views/layouts/admin.php';