<?php
/**
 * Pure Chemical Admin
 * File: admin/form_fields.php
 *
 * Existing tables used:
 *   forms
 *   form_fields
 *
 * No new table required.
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';


/* =========================================================
   FORMS TABLE COMPATIBILITY
   Detect real column names so this page works with the
   existing forms schema without requiring a database change.
========================================================= */
$formTableColumns = [];
try {
    $formColumnStmt = $pdo->prepare("\n        SELECT COLUMN_NAME\n        FROM information_schema.columns\n        WHERE table_schema = DATABASE()\n          AND table_name = ?\n    ");
    $formColumnStmt->execute(['forms']);
    $formTableColumns = array_map('strval', $formColumnStmt->fetchAll(PDO::FETCH_COLUMN));
} catch (Throwable $e) {
    error_log('Form Fields Schema Detection Error: ' . $e->getMessage());
}

$formNameColumn = null;
foreach (['name', 'form_name', 'title', 'form_title', 'label'] as $candidateColumn) {
    if (in_array($candidateColumn, $formTableColumns, true)) {
        $formNameColumn = $candidateColumn;
        break;
    }
}
$formSlugColumn = in_array('slug', $formTableColumns, true) ? 'slug' : null;
$formStatusColumn = in_array('status', $formTableColumns, true) ? 'status' : null;
$formNameSelect = $formNameColumn !== null
    ? '`' . $formNameColumn . '`'
    : 'CAST(`id` AS CHAR)';
$formNameSelectWithAlias = $formNameColumn !== null
    ? 'f.`' . $formNameColumn . '`'
    : 'CAST(f.`id` AS CHAR)';
$formSlugSelectWithAlias = $formSlugColumn !== null
    ? 'f.`' . $formSlugColumn . '`'
    : "''";

if (file_exists(__DIR__ . '/includes/auth.php')) {
    require_once __DIR__ . '/includes/auth.php';
}

if (file_exists(__DIR__ . '/includes/functions.php')) {
    require_once __DIR__ . '/includes/functions.php';
}

if (file_exists(__DIR__ . '/includes/csrf.php')) {
    require_once __DIR__ . '/includes/csrf.php';
}

if (function_exists('requireAdmin')) {
    requireAdmin();
}


/* =========================================================
   HELPERS
========================================================= */

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
    }
}


/**
 * CSRF token fallback.
 */
if (!function_exists('formFieldsCsrfToken')) {
function formFieldsCsrfToken()
{
    if (function_exists('csrf_token')) {
        return csrf_token();
    }

    if (empty($_SESSION['form_fields_csrf_token'])) {
        $_SESSION['form_fields_csrf_token'] = bin2hex(random_bytes(32));
    }

    return $_SESSION['form_fields_csrf_token'];
}
}


/**
 * CSRF verification fallback.
 */
if (!function_exists('formFieldsVerifyCsrf')) {
function formFieldsVerifyCsrf($token)
{
    if (function_exists('csrf_verify')) {
        return csrf_verify($token);
    }

    return isset($_SESSION['form_fields_csrf_token'])
        && hash_equals(
            $_SESSION['form_fields_csrf_token'],
            (string) $token
        );
}
}


/**
 * Flash message.
 */
if (!function_exists('formFieldsFlash')) {
function formFieldsFlash($type, $message)
{
    $_SESSION['form_fields_flash'] = [
        'type' => $type,
        'message' => $message
    ];
}
}


/**
 * Get flash.
 */
if (!function_exists('formFieldsGetFlash')) {
function formFieldsGetFlash()
{
    if (empty($_SESSION['form_fields_flash'])) {
        return null;
    }

    $flash = $_SESSION['form_fields_flash'];

    unset($_SESSION['form_fields_flash']);

    return $flash;
}
}


/**
 * Check table.
 */
if (!function_exists('formFieldsTableExists')) {
function formFieldsTableExists(PDO $pdo, $table)
{
    try {

        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
            AND table_name = ?
        ");

        $stmt->execute([$table]);

        return (bool) $stmt->fetchColumn();

    } catch (Throwable $e) {

        return false;
    }
}
}


/**
 * Read ENUM values dynamically from database.
 */
if (!function_exists('formFieldsEnumOptions')) {
function formFieldsEnumOptions(
    PDO $pdo,
    $table,
    $column,
    array $fallback = []
) {
    try {

        $stmt = $pdo->prepare("
            SELECT COLUMN_TYPE
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
            AND table_name = ?
            AND column_name = ?
            LIMIT 1
        ");

        $stmt->execute([
            $table,
            $column
        ]);

        $type = $stmt->fetchColumn();

        if (!$type) {
            return $fallback;
        }

        if (
            preg_match(
                "/^enum\\((.*)\\)$/i",
                $type,
                $matches
            )
        ) {

            $inside = $matches[1];

            $values = str_getcsv(
                $inside,
                ',',
                "'",
                "\\"
            );

            $options = [];

            foreach ($values as $value) {

                $value = str_replace(
                    "''",
                    "'",
                    $value
                );

                if ($value !== '') {
                    $options[] = $value;
                }
            }

            if (!empty($options)) {
                return $options;
            }
        }

    } catch (Throwable $e) {
        // Use fallback.
    }

    return $fallback;
}
}


/**
 * Convert option text to clean lines.
 */
if (!function_exists('cleanFieldOptions')) {
function cleanFieldOptions($value)
{
    $value = str_replace(
        ["\r\n", "\r"],
        "\n",
        (string) $value
    );

    $lines = explode("\n", $value);

    $clean = [];

    foreach ($lines as $line) {

        $line = trim($line);

        if ($line !== '') {
            $clean[] = $line;
        }
    }

    return implode("\n", $clean);
}
}


/**
 * Normalize validation rules into valid JSON.
 * The database validation column enforces JSON validity, so plain
 * newline-separated rules must not be inserted directly.
 */
if (!function_exists('cleanValidationRules')) {
function cleanValidationRules($value)
{
    $value = trim((string) $value);

    if ($value === '') {
        return '';
    }

    // Keep existing valid JSON supplied by an older/editing record.
    $decoded = json_decode($value, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
        return json_encode(
            $decoded,
            JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
        );
    }

    $value = str_replace(["\r\n", "\r"], "\n", $value);
    $lines = explode("\n", $value);
    $clean = [];

    foreach ($lines as $line) {
        $line = trim($line);
        if ($line !== '') {
            $clean[] = $line;
        }
    }

    if (!$clean) {
        return '';
    }

    return json_encode(
        $clean,
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
    );
}
}

/** Convert stored JSON validation rules back to editable one-rule-per-line text. */
if (!function_exists('displayValidationRules')) {
function displayValidationRules($value)
{
    $value = (string) ($value ?? '');
    if ($value === '') {
        return '';
    }

    $decoded = json_decode($value, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
        $lines = [];
        foreach ($decoded as $key => $rule) {
            if (is_string($rule) || is_numeric($rule)) {
                $lines[] = (string) $rule;
            } elseif (is_bool($rule) && $rule) {
                $lines[] = (string) $key;
            } elseif (is_array($rule)) {
                $lines[] = (string) $key . ':' . implode(',', array_map('strval', $rule));
            }
        }
        return implode("\n", $lines);
    }

    // Legacy non-JSON values remain editable.
    return $value;
}
}


/* =========================================================
   ADMIN
========================================================= */

$adminName =
    $_SESSION['ADMIN_NAME']
    ?? $_SESSION['admin_name']
    ?? $_SESSION['name']
    ?? 'Administrator';

$adminEmail =
    $_SESSION['ADMIN_EMAIL']
    ?? $_SESSION['admin_email']
    ?? '';

$csrfToken = formFieldsCsrfToken();


/* =========================================================
   FIELD TYPES
========================================================= */

$fieldTypeFallback = [
    'text',
    'email',
    'tel',
    'number',
    'textarea'
];

$fieldTypes = formFieldsEnumOptions(
    $pdo,
    'form_fields',
    'field_type',
    $fieldTypeFallback
);


/* =========================================================
   ACTION HANDLER
========================================================= */

$action = $_POST['action'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $postedToken = $_POST['csrf_token'] ?? '';

    if (!formFieldsVerifyCsrf($postedToken)) {

        formFieldsFlash(
            'error',
            'Security verification failed. Please try again.'
        );

        header('Location: form_fields.php');
        exit;
    }


    /* =====================================================
       SAVE FIELD
    ===================================================== */

    if ($action === 'save') {

        $id = (int) ($_POST['id'] ?? 0);

        $formId = (int) ($_POST['form_id'] ?? 0);

        $fieldName = trim(
            $_POST['field_name'] ?? ''
        );

        $label = trim(
            $_POST['label'] ?? ''
        );

        $fieldType = trim(
            $_POST['field_type'] ?? ''
        );

        $placeholder = trim(
            $_POST['placeholder'] ?? ''
        );

        $options = cleanFieldOptions(
            $_POST['options'] ?? ''
        );

        $validation = cleanValidationRules(
            $_POST['validation'] ?? ''
        );

        $defaultValue = trim(
            $_POST['default_value'] ?? ''
        );

        $sortOrder = (int) (
            $_POST['sort_order'] ?? 0
        );

        $required = isset($_POST['required'])
            ? 1
            : 0;

        $status = isset($_POST['status'])
            ? 1
            : 0;


        if ($formId <= 0) {

            formFieldsFlash(
                'error',
                'Please select a valid form.'
            );

            header('Location: form_fields.php');
            exit;
        }

        if ($fieldName === '') {

            formFieldsFlash(
                'error',
                'Field name is required.'
            );

            header(
                'Location: form_fields.php?form_id=' .
                $formId .
                ($id > 0 ? '&edit=' . $id : '')
            );

            exit;
        }

        if ($label === '') {

            formFieldsFlash(
                'error',
                'Field label is required.'
            );

            header(
                'Location: form_fields.php?form_id=' .
                $formId .
                ($id > 0 ? '&edit=' . $id : '')
            );

            exit;
        }

        if (
            !preg_match(
                '/^[A-Za-z][A-Za-z0-9_-]*$/',
                $fieldName
            )
        ) {

            formFieldsFlash(
                'error',
                'Field name may contain only letters, numbers, underscore and hyphen, and must start with a letter.'
            );

            header(
                'Location: form_fields.php?form_id=' .
                $formId .
                ($id > 0 ? '&edit=' . $id : '')
            );

            exit;
        }

        if (!in_array($fieldType, $fieldTypes, true)) {

            formFieldsFlash(
                'error',
                'Invalid field type selected.'
            );

            header(
                'Location: form_fields.php?form_id=' .
                $formId .
                ($id > 0 ? '&edit=' . $id : '')
            );

            exit;
        }


        try {

            $stmt = $pdo->prepare("
                SELECT id, {$formNameSelect} AS name
                FROM forms
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([
                $formId
            ]);

            $form = $stmt->fetch();

            if (!$form) {

                formFieldsFlash(
                    'error',
                    'Selected form does not exist.'
                );

                header('Location: form_fields.php');
                exit;
            }

            if ($id > 0) {

                $stmt = $pdo->prepare("
                    SELECT id
                    FROM form_fields
                    WHERE form_id = ?
                    AND field_name = ?
                    AND id != ?
                    LIMIT 1
                ");

                $stmt->execute([
                    $formId,
                    $fieldName,
                    $id
                ]);

            } else {

                $stmt = $pdo->prepare("
                    SELECT id
                    FROM form_fields
                    WHERE form_id = ?
                    AND field_name = ?
                    LIMIT 1
                ");

                $stmt->execute([
                    $formId,
                    $fieldName
                ]);
            }

            if ($stmt->fetch()) {

                formFieldsFlash(
                    'error',
                    'This field name already exists in the selected form.'
                );

                header(
                    'Location: form_fields.php?form_id=' .
                    $formId .
                    ($id > 0 ? '&edit=' . $id : '')
                );

                exit;
            }

            if ($id > 0) {

                $stmt = $pdo->prepare("
                    SELECT id
                    FROM form_fields
                    WHERE id = ?
                    AND form_id = ?
                    LIMIT 1
                ");

                $stmt->execute([
                    $id,
                    $formId
                ]);

                if (!$stmt->fetch()) {

                    formFieldsFlash(
                        'error',
                        'Field not found for the selected form.'
                    );

                    header(
                        'Location: form_fields.php?form_id=' .
                        $formId
                    );

                    exit;
                }


                $stmt = $pdo->prepare("
                    UPDATE form_fields
                    SET
                        form_id = ?,
                        field_name = ?,
                        label = ?,
                        field_type = ?,
                        placeholder = ?,
                        options = ?,
                        validation = ?,
                        default_value = ?,
                        sort_order = ?,
                        required = ?,
                        status = ?
                    WHERE id = ?
                ");

                $stmt->execute([
                    $formId,
                    $fieldName,
                    $label,
                    $fieldType,
                    $placeholder !== ''
                        ? $placeholder
                        : null,
                    $options !== ''
                        ? $options
                        : null,
                    $validation !== ''
                        ? $validation
                        : null,
                    $defaultValue !== ''
                        ? $defaultValue
                        : null,
                    $sortOrder,
                    $required,
                    $status,
                    $id
                ]);

                formFieldsFlash(
                    'success',
                    'Form field updated successfully.'
                );

            } else {

                $stmt = $pdo->prepare("
                    INSERT INTO form_fields
                    (
                        form_id,
                        field_name,
                        label,
                        field_type,
                        placeholder,
                        options,
                        validation,
                        default_value,
                        sort_order,
                        required,
                        status
                    )
                    VALUES
                    (
                        ?,
                        ?,
                        ?,
                        ?,
                        ?,
                        ?,
                        ?,
                        ?,
                        ?,
                        ?,
                        ?
                    )
                ");

                $stmt->execute([
                    $formId,
                    $fieldName,
                    $label,
                    $fieldType,
                    $placeholder !== ''
                        ? $placeholder
                        : null,
                    $options !== ''
                        ? $options
                        : null,
                    $validation !== ''
                        ? $validation
                        : null,
                    $defaultValue !== ''
                        ? $defaultValue
                        : null,
                    $sortOrder,
                    $required,
                    $status
                ]);

                formFieldsFlash(
                    'success',
                    'New form field created successfully.'
                );
            }

        } catch (Throwable $e) {

            error_log(
                'Form Fields Save Error: ' .
                $e->getMessage()
            );

            formFieldsFlash(
                'error',
                'Unable to save the form field. Please try again.'
            );
        }

        header(
            'Location: form_fields.php?form_id=' .
            $formId
        );

        exit;
    }


    /* =====================================================
       DELETE FIELD
    ===================================================== */

    if ($action === 'delete') {

        $id = (int) ($_POST['id'] ?? 0);

        if ($id <= 0) {

            formFieldsFlash(
                'error',
                'Invalid field selected.'
            );

            header('Location: form_fields.php');
            exit;
        }

        try {

            $stmt = $pdo->prepare("
                SELECT
                    id,
                    form_id,
                    field_name,
                    label
                FROM form_fields
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([
                $id
            ]);

            $field = $stmt->fetch();

            if (!$field) {

                formFieldsFlash(
                    'error',
                    'Form field not found.'
                );

                header('Location: form_fields.php');
                exit;
            }


            $stmt = $pdo->prepare("
                DELETE FROM form_fields
                WHERE id = ?
            ");

            $stmt->execute([
                $id
            ]);

            formFieldsFlash(
                'success',
                'Field "' .
                $field['label'] .
                '" deleted successfully.'
            );

            header(
                'Location: form_fields.php?form_id=' .
                (int) $field['form_id']
            );

            exit;

        } catch (Throwable $e) {

            error_log(
                'Form Fields Delete Error: ' .
                $e->getMessage()
            );

            formFieldsFlash(
                'error',
                'Unable to delete this form field.'
            );

            header('Location: form_fields.php');
            exit;
        }
    }


    /* =====================================================
       TOGGLE STATUS
    ===================================================== */

    if ($action === 'toggle_status') {

        $id = (int) ($_POST['id'] ?? 0);

        if ($id <= 0) {

            formFieldsFlash(
                'error',
                'Invalid field selected.'
            );

            header('Location: form_fields.php');
            exit;
        }

        try {

            $stmt = $pdo->prepare("
                UPDATE form_fields
                SET status = IF(status = 1, 0, 1)
                WHERE id = ?
            ");

            $stmt->execute([
                $id
            ]);

            formFieldsFlash(
                'success',
                'Field status updated.'
            );

        } catch (Throwable $e) {

            error_log(
                'Form Fields Status Error: ' .
                $e->getMessage()
            );

            formFieldsFlash(
                'error',
                'Unable to update field status.'
            );
        }

        $redirectForm =
            (int) ($_POST['redirect_form_id'] ?? 0);

        header(
            'Location: form_fields.php' .
            (
                $redirectForm > 0
                    ? '?form_id=' . $redirectForm
                    : ''
            )
        );

        exit;
    }
}


/* =========================================================
   FLASH
========================================================= */

$flash = formFieldsGetFlash();


/* =========================================================
   FILTERS
========================================================= */

$selectedFormId = (int) (
    $_GET['form_id'] ?? 0
);

$search = trim(
    $_GET['search'] ?? ''
);

$statusFilter =
    $_GET['status'] ?? 'all';

$typeFilter =
    $_GET['type'] ?? 'all';

$page = max(
    1,
    (int) ($_GET['page'] ?? 1)
);

$perPage = 15;


/* =========================================================
   LOAD FORMS
========================================================= */

$forms = [];

try {

    $formSlugSelect = $formSlugColumn !== null ? '`' . $formSlugColumn . '`' : "''";
    $formStatusSelect = $formStatusColumn !== null ? '`' . $formStatusColumn . '`' : '1';
    $stmt = $pdo->query("
        SELECT
            id,
            {$formNameSelect} AS name,
            {$formSlugSelect} AS slug,
            {$formStatusSelect} AS status
        FROM forms
        ORDER BY
            name ASC,
            id ASC
    ");

    $forms = $stmt->fetchAll();

} catch (Throwable $e) {

    error_log('Form Fields Forms Load Error: ' . $e->getMessage());
    $forms = [];
}


/* =========================================================
   SELECTED FORM
========================================================= */

$selectedForm = null;

if ($selectedFormId > 0) {

    foreach ($forms as $form) {

        if ((int) $form['id'] === $selectedFormId) {

            $selectedForm = $form;

            break;
        }
    }
}


/* =========================================================
   EDIT FIELD
========================================================= */

$editId = (int) (
    $_GET['edit'] ?? 0
);

$editField = null;

if ($editId > 0) {

    try {

        $stmt = $pdo->prepare("
            SELECT
                id,
                form_id,
                field_name,
                label,
                field_type,
                placeholder,
                options,
                validation,
                default_value,
                sort_order,
                required,
                status,
                created_at
            FROM form_fields
            WHERE id = ?
            LIMIT 1
        ");

        $stmt->execute([
            $editId
        ]);

        $editField = $stmt->fetch();

        if (
            $editField &&
            $selectedFormId <= 0
        ) {
            $selectedFormId =
                (int) $editField['form_id'];

            foreach ($forms as $form) {

                if (
                    (int) $form['id'] ===
                    $selectedFormId
                ) {

                    $selectedForm = $form;

                    break;
                }
            }
        }

    } catch (Throwable $e) {

        $editField = null;
    }
}


/* =========================================================
   FILTER WHERE
========================================================= */

$where = [];

$params = [];


if ($selectedFormId > 0) {

    $where[] = "ff.form_id = ?";

    $params[] = $selectedFormId;
}


if ($search !== '') {

    $where[] = "
        (
            ff.field_name LIKE ?
            OR ff.label LIKE ?
            OR ff.placeholder LIKE ?
        )
    ";

    $searchLike = '%' . $search . '%';

    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
}


if ($statusFilter === 'active') {

    $where[] = "ff.status = 1";

} elseif ($statusFilter === 'inactive') {

    $where[] = "ff.status = 0";
}


if (
    $typeFilter !== 'all' &&
    in_array($typeFilter, $fieldTypes, true)
) {

    $where[] = "ff.field_type = ?";

    $params[] = $typeFilter;
}


$whereSql = '';

if (!empty($where)) {

    $whereSql =
        'WHERE ' .
        implode(
            ' AND ',
            $where
        );
}


/* =========================================================
   TOTAL
========================================================= */

$totalRows = 0;

try {

    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM form_fields ff
        {$whereSql}
    ");

    $stmt->execute($params);

    $totalRows =
        (int) $stmt->fetchColumn();

} catch (Throwable $e) {

    $totalRows = 0;
}

$totalPages = max(
    1,
    (int) ceil(
        $totalRows / $perPage
    )
);

if ($page > $totalPages) {

    $page = $totalPages;
}

$offset =
    ($page - 1) *
    $perPage;


/* =========================================================
   FETCH FIELDS
========================================================= */

$fieldRows = [];

try {

    $stmt = $pdo->prepare("
        SELECT
            ff.id,
            ff.form_id,
            ff.field_name,
            ff.label,
            ff.field_type,
            ff.placeholder,
            ff.options,
            ff.validation,
            ff.default_value,
            ff.sort_order,
            ff.required,
            ff.status,
            ff.created_at,

            {$formNameSelectWithAlias} AS form_name,
            {$formSlugSelectWithAlias} AS form_slug

        FROM form_fields ff

        INNER JOIN forms f
            ON f.id = ff.form_id

        {$whereSql}

        ORDER BY
            ff.form_id ASC,
            ff.sort_order ASC,
            ff.id ASC

        LIMIT {$perPage}
        OFFSET {$offset}
    ");

    $stmt->execute($params);

    $fieldRows =
        $stmt->fetchAll();

} catch (Throwable $e) {

    error_log(
        'Form Fields Fetch Error: ' .
        $e->getMessage()
    );

    $fieldRows = [];
}


/* =========================================================
   STATS
========================================================= */

$stats = [
    'total' => 0,
    'active' => 0,
    'inactive' => 0,
    'required' => 0
];

try {

    $statsWhere = [];

    $statsParams = [];

    if ($selectedFormId > 0) {

        $statsWhere[] =
            "form_id = ?";

        $statsParams[] =
            $selectedFormId;
    }

    $statsWhereSql = '';

    if (!empty($statsWhere)) {

        $statsWhereSql =
            'WHERE ' .
            implode(
                ' AND ',
                $statsWhere
            );
    }


    $stmt = $pdo->prepare("
        SELECT
            COUNT(*) AS total,
            SUM(status = 1) AS active,
            SUM(status = 0) AS inactive,
            SUM(required = 1) AS required_count
        FROM form_fields
        {$statsWhereSql}
    ");

    $stmt->execute(
        $statsParams
    );

    $statRow =
        $stmt->fetch();

    if ($statRow) {

        $stats['total'] =
            (int) ($statRow['total'] ?? 0);

        $stats['active'] =
            (int) ($statRow['active'] ?? 0);

        $stats['inactive'] =
            (int) ($statRow['inactive'] ?? 0);

        $stats['required'] =
            (int) ($statRow['required_count'] ?? 0);
    }

} catch (Throwable $e) {
    // Keep defaults.
}


/* =========================================================
   PAGINATION URL
========================================================= */

if (!function_exists('formFieldsPageUrl')) {
function formFieldsPageUrl($page)
{
    $query = $_GET;

    $query['page'] = $page;

    return 'form_fields.php?' .
        http_build_query($query);
}
}

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Form Fields | Pure Chemical Admin
    </title>

    <link
        rel="preconnect"
        href="https://fonts.googleapis.com"
    >

    <link
        rel="preconnect"
        href="https://fonts.gstatic.com"
        crossorigin
    >

    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
        rel="stylesheet"
    >

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >

    <style>

        :root {
            --primary: #176b52;
            --primary-dark: #0e4e3c;
            --primary-soft: #eaf7f1;

            --dark: #10231d;
            --muted: #71807a;

            --border: #e5ebe8;
            --bg: #f5f8f7;
            --white: #ffffff;

            --success: #14804a;
            --success-bg: #eaf8f0;

            --danger: #c53b3b;
            --danger-bg: #fff0f0;

            --warning: #b97800;
            --warning-bg: #fff8e8;

            --blue: #3867b3;
            --blue-bg: #eef4ff;

            --shadow:
                0 15px 45px rgba(16, 35, 29, .07);

            --radius: 18px;
        }

        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            margin: 0;
            font-family: "Inter", sans-serif;
            background: var(--bg);
            color: var(--dark);
        }

        a {
            color: inherit;
            text-decoration: none;
        }

        button,
        input,
        textarea,
        select {
            font: inherit;
        }


        /* =================================================
           MAIN
        ================================================= */

        .main {
            margin-left: 280px;
            min-height: 100vh;
        }


        /* =================================================
           TOPBAR
        ================================================= */

        .topbar {
            height: 78px;

            background: rgba(255,255,255,.95);

            backdrop-filter: blur(18px);

            border-bottom: 1px solid var(--border);

            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 0 32px;

            position: sticky;
            top: 0;
            z-index: 50;
        }

        .topbar-left {
            display: flex;
            align-items: center;
            gap: 14px;
        }

        .page-icon {
            width: 45px;
            height: 45px;

            border-radius: 13px;

            background: var(--primary-soft);
            color: var(--primary);

            display: flex;
            align-items: center;
            justify-content: center;

            font-size: 18px;
        }

        .page-title h1 {
            margin: 0;

            font-size: 19px;
            font-weight: 800;

            letter-spacing: -.3px;
        }

        .page-title p {
            margin: 4px 0 0;

            color: var(--muted);

            font-size: 11px;
        }

        .admin-profile {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .admin-avatar {
            width: 42px;
            height: 42px;

            border-radius: 50%;

            background:
                linear-gradient(
                    135deg,
                    var(--primary),
                    #29966f
                );

            color: white;

            display: flex;
            align-items: center;
            justify-content: center;

            font-size: 14px;
            font-weight: 800;
        }

        .admin-info strong {
            display: block;
            font-size: 13px;
        }

        .admin-info span {
            display: block;

            margin-top: 3px;

            color: var(--muted);

            font-size: 10px;
        }


        /* =================================================
           CONTENT
        ================================================= */

        .content {
            padding: 30px 32px 55px;
        }


        /* =================================================
           ALERT
        ================================================= */

        .alert {
            padding: 14px 17px;

            border-radius: 14px;

            margin-bottom: 22px;

            display: flex;
            align-items: center;
            gap: 10px;

            font-size: 13px;
            font-weight: 600;
        }

        .alert.success {
            background: var(--success-bg);
            color: var(--success);
            border: 1px solid #ccebd9;
        }

        .alert.error {
            background: var(--danger-bg);
            color: var(--danger);
            border: 1px solid #f1cccc;
        }


        /* =================================================
           HERO
        ================================================= */

        .hero {
            display: flex;
            align-items: flex-end;
            justify-content: space-between;

            gap: 20px;

            margin-bottom: 24px;
        }

        .hero h2 {
            margin: 0;

            font-size: 27px;
            font-weight: 800;

            letter-spacing: -.8px;
        }

        .hero p {
            margin: 7px 0 0;

            color: var(--muted);

            font-size: 13px;
        }

        .selected-form-badge {
            display: inline-flex;
            align-items: center;
            gap: 7px;

            margin-top: 11px;

            padding: 7px 10px;

            border-radius: 9px;

            background: var(--primary-soft);
            color: var(--primary);

            font-size: 11px;
            font-weight: 700;
        }


        /* =================================================
           BUTTONS
        ================================================= */

        .btn {
            min-height: 43px;

            border: 0;

            border-radius: 12px;

            padding: 0 17px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            gap: 8px;

            cursor: pointer;

            font-size: 12px;
            font-weight: 700;

            transition: .2s ease;
        }

        .btn-primary {
            background: var(--primary);
            color: white;

            box-shadow:
                0 8px 20px rgba(23,107,82,.2);
        }

        .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-1px);
        }

        .btn-light {
            background: white;
            color: var(--dark);

            border: 1px solid var(--border);
        }

        .btn-light:hover {
            border-color: #bfd0c8;
        }

        .btn-danger {
            background: var(--danger);
            color: white;
        }

        .btn-danger:hover {
            background: #aa2e2e;
        }


        /* =================================================
           STATS
        ================================================= */

        .stats {
            display: grid;

            grid-template-columns:
                repeat(4, minmax(0, 1fr));

            gap: 16px;

            margin-bottom: 24px;
        }

        .stat-card {
            position: relative;

            overflow: hidden;

            padding: 19px;

            background: white;

            border: 1px solid var(--border);

            border-radius: var(--radius);

            box-shadow: var(--shadow);
        }

        .stat-card::after {
            content: "";

            position: absolute;

            right: -28px;
            bottom: -28px;

            width: 72px;
            height: 72px;

            border-radius: 50%;

            background: var(--primary-soft);
        }

        .stat-icon {
            width: 42px;
            height: 42px;

            border-radius: 12px;

            display: flex;
            align-items: center;
            justify-content: center;

            background: var(--primary-soft);
            color: var(--primary);
        }

        .stat-number {
            margin-top: 14px;

            font-size: 26px;
            font-weight: 800;

            line-height: 1;
        }

        .stat-label {
            margin-top: 7px;

            color: var(--muted);

            font-size: 11px;
            font-weight: 600;
        }


        /* =================================================
           PANEL
        ================================================= */

        .panel {
            background: white;

            border: 1px solid var(--border);

            border-radius: var(--radius);

            box-shadow: var(--shadow);

            overflow: hidden;
        }


        /* =================================================
           TOOLBAR
        ================================================= */

        .toolbar {
            padding: 17px;

            border-bottom: 1px solid var(--border);

            display: flex;
            align-items: center;

            gap: 9px;
        }

        .filter-form {
            width: 100%;

            display: flex;
            align-items: center;

            gap: 9px;
        }

        .search-box {
            position: relative;

            flex: 1;

            max-width: 400px;
        }

        .search-box i {
            position: absolute;

            left: 14px;
            top: 50%;

            transform: translateY(-50%);

            color: #91a099;

            font-size: 12px;
        }

        .input {
            width: 100%;

            height: 43px;

            border: 1px solid var(--border);

            border-radius: 11px;

            background: #fbfcfc;

            outline: none;

            padding: 0 13px;

            color: var(--dark);

            font-size: 12px;

            transition: .2s ease;
        }

        .search-box .input {
            padding-left: 38px;
        }

        .input:focus {
            border-color: #91cbb7;

            background: white;

            box-shadow:
                0 0 0 4px rgba(23,107,82,.08);
        }

        select.input {
            cursor: pointer;
        }


        /* =================================================
           TABLE
        ================================================= */

        .table-wrap {
            width: 100%;
            overflow-x: auto;
        }

        table {
            width: 100%;

            min-width: 1100px;

            border-collapse: collapse;
        }

        th {
            padding: 13px 17px;

            text-align: left;

            background: #fbfcfc;

            border-bottom: 1px solid var(--border);

            color: #7a8983;

            font-size: 9px;

            text-transform: uppercase;

            letter-spacing: .8px;

            font-weight: 800;
        }

        td {
            padding: 16px 17px;

            border-bottom: 1px solid #edf1ef;

            vertical-align: middle;

            font-size: 12px;
        }

        tbody tr {
            transition: .18s ease;
        }

        tbody tr:hover {
            background: #fbfdfc;
        }

        tbody tr:last-child td {
            border-bottom: 0;
        }


        /* =================================================
           FIELD INFO
        ================================================= */

        .field-info {
            display: flex;
            align-items: center;
            gap: 11px;
        }

        .field-icon {
            width: 40px;
            height: 40px;

            flex: 0 0 40px;

            border-radius: 11px;

            background: var(--primary-soft);
            color: var(--primary);

            display: flex;
            align-items: center;
            justify-content: center;
        }

        .field-info strong {
            display: block;

            font-size: 12px;
        }

        .field-info span {
            display: block;

            margin-top: 4px;

            color: var(--muted);

            font-size: 10px;
        }

        .code-name {
            display: inline-block;

            padding: 5px 8px;

            border-radius: 7px;

            background: #f2f5f4;

            color: #5d6c66;

            font-family: monospace;

            font-size: 10px;
        }


        /* =================================================
           TYPE BADGE
        ================================================= */

        .type-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;

            padding: 6px 9px;

            border-radius: 8px;

            background: var(--blue-bg);
            color: var(--blue);

            font-size: 10px;
            font-weight: 800;

            text-transform: lowercase;
        }


        /* =================================================
           REQUIRED
        ================================================= */

        .required-badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;

            color: var(--danger);

            font-size: 10px;
            font-weight: 800;
        }

        .optional-badge {
            color: #89958f;

            font-size: 10px;
            font-weight: 700;
        }


        /* =================================================
           STATUS
        ================================================= */

        .badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;

            padding: 6px 9px;

            border-radius: 100px;

            font-size: 9px;
            font-weight: 800;
        }

        .badge::before {
            content: "";

            width: 5px;
            height: 5px;

            border-radius: 50%;
        }

        .badge.active {
            background: var(--success-bg);
            color: var(--success);
        }

        .badge.active::before {
            background: var(--success);
        }

        .badge.inactive {
            background: #f1f3f3;
            color: #7d8884;
        }

        .badge.inactive::before {
            background: #89938f;
        }


        /* =================================================
           ACTIONS
        ================================================= */

        .actions {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .icon-btn {
            width: 34px;
            height: 34px;

            border-radius: 9px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            border: 1px solid var(--border);

            background: white;

            color: #66746e;

            cursor: pointer;

            transition: .2s ease;
        }

        .icon-btn:hover {
            background: var(--primary-soft);
            border-color: #bdd0c8;
            color: var(--primary);
        }

        .icon-btn.delete:hover {
            background: var(--danger-bg);
            border-color: #f0cccc;
            color: var(--danger);
        }

        .icon-btn.status:hover {
            background: var(--warning-bg);
            border-color: #ecd8a8;
            color: var(--warning);
        }


        /* =================================================
           PAGINATION
        ================================================= */

        .pagination {
            padding: 16px 18px;

            border-top: 1px solid var(--border);

            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 15px;
        }

        .pagination-info {
            color: var(--muted);

            font-size: 11px;
        }

        .pagination-links {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .page-link {
            min-width: 34px;
            height: 34px;

            padding: 0 8px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            background: white;

            border: 1px solid var(--border);

            border-radius: 9px;

            color: #66736e;

            font-size: 10px;
            font-weight: 700;
        }

        .page-link:hover {
            color: var(--primary);
            border-color: #bfd0c8;
        }

        .page-link.active {
            background: var(--primary);
            color: white;
            border-color: var(--primary);
        }


        /* =================================================
           EMPTY
        ================================================= */

        .empty {
            padding: 70px 20px;

            text-align: center;
        }

        .empty-icon {
            width: 65px;
            height: 65px;

            margin: 0 auto 16px;

            border-radius: 18px;

            background: var(--primary-soft);
            color: var(--primary);

            display: flex;
            align-items: center;
            justify-content: center;

            font-size: 23px;
        }

        .empty h3 {
            margin: 0;

            font-size: 16px;
        }

        .empty p {
            margin: 7px 0 18px;

            color: var(--muted);

            font-size: 11px;
        }


        /* =================================================
           MODAL (FIXED FOR SIDEBAR OVERLAP)
        ================================================= */

        .modal {
            position: fixed;

            inset: 0;

            z-index: 99999;

            padding: 20px;
            padding-left: 300px; /* Sidebar over lap fix */

            display: none;

            align-items: center;
            justify-content: center;

            background: rgba(10,27,21,.58);

            backdrop-filter: blur(6px);
        }

        .modal.show {
            display: flex;
        }

        .modal-card {
            width: min(980px, calc(100vw - 340px));
            height: calc(100vh - 40px);
            height: calc(100dvh - 40px);
            max-height: none;
            display: flex;
            flex-direction: column;
            min-height: 0;
            overflow: hidden;

            background: white;

            border-radius: 22px;

            box-shadow:
                0 30px 90px rgba(0,0,0,.22);

            animation: modalIn .2s ease;
        }

        @keyframes modalIn {

            from {
                opacity: 0;
                transform:
                    translateY(15px)
                    scale(.98);
            }

            to {
                opacity: 1;
                transform:
                    translateY(0)
                    scale(1);
            }

        }

        .modal-card > form#fieldEditor {
            display: flex;
            flex: 1 1 auto;
            flex-direction: column;
            min-height: 0;
            overflow: hidden;
        }

        .modal-header {
            flex: 0 0 auto;
            padding: 20px 23px;

            border-bottom: 1px solid var(--border);

            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .modal-title {
            display: flex;
            align-items: center;
            gap: 11px;
        }

        .modal-title-icon {
            width: 42px;
            height: 42px;

            border-radius: 12px;

            background: var(--primary-soft);
            color: var(--primary);

            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-title h3 {
            margin: 0;

            font-size: 17px;
        }

        .modal-title p {
            margin: 4px 0 0;

            color: var(--muted);

            font-size: 10px;
        }

        .modal-close {
            width: 35px;
            height: 35px;

            border: 0;

            border-radius: 10px;

            background: #f3f5f4;

            color: #66736e;

            cursor: pointer;
        }

        .modal-body {
            padding: 23px;
            overflow-y: auto;
            overflow-x: hidden;
            overscroll-behavior: contain;
            -webkit-overflow-scrolling: touch;
            min-height: 0;
            flex: 1 1 auto;
            height: auto;
        }

        .form-grid {
            display: grid;

            grid-template-columns:
                1fr 1fr;

            gap: 17px;
        }

        .field {
            margin-bottom: 2px;
        }

        .field.full {
            grid-column: 1 / -1;
        }

        .field label {
            display: block;

            margin-bottom: 7px;

            color: #44534d;

            font-size: 10px;
            font-weight: 800;
        }

        .required {
            color: var(--danger);
        }

        textarea.input {
            height: auto;

            min-height: 95px;

            padding: 12px;

            resize: vertical;

            line-height: 1.6;
        }

        .help {
            margin-top: 6px;

            color: #89958f;

            font-size: 9px;

            line-height: 1.55;
        }

        .help strong {
            color: #68766f;
        }

        .toggle-row {
            min-height: 43px;

            padding: 0 12px;

            border: 1px solid var(--border);

            border-radius: 11px;

            background: #fbfcfc;

            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .toggle-text strong {
            display: block;

            font-size: 11px;
        }

        .toggle-text span {
            display: block;

            margin-top: 2px;

            color: var(--muted);

            font-size: 9px;
        }

        .switch {
            position: relative;

            width: 42px;
            height: 23px;
        }

        .switch input {
            width: 0;
            height: 0;
            opacity: 0;
        }

        .slider {
            position: absolute;

            inset: 0;

            background: #ccd5d1;

            border-radius: 50px;

            cursor: pointer;

            transition: .2s;
        }

        .slider::before {
            content: "";

            position: absolute;

            width: 17px;
            height: 17px;

            left: 3px;
            top: 3px;

            background: white;

            border-radius: 50%;

            box-shadow:
                0 2px 5px rgba(0,0,0,.12);

            transition: .2s;
        }

        .switch input:checked + .slider {
            background: var(--primary);
        }

        .switch input:checked + .slider::before {
            transform: translateX(19px);
        }

        .modal-footer {
            flex: 0 0 auto;
            padding: 17px 23px;

            border-top: 1px solid var(--border);

            display: flex;
            justify-content: flex-end;

            gap: 9px;
        }


        /* =================================================
           DELETE
        ================================================= */

        .delete-card {
            width: min(440px, 100%);

            padding: 28px;

            border-radius: 22px;

            background: white;

            text-align: center;
        }

        .delete-icon {
            width: 58px;
            height: 58px;

            margin: 0 auto 15px;

            border-radius: 17px;

            background: var(--danger-bg);
            color: var(--danger);

            display: flex;
            align-items: center;
            justify-content: center;

            font-size: 21px;
        }

        .delete-card h3 {
            margin: 0;

            font-size: 18px;
        }

        .delete-card p {
            margin: 9px 0 0;

            color: var(--muted);

            font-size: 11px;

            line-height: 1.6;
        }

        .delete-actions {
            margin-top: 22px;

            display: flex;
            justify-content: center;

            gap: 9px;
        }


        /* =================================================
           RESPONSIVE
        ================================================= */

        @media (max-width: 1200px) {

            .stats {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }

        }

        @media (max-width: 1050px) {

            .main {
                margin-left: 0;
            }

            .topbar {
                padding: 0 20px;
            }

            .content {
                padding: 25px 20px 45px;
            }

            .modal {
                padding-left: 20px;
            }

        }

        @media (max-width: 750px) {

            .content {
                padding: 20px 14px 35px;
            }

            .hero {
                flex-direction: column;
                align-items: flex-start;
            }

            .hero h2 {
                font-size: 23px;
            }

            .toolbar {
                padding: 13px;
            }

            .filter-form {
                flex-wrap: wrap;
            }

            .search-box {
                width: 100%;
                max-width: none;
                flex-basis: 100%;
            }

            .form-grid {
                grid-template-columns: 1fr;
            }

            .field.full {
                grid-column: auto;
            }

            .pagination {
                flex-direction: column;
            }

        }

        @media (max-width: 500px) {

            .stats {
                grid-template-columns: 1fr 1fr;
                gap: 9px;
            }

            .stat-card {
                padding: 14px;
            }

            .stat-number {
                font-size: 21px;
            }

            .page-title p,
            .admin-info {
                display: none;
            }

            .topbar {
                height: 70px;
            }

            .modal {
                padding: 10px;
                align-items: center;
            }

            .modal-card {
                height: calc(100vh - 20px);
                height: calc(100dvh - 20px);
                max-height: none;
                width: 100%;
            }

            .modal-body {
                padding: 18px;
            }

            .modal-header,
            .modal-footer {
                padding-left: 18px;
                padding-right: 18px;
            }

        }

    </style>

</head>


<body>


<?php
/*
|--------------------------------------------------------------------------
| EXISTING SIDEBAR
|--------------------------------------------------------------------------
|
| Sidebar intentionally included separately.
|
*/
require_once __DIR__ . '/sidebar.php';
?>


<div class="main">


    <!-- =====================================================
         TOPBAR
    ====================================================== -->

    <header class="topbar">

        <div class="topbar-left">

            <div class="page-icon">
                <i class="fa-solid fa-list-check"></i>
            </div>

            <div class="page-title">

                <h1>Form Fields</h1>

                <p>
                    Build and manage fields for website forms
                </p>

            </div>

        </div>


        <div class="admin-profile">

            <div class="admin-avatar">

                <?= e(
                    strtoupper(
                        substr(
                            trim($adminName),
                            0,
                            1
                        )
                    )
                ) ?>

            </div>

            <div class="admin-info">

                <strong>
                    <?= e($adminName) ?>
                </strong>

                <span>
                    <?= e(
                        $adminEmail
                        ?: 'Administrator'
                    ) ?>
                </span>

            </div>

        </div>

    </header>


    <!-- =====================================================
         CONTENT
    ====================================================== -->

    <main class="content">


        <?php if ($flash): ?>

            <div class="alert <?= e($flash['type']) ?>">

                <?php if ($flash['type'] === 'success'): ?>

                    <i class="fa-solid fa-circle-check"></i>

                <?php else: ?>

                    <i class="fa-solid fa-circle-exclamation"></i>

                <?php endif; ?>

                <span>
                    <?= e($flash['message']) ?>
                </span>

            </div>

        <?php endif; ?>


        <!-- =================================================
             HERO
        ================================================== -->

        <section class="hero">

            <div>

                <h2>
                    Form Fields
                </h2>

                <p>
                    Configure individual input fields for your website forms.
                </p>


                <?php if ($selectedForm): ?>

                    <div class="selected-form-badge">

                        <i class="fa-solid fa-file-lines"></i>

                        Managing:
                        <?= e($selectedForm['name']) ?>

                    </div>

                <?php endif; ?>

            </div>


            <button
                type="button"
                class="btn btn-primary"
                onclick="openFieldModal()"
            >

                <i class="fa-solid fa-plus"></i>

                Add Field

            </button>

        </section>


        <!-- =================================================
             STATS
        ================================================== -->

        <section class="stats">


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-list-check"></i>
                </div>

                <div class="stat-number">
                    <?= number_format($stats['total']) ?>
                </div>

                <div class="stat-label">
                    Total Fields
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-circle-check"></i>
                </div>

                <div class="stat-number">
                    <?= number_format($stats['active']) ?>
                </div>

                <div class="stat-label">
                    Active Fields
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-asterisk"></i>
                </div>

                <div class="stat-number">
                    <?= number_format($stats['required']) ?>
                </div>

                <div class="stat-label">
                    Required Fields
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-icon">
                    <i class="fa-solid fa-circle-pause"></i>
                </div>

                <div class="stat-number">
                    <?= number_format($stats['inactive']) ?>
                </div>

                <div class="stat-label">
                    Inactive Fields
                </div>

            </div>


        </section>


        <!-- =================================================
             PANEL
        ================================================== -->

        <section class="panel">


            <!-- =================================================
                 FILTER BAR
            ================================================== -->

            <div class="toolbar">

                <form
                    method="get"
                    action="form_fields.php"
                    class="filter-form"
                >


                    <!-- SEARCH -->

                    <div class="search-box">

                        <i class="fa-solid fa-magnifying-glass"></i>

                        <input
                            type="text"
                            name="search"
                            class="input"
                            placeholder="Search field name, label..."
                            value="<?= e($search) ?>"
                        >

                    </div>


                    <!-- FORM -->

                    <select
                        name="form_id"
                        class="input"
                        style="max-width:220px;"
                        onchange="this.form.submit()"
                    >

                        <option value="0">
                            All Forms
                        </option>

                        <?php foreach ($forms as $form): ?>

                            <option
                                value="<?= (int) $form['id'] ?>"
                                <?= (
                                    $selectedFormId ===
                                    (int) $form['id']
                                )
                                    ? 'selected'
                                    : ''
                                ?>
                            >

                                <?= e($form['name']) ?>

                            </option>

                        <?php endforeach; ?>

                    </select>


                    <!-- TYPE -->

                    <select
                        name="type"
                        class="input"
                        style="max-width:150px;"
                        onchange="this.form.submit()"
                    >

                        <option value="all">
                            All Types
                        </option>

                        <?php foreach ($fieldTypes as $type): ?>

                            <option
                                value="<?= e($type) ?>"
                                <?= (
                                    $typeFilter === $type
                                )
                                    ? 'selected'
                                    : ''
                                ?>
                            >

                                <?= e(ucwords(
                                    str_replace(
                                        '_',
                                        ' ',
                                        $type
                                    )
                                )) ?>

                            </option>

                        <?php endforeach; ?>

                    </select>


                    <!-- STATUS -->

                    <select
                        name="status"
                        class="input"
                        style="max-width:145px;"
                        onchange="this.form.submit()"
                    >

                        <option
                            value="all"
                            <?= $statusFilter === 'all'
                                ? 'selected'
                                : ''
                            ?>
                        >
                            All Status
                        </option>

                        <option
                            value="active"
                            <?= $statusFilter === 'active'
                                ? 'selected'
                                : ''
                            ?>
                        >
                            Active
                        </option>

                        <option
                            value="inactive"
                            <?= $statusFilter === 'inactive'
                                ? 'selected'
                                : ''
                            ?>
                        >
                            Inactive
                        </option>

                    </select>


                    <button
                        type="submit"
                        class="btn btn-primary"
                    >

                        <i class="fa-solid fa-filter"></i>

                        Filter

                    </button>


                    <?php
                    if (
                        $search !== '' ||
                        $selectedFormId > 0 ||
                        $statusFilter !== 'all' ||
                        $typeFilter !== 'all'
                    ):
                    ?>

                        <a
                            href="form_fields.php"
                            class="btn btn-light"
                        >

                            <i class="fa-solid fa-rotate-left"></i>

                            Reset

                        </a>

                    <?php endif; ?>


                </form>

            </div>


            <!-- =================================================
                 TABLE
            ================================================== -->

            <?php if (!empty($fieldRows)): ?>

                <div class="table-wrap">

                    <table>

                        <thead>

                            <tr>

                                <th>
                                    Field
                                </th>

                                <th>
                                    Form
                                </th>

                                <th>
                                    Type
                                </th>

                                <th>
                                    Required
                                </th>

                                <th>
                                    Order
                                </th>

                                <th>
                                    Status
                                </th>

                                <th>
                                    Created
                                </th>

                                <th>
                                    Actions
                                </th>

                            </tr>

                        </thead>


                        <tbody>

                        <?php foreach ($fieldRows as $row): ?>

                            <tr>


                                <!-- FIELD -->

                                <td>

                                    <div class="field-info">

                                        <div class="field-icon">

                                            <?php

                                            $fieldIcon = 'fa-i-cursor';

                                            switch ($row['field_type']) {

                                                case 'email':
                                                    $fieldIcon =
                                                        'fa-envelope';
                                                    break;

                                                case 'tel':
                                                    $fieldIcon =
                                                        'fa-phone';
                                                    break;

                                                case 'number':
                                                    $fieldIcon =
                                                        'fa-hashtag';
                                                    break;

                                                case 'textarea':
                                                    $fieldIcon =
                                                        'fa-align-left';
                                                    break;

                                                case 'select':
                                                    $fieldIcon =
                                                        'fa-list';
                                                    break;

                                                case 'radio':
                                                    $fieldIcon =
                                                        'fa-circle-dot';
                                                    break;

                                                case 'checkbox':
                                                    $fieldIcon =
                                                        'fa-square-check';
                                                    break;

                                                case 'date':
                                                    $fieldIcon =
                                                        'fa-calendar';
                                                    break;

                                                case 'file':
                                                    $fieldIcon =
                                                        'fa-paperclip';
                                                    break;

                                                default:
                                                    $fieldIcon =
                                                        'fa-i-cursor';
                                            }

                                            ?>

                                            <i
                                                class="fa-solid <?= e($fieldIcon) ?>"
                                            ></i>

                                        </div>


                                        <div>

                                            <strong>
                                                <?= e($row['label']) ?>
                                            </strong>

                                            <span>
                                                <span class="code-name">
                                                    <?= e($row['field_name']) ?>
                                                </span>
                                            </span>

                                        </div>

                                    </div>

                                </td>


                                <!-- FORM -->

                                <td>

                                    <div
                                        style="
                                            font-size:11px;
                                            font-weight:700;
                                            color:#53615b;
                                        "
                                    >

                                        <?= e(
                                            $row['form_name']
                                        ) ?>

                                    </div>

                                    <div
                                        style="
                                            margin-top:4px;
                                            color:#96a19d;
                                            font-size:9px;
                                        "
                                    >

                                        <?= e(
                                            $row['form_slug']
                                        ) ?>

                                    </div>

                                </td>


                                <!-- TYPE -->

                                <td>

                                    <span class="type-badge">

                                        <i
                                            class="fa-solid fa-code"
                                        ></i>

                                        <?= e(
                                            $row['field_type']
                                        ) ?>

                                    </span>

                                </td>


                                <!-- REQUIRED -->

                                <td>

                                    <?php if (
                                        (int) $row['required'] === 1
                                    ): ?>

                                        <span class="required-badge">

                                            <i class="fa-solid fa-asterisk"></i>

                                            Required

                                        </span>

                                    <?php else: ?>

                                        <span class="optional-badge">
                                            Optional
                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- SORT -->

                                <td>

                                    <span
                                        style="
                                            display:inline-flex;
                                            align-items:center;
                                            justify-content:center;
                                            min-width:30px;
                                            height:28px;
                                            padding:0 8px;
                                            border-radius:8px;
                                            background:#f3f6f5;
                                            color:#64716c;
                                            font-size:10px;
                                            font-weight:800;
                                        "
                                    >

                                        <?= (int) $row['sort_order'] ?>

                                    </span>

                                </td>


                                <!-- STATUS -->

                                <td>

                                    <?php if (
                                        (int) $row['status'] === 1
                                    ): ?>

                                        <span class="badge active">
                                            Active
                                        </span>

                                    <?php else: ?>

                                        <span class="badge inactive">
                                            Inactive
                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- CREATED -->

                                <td>

                                    <span
                                        style="
                                            color:#78847f;
                                            font-size:10px;
                                            white-space:nowrap;
                                        "
                                    >

                                        <?php

                                        echo !empty(
                                            $row['created_at']
                                        )
                                            ? e(
                                                date(
                                                    'd M Y',
                                                    strtotime(
                                                        $row['created_at']
                                                    )
                                                )
                                            )
                                            : '—';

                                        ?>

                                    </span>

                                </td>


                                <!-- ACTIONS -->

                                <td>

                                    <div class="actions">


                                        <!-- EDIT -->

                                        <a
                                            href="form_fields.php?form_id=<?= (int) $row['form_id'] ?>&edit=<?= (int) $row['id'] ?>"
                                            class="icon-btn"
                                            title="Edit Field"
                                        >

                                            <i
                                                class="fa-solid fa-pen"
                                            ></i>

                                        </a>


                                        <!-- STATUS -->

                                        <form
                                            method="post"
                                            style="display:inline;"
                                            onsubmit="return confirmStatusChange();"
                                        >

                                            <input
                                                type="hidden"
                                                name="csrf_token"
                                                value="<?= e($csrfToken) ?>"
                                            >

                                            <input
                                                type="hidden"
                                                name="action"
                                                value="toggle_status"
                                            >

                                            <input
                                                type="hidden"
                                                name="id"
                                                value="<?= (int) $row['id'] ?>"
                                            >

                                            <input
                                                type="hidden"
                                                name="redirect_form_id"
                                                value="<?= (int) $row['form_id'] ?>"
                                            >

                                            <button
                                                type="submit"
                                                class="icon-btn status"
                                                title="Toggle Status"
                                            >

                                                <?php if (
                                                    (int) $row['status'] === 1
                                                ): ?>

                                                    <i
                                                        class="fa-solid fa-toggle-on"
                                                    ></i>

                                                <?php else: ?>

                                                    <i
                                                        class="fa-solid fa-toggle-off"
                                                    ></i>

                                                <?php endif; ?>

                                            </button>

                                        </form>


                                        <!-- DELETE -->

                                        <button
                                            type="button"
                                            class="icon-btn delete"
                                            title="Delete Field"
                                            onclick="openDeleteModal(
                                                <?= (int) $row['id'] ?>,
                                                <?= htmlspecialchars(
                                                    json_encode(
                                                        $row['label'],
                                                        JSON_HEX_TAG |
                                                        JSON_HEX_APOS |
                                                        JSON_HEX_QUOT |
                                                        JSON_HEX_AMP
                                                    ),
                                                    ENT_QUOTES,
                                                    'UTF-8'
                                                ) ?>,
                                                <?= (int) $row['form_id'] ?>
                                            )"
                                        >

                                            <i
                                                class="fa-regular fa-trash-can"
                                            ></i>

                                        </button>


                                    </div>

                                </td>


                            </tr>

                        <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>


                <!-- =================================================
                     PAGINATION
                ================================================== -->

                <?php if ($totalPages > 1): ?>

                    <div class="pagination">

                        <div class="pagination-info">

                            Showing

                            <strong>
                                <?= $totalRows > 0
                                    ? $offset + 1
                                    : 0
                                ?>
                            </strong>

                            -

                            <strong>
                                <?= min(
                                    $offset + $perPage,
                                    $totalRows
                                ) ?>
                            </strong>

                            of

                            <strong>
                                <?= number_format(
                                    $totalRows
                                ) ?>
                            </strong>

                            fields

                        </div>


                        <div class="pagination-links">

                            <?php if ($page > 1): ?>

                                <a
                                    href="<?= e(
                                        formFieldsPageUrl(
                                            $page - 1
                                        )
                                    ) ?>"
                                    class="page-link"
                                >

                                    <i
                                        class="fa-solid fa-chevron-left"
                                    ></i>

                                </a>

                            <?php endif; ?>


                            <?php

                            $startPage =
                                max(
                                    1,
                                    $page - 2
                                );

                            $endPage =
                                min(
                                    $totalPages,
                                    $page + 2
                                );

                            for (
                                $p = $startPage;
                                $p <= $endPage;
                                $p++
                            ):
                            ?>

                                <a
                                    href="<?= e(
                                        formFieldsPageUrl(
                                            $p
                                        )
                                    ) ?>"
                                    class="page-link <?= $p === $page
                                        ? 'active'
                                        : ''
                                    ?>"
                                >

                                    <?= $p ?>

                                </a>

                            <?php endfor; ?>


                            <?php if (
                                $page < $totalPages
                            ): ?>

                                <a
                                    href="<?= e(
                                        formFieldsPageUrl(
                                            $page + 1
                                        )
                                    ) ?>"
                                    class="page-link"
                                >

                                    <i
                                        class="fa-solid fa-chevron-right"
                                    ></i>

                                </a>

                            <?php endif; ?>

                        </div>

                    </div>

                <?php endif; ?>


            <?php else: ?>


                <!-- EMPTY -->

                <div class="empty">

                    <div class="empty-icon">

                        <i
                            class="fa-solid fa-list-check"
                        ></i>

                    </div>


                    <?php if (
                        $search !== '' ||
                        $selectedFormId > 0 ||
                        $statusFilter !== 'all' ||
                        $typeFilter !== 'all'
                    ): ?>

                        <h3>
                            No form fields found
                        </h3>

                        <p>
                            Try changing your filters or create a new field.
                        </p>

                        <a
                            href="form_fields.php"
                            class="btn btn-light"
                        >

                            <i
                                class="fa-solid fa-rotate-left"
                            ></i>

                            Clear Filters

                        </a>

                    <?php else: ?>

                        <h3>
                            No form fields created yet
                        </h3>

                        <p>
                            Add fields to your website forms to start collecting data.
                        </p>

                        <button
                            type="button"
                            class="btn btn-primary"
                            onclick="openFieldModal()"
                        >

                            <i
                                class="fa-solid fa-plus"
                            ></i>

                            Add First Field

                        </button>

                    <?php endif; ?>

                </div>


            <?php endif; ?>


        </section>


    </main>


</div>


<!-- =========================================================
     ADD / EDIT FIELD MODAL
========================================================= -->

<div
    class="modal <?= $editField ? 'show' : '' ?>"
    id="fieldModal"
    onclick="closeFieldBackdrop(event)"
>

    <div class="modal-card">


        <div class="modal-header">

            <div class="modal-title">

                <div class="modal-title-icon">

                    <i
                        class="fa-solid fa-list-check"
                    ></i>

                </div>

                <div>

                    <h3 id="modalTitle">

                        <?= $editField
                            ? 'Edit Form Field'
                            : 'Add Form Field'
                        ?>

                    </h3>

                    <p>
                        Configure the field behaviour and display settings
                    </p>

                </div>

            </div>


            <button
                type="button"
                class="modal-close"
                onclick="closeFieldModal()"
            >

                <i
                    class="fa-solid fa-xmark"
                ></i>

            </button>

        </div>


        <form
            method="post"
            action="form_fields.php"
            id="fieldEditor"
        >

            <input
                type="hidden"
                name="csrf_token"
                value="<?= e($csrfToken) ?>"
            >

            <input
                type="hidden"
                name="action"
                value="save"
            >

            <input
                type="hidden"
                name="id"
                id="fieldId"
                value="<?= $editField
                    ? (int) $editField['id']
                    : 0
                ?>"
            >


            <div class="modal-body">


                <div class="form-grid">


                    <!-- FORM -->

                    <div class="field full">

                        <label for="form_id">

                            Form

                            <span class="required">
                                *
                            </span>

                        </label>


                        <select
                            name="form_id"
                            id="form_id"
                            class="input"
                            required
                        >

                            <option value="">
                                Select Form
                            </option>

                            <?php foreach (
                                $forms as $form
                            ): ?>

                                <option
                                    value="<?= (int) $form['id'] ?>"
                                    <?= (
                                        (
                                            $editField
                                                ? (int) $editField['form_id']
                                                : $selectedFormId
                                        )
                                        ===
                                        (int) $form['id']
                                    )
                                        ? 'selected'
                                        : ''
                                    ?>
                                >

                                    <?= e(
                                        $form['name']
                                    ) ?>

                                    <?php if (
                                        (int) $form['status'] !== 1
                                    ): ?>

                                        — Inactive

                                    <?php endif; ?>

                                </option>

                            <?php endforeach; ?>

                        </select>

                        <div class="help">
                            Select the website form where this field will appear.
                        </div>

                    </div>


                    <!-- FIELD NAME -->

                    <div class="field">

                        <label for="field_name">

                            Field Name

                            <span class="required">
                                *
                            </span>

                        </label>


                        <input
                            type="text"
                            name="field_name"
                            id="field_name"
                            class="input"
                            maxlength="150"
                            placeholder="customer_name"
                            required
                            value="<?= e(
                                $editField['field_name']
                                ?? ''
                            ) ?>"
                        >

                        <div class="help">
                            Use a developer-friendly unique name.
                            Example:
                            <strong>customer_name</strong>
                        </div>

                    </div>


                    <!-- LABEL -->

                    <div class="field">

                        <label for="label">

                            Field Label

                            <span class="required">
                                *
                            </span>

                        </label>


                        <input
                            type="text"
                            name="label"
                            id="label"
                            class="input"
                            maxlength="255"
                            placeholder="Your Name"
                            required
                            value="<?= e(
                                $editField['label']
                                ?? ''
                            ) ?>"
                        >

                        <div class="help">
                            Human-readable label shown to website visitors.
                        </div>

                    </div>


                    <!-- TYPE -->

                    <div class="field">

                        <label for="field_type">

                            Field Type

                            <span class="required">
                                *
                            </span>

                        </label>


                        <select
                            name="field_type"
                            id="field_type"
                            class="input"
                            required
                        >

                            <?php foreach (
                                $fieldTypes as $type
                            ): ?>

                                <option
                                    value="<?= e($type) ?>"
                                    <?= (
                                        (
                                            $editField['field_type']
                                            ?? 'text'
                                        ) === $type
                                    )
                                        ? 'selected'
                                        : ''
                                    ?>
                                >

                                    <?= e(
                                        ucwords(
                                            str_replace(
                                                '_',
                                                ' ',
                                                $type
                                            )
                                        )
                                    ) ?>

                                </option>

                            <?php endforeach; ?>

                        </select>

                        <div class="help">
                            The available types are read directly from your database ENUM.
                        </div>

                    </div>


                    <!-- PLACEHOLDER -->

                    <div class="field">

                        <label for="placeholder">

                            Placeholder

                        </label>


                        <input
                            type="text"
                            name="placeholder"
                            id="placeholder"
                            class="input"
                            maxlength="255"
                            placeholder="Enter your name"
                            value="<?= e(
                                $editField['placeholder']
                                ?? ''
                            ) ?>"
                        >

                    </div>


                    <!-- OPTIONS -->

                    <div
                        class="field full"
                        id="optionsField"
                    >

                        <label for="options">

                            Options

                        </label>


                        <textarea
                            name="options"
                            id="options"
                            class="input"
                            placeholder="India&#10;USA&#10;United Kingdom&#10;Germany"
                        ><?= e(
                            $editField['options']
                            ?? ''
                        ) ?></textarea>


                        <div class="help" id="optionsHelp">

                            Use for select/radio/checkbox-type fields.
                            <strong>One option per line.</strong>
                            No JSON required.

                        </div>

                    </div>


                    <!-- VALIDATION -->

                    <div class="field full">

                        <label for="validation">

                            Validation Rules

                        </label>


                        <textarea
                            name="validation"
                            id="validation"
                            class="input"
                            placeholder="required&#10;min:3&#10;max:100"
                        ><?= e(
                            displayValidationRules(
                                $editField['validation'] ?? ''
                            )
                        ) ?></textarea>


                        <div class="help">

                            Store your validation rules as normal text,
                            one rule per line.
                            Example:
                            <strong>required</strong>,
                            <strong>min:3</strong>,
                            <strong>max:100</strong>.

                        </div>

                    </div>


                    <!-- DEFAULT -->

                    <div class="field">

                        <label for="default_value">

                            Default Value

                        </label>


                        <input
                            type="text"
                            name="default_value"
                            id="default_value"
                            class="input"
                            placeholder="Optional default value"
                            value="<?= e(
                                $editField['default_value']
                                ?? ''
                            ) ?>"
                        >

                    </div>


                    <!-- SORT -->

                    <div class="field">

                        <label for="sort_order">

                            Sort Order

                        </label>


                        <input
                            type="number"
                            name="sort_order"
                            id="sort_order"
                            class="input"
                            min="0"
                            step="1"
                            value="<?= e(
                                $editField['sort_order']
                                ?? 0
                            ) ?>"
                        >

                        <div class="help">
                            Lower number appears earlier in the form.
                        </div>

                    </div>


                    <!-- REQUIRED -->

                    <div class="field">

                        <label>
                            Required Field
                        </label>


                        <div class="toggle-row">

                            <div class="toggle-text">

                                <strong>
                                    Required
                                </strong>

                                <span>
                                    Visitor must provide a value
                                </span>

                            </div>


                            <label class="switch">

                                <input
                                    type="checkbox"
                                    name="required"
                                    value="1"
                                    <?= (
                                        $editField &&
                                        (int) $editField['required'] === 1
                                    )
                                        ? 'checked'
                                        : ''
                                    ?>
                                >

                                <span class="slider"></span>

                            </label>

                        </div>

                    </div>


                    <!-- STATUS -->

                    <div class="field">

                        <label>
                            Field Status
                        </label>


                        <div class="toggle-row">

                            <div class="toggle-text">

                                <strong>
                                    Enable Field
                                </strong>

                                <span>
                                    Show this field on the form
                                </span>

                            </div>


                            <label class="switch">

                                <input
                                    type="checkbox"
                                    name="status"
                                    value="1"
                                    <?= (
                                        !$editField ||
                                        (int) $editField['status'] === 1
                                    )
                                        ? 'checked'
                                        : ''
                                    ?>
                                >

                                <span class="slider"></span>

                            </label>

                        </div>

                    </div>


                </div>


            </div>


            <div class="modal-footer">

                <button
                    type="button"
                    class="btn btn-light"
                    onclick="closeFieldModal()"
                >

                    Cancel

                </button>


                <button
                    type="submit"
                    class="btn btn-primary"
                >

                    <i
                        class="fa-solid fa-check"
                    ></i>

                    <?= $editField
                        ? 'Update Field'
                        : 'Create Field'
                    ?>

                </button>

            </div>


        </form>


    </div>

</div>


<!-- =========================================================
     DELETE MODAL
========================================================= -->

<div
    class="modal"
    id="deleteModal"
    onclick="closeDeleteBackdrop(event)"
>

    <div class="delete-card">


        <div class="delete-icon">

            <i
                class="fa-regular fa-trash-can"
            ></i>

        </div>


        <h3>
            Delete Form Field?
        </h3>


        <p>

            Are you sure you want to delete

            <strong id="deleteFieldName"></strong>?

            This action cannot be undone.

        </p>


        <form
            method="post"
            action="form_fields.php"
        >

            <input
                type="hidden"
                name="csrf_token"
                value="<?= e($csrfToken) ?>"
            >

            <input
                type="hidden"
                name="action"
                value="delete"
            >

            <input
                type="hidden"
                name="id"
                id="deleteFieldId"
                value=""
            >


            <div class="delete-actions">

                <button
                    type="button"
                    class="btn btn-light"
                    onclick="closeDeleteModal()"
                >

                    Cancel

                </button>


                <button
                    type="submit"
                    class="btn btn-danger"
                >

                    <i
                        class="fa-regular fa-trash-can"
                    ></i>

                    Delete Field

                </button>

            </div>


        </form>


    </div>

</div>


<script>


    /* =====================================================
       OPEN FIELD MODAL
    ====================================================== */

    function openFieldModal() {

        const modal =
            document.getElementById('fieldModal');

        if (!modal) {
            return;
        }

        modal.classList.add('show');

        document.body.style.overflow = 'hidden';


        setTimeout(function () {

            const fieldName =
                document.getElementById(
                    'field_name'
                );

            if (fieldName) {
                fieldName.focus();
            }

        }, 100);

    }


    /* =====================================================
       CLOSE FIELD MODAL
    ====================================================== */

    function closeFieldModal() {

        const modal =
            document.getElementById(
                'fieldModal'
            );

        if (!modal) {
            return;
        }

        modal.classList.remove('show');

        document.body.style.overflow = '';


        const urlParams =
            new URLSearchParams(
                window.location.search
            );


        if (urlParams.has('edit')) {

            const cleanUrl =
                window.location.pathname +
                (
                    urlParams.has('form_id')
                        ? '?form_id=' +
                          encodeURIComponent(
                              urlParams.get(
                                  'form_id'
                              )
                          )
                        : ''
                );

            window.history.replaceState(
                {},
                document.title,
                cleanUrl
            );


            const form =
                document.getElementById(
                    'fieldEditor'
                );

            if (form) {

                form.reset();

                document.getElementById(
                    'fieldId'
                ).value = '0';

            }

        }

    }


    /* =====================================================
       BACKDROP
    ====================================================== */

    function closeFieldBackdrop(event) {

        if (
            event.target ===
            document.getElementById(
                'fieldModal'
            )
        ) {

            closeFieldModal();

        }

    }


    /* =====================================================
       DELETE
    ====================================================== */

    function openDeleteModal(
        id,
        name,
        formId
    ) {

        const modal =
            document.getElementById(
                'deleteModal'
            );

        const idInput =
            document.getElementById(
                'deleteFieldId'
            );

        const nameElement =
            document.getElementById(
                'deleteFieldName'
            );

        if (
            !modal ||
            !idInput ||
            !nameElement
        ) {
            return;
        }


        idInput.value = id;

        nameElement.textContent =
            name;

        modal.classList.add('show');

        document.body.style.overflow =
            'hidden';

    }


    function closeDeleteModal() {

        const modal =
            document.getElementById(
                'deleteModal'
            );

        if (!modal) {
            return;
        }

        modal.classList.remove(
            'show'
        );

        document.body.style.overflow =
            '';

    }


    function closeDeleteBackdrop(event) {

        if (
            event.target ===
            document.getElementById(
                'deleteModal'
            )
        ) {

            closeDeleteModal();

        }

    }


    /* =====================================================
       STATUS CONFIRM
    ====================================================== */

    function confirmStatusChange() {

        return confirm(
            'Are you sure you want to change this field status?'
        );

    }


    /* =====================================================
       FIELD NAME NORMALIZATION
    ====================================================== */

    const fieldNameInput =
        document.getElementById(
            'field_name'
        );


    if (fieldNameInput) {

        fieldNameInput.addEventListener(
            'input',
            function () {

                let value =
                    this.value;

                value =
                    value.replace(
                        /[^A-Za-z0-9_-]/g,
                        '_'
                    );

                if (
                    value.length > 0 &&
                    !/^[A-Za-z]/.test(value)
                ) {

                    value =
                        'field_' +
                        value;

                }

                this.value =
                    value;

            }
        );

    }


    /* =====================================================
       FIELD TYPE UI
    ====================================================== */

    const fieldType =
        document.getElementById(
            'field_type'
        );

    const optionsField =
        document.getElementById(
            'optionsField'
        );


    function updateOptionsVisibility() {

        if (
            !fieldType ||
            !optionsField
        ) {
            return;
        }


        const selected =
            fieldType.value.toLowerCase();


        const optionTypes = [
            'select',
            'radio',
            'checkbox',
            'multi_select'
        ];


        const needsOptions = optionTypes.includes(selected);
        optionsField.style.display = needsOptions ? '' : 'none';

        const optionsInput = document.getElementById('options');
        if (optionsInput) {
            optionsInput.required = false;
            optionsInput.setAttribute(
                'aria-describedby',
                needsOptions ? 'optionsHelp' : ''
            );
        }

    }


    if (fieldType) {

        fieldType.addEventListener(
            'change',
            updateOptionsVisibility
        );

        updateOptionsVisibility();

    }


    /* =====================================================
       ESC
    ====================================================== */

    document.addEventListener(
        'keydown',
        function (event) {

            if (
                event.key === 'Escape'
            ) {

                closeFieldModal();

                closeDeleteModal();

            }

        }
    );


    /* =====================================================
       PAGE SHOW
    ====================================================== */

    window.addEventListener(
        'pageshow',
        function () {

            const fieldModal =
                document.getElementById(
                    'fieldModal'
                );

            const deleteModal =
                document.getElementById(
                    'deleteModal'
                );


            if (
                (
                    !fieldModal ||
                    !fieldModal.classList.contains(
                        'show'
                    )
                )
                &&
                (
                    !deleteModal ||
                    !deleteModal.classList.contains(
                        'show'
                    )
                )
            ) {

                document.body.style.overflow =
                    '';

            }

        }
    );


</script>


</body>

</html>