<?php

if (!class_exists('WP_List_Table')) {
    require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}

function view_race_user_list_initialisation()
{
    global $wpdb;
    //Delete element action
    if (isset($_GET["action"]) && $_GET["action"] == "delete" && isset($_GET["IDRace_user"]) && intval($_GET["IDRace_user"]) > 0) {
        $race_user = new Race_User;
        $race_user->setIDRace_User(intval($_GET["IDRace_user"]));
        $race_user->delete();
    }

    //Set deputy element action
    if (isset($_GET["action"]) && $_GET["action"] == "setDeputy" && isset($_GET["IDRace_user"]) && intval($_GET["IDRace_user"]) > 0) {
        Race_User::setDeputy(intval($_GET["IDRace_user"]));
    }

    //Validate element action
    if (isset($_GET["action"]) && $_GET["action"] == "validate" && isset($_GET["IDRace_user"]) && intval($_GET["IDRace_user"]) > 0) {
        $race_user = new Race_User;
        $race_user->loadFromId(intval($_GET["IDRace_user"]));
        $race_user->updateState(2);

        //Send Mail
        $race = new Race();
        $race->loadFromId($race_user->getIDRace());

        $member_info = get_userdata($race_user->getIDWPUser());
        $member_mail = $member_info->user_email;
        $member_first_name = $member_info->first_name;
        $member_last_name = $member_info->last_name;
        $member_no = $member_info->cassMemberNo;

        $rl_info = get_userdata($race->getIDWPUser_RL());
        $rl_mail = $rl_info->user_email;
        $rl_first_name = $rl_info->first_name;
        $rl_last_name = $rl_info->last_name;
        //Send mail
        $mailer = new Mailer("", $member_mail, ReadGlobal(Mailer::getTemplate("mailContentParticipiantValidationToMemberObject")), ReadGlobal(Mailer::getTemplate("mailContentParticipiantValidationToMember")), $member_first_name, $member_last_name, $member_no, ReadGlobal($race->getName()), "");
        $mailer->setMailMessage(SantizeGlobal($_GET["mailContent"]));
        $mailer->setMailObject(SantizeGlobal($_GET["mailSubject"]));
        $mailer->replaceParametterValue();
        $mailer->sendMail();
    }

    //Validate element action
    if (isset($_GET["action"]) && $_GET["action"] == "excuse" && isset($_GET["IDRace_user"]) && intval($_GET["IDRace_user"]) > 0) {
        $race_user = new Race_User;
        $race_user->loadFromId(intval($_GET["IDRace_user"]));
        $race_user->updateState(4);

        //Send Mail
        $race = new Race();
        $race->loadFromId(intval($race_user->getIDRace()));

        $member_info = get_userdata($race_user->getIDWPUser());
        $member_mail = $member_info->user_email;
        $member_first_name = $member_info->first_name;
        $member_last_name = $member_info->last_name;
        $member_no = $member_info->cassMemberNo;

        $rl_info = get_userdata($race->getIDWPUser_RL());
        $rl_mail = $rl_info->user_email;
        $rl_first_name = $rl_info->first_name;
        $rl_last_name = $rl_info->last_name;
        //Send mail
        $mailer = new Mailer("", $member_mail, ReadGlobal(Mailer::getTemplate("mailContentParticipiantExcusationToMemberObject")), ReadGlobal(Mailer::getTemplate("mailContentParticipiantExcusationToMember")), $member_first_name, $member_last_name, $member_no, ReadGlobal($race->getName()), "");
        $mailer->setMailMessage(SantizeGlobal($_GET["mailContent"]));
        $mailer->setMailObject(SantizeGlobal($_GET["mailSubject"]));
        $mailer->replaceParametterValue();
        $mailer->sendMail();
    }

    //Download model
    if (isset($_POST["downloadParticipant"]) && intval($_POST["downloadParticipant"]) == 1) {
        exportParticipantListOfRace(intval($_GET["IDRace"]));
    }

    //Download model
    if (isset($_POST["downloadParticipantMailCSV"]) && intval($_POST["downloadParticipantMailCSV"]) == 1) {
        $mails = exportParticipantListOfRaceMailOnly(intval($_GET["IDRace"]));

        // Convert emails to a string separated by semicolons
        $mails = implode(";", $mails);

        // Create the 'cass' folder inside the uploads directory
        $directoryCass = 'cass';
        $upload_dir = wp_upload_dir();
        $upload_path = $upload_dir['basedir'];
        $subdirectory_path = $upload_path . '/' . $directoryCass;
        if (!file_exists($subdirectory_path)) {
            wp_mkdir_p($subdirectory_path);
        }

        // Path for the CSV file
        $modelCSVExportFile = $subdirectory_path . "/" . "participants.csv";

        // Create and write the emails into the CSV file
        file_put_contents($modelCSVExportFile, $mails);

        // Generate the full URL for the file
        $url_complet = home_url() . '/wp-content/uploads/' . $directoryCass . '/participants.csv';

        // Open the file in a new browser tab
        echo "<script>window.open('$url_complet', '_blank');</script>";
    }


    if (isset($_POST["copyParticipantMail"]) && intval($_POST["copyParticipantMail"]) == 1) {
        $mails = exportParticipantListOfRaceMailOnly(intval($_GET["IDRace"]));

        // Convertir les mails en une chaîne séparée par des ";"
        $mails = implode(";", $mails);

        // Générer le script JavaScript pour afficher une modale
        echo "<script>
            // Création de la modale
            const modal = document.createElement('div');
            modal.style.position = 'fixed';
            modal.style.top = '50%';
            modal.style.left = '50%';
            modal.style.transform = 'translate(-50%, -50%)';
            modal.style.background = '#fff';
            modal.style.padding = '20px';
            modal.style.border = '1px solid #ccc';
            modal.style.boxShadow = '0px 4px 8px rgba(0, 0, 0, 0.2)';
            modal.style.zIndex = '1000';
            modal.style.width = '400px';
            modal.style.textAlign = 'center';
    
            // Contenu de la modale
            modal.innerHTML = `
                <h3>Liste des e-mails</h3>
                <textarea id='emailList' style='width: 100%; height: 100px; margin-bottom: 15px;'>" . $mails . "</textarea>
                <div>
                    <button id='copyButton' style='padding: 10px 15px; margin-right: 10px;'>Copier</button>
                    <button id='closeButton' style='padding: 10px 15px;'>Fermer</button>
                </div>
            `;
    
            // Ajout de la modale au document
            document.body.appendChild(modal);
    
            // Fonction pour copier dans le presse-papiers
            document.getElementById('copyButton').addEventListener('click', async () => {
                const text = document.getElementById('emailList').value;
                try {
                    await navigator.clipboard.writeText(text);
                    alert('La liste des e-mails a été copiée dans le presse-papiers.');
                } catch (err) {
                    alert('Erreur : Impossible de copier les e-mails.');
                }
            });
    
            // Fonction pour fermer la modale
            document.getElementById('closeButton').addEventListener('click', () => {
                modal.remove();
            });
        </script>";
    }





    $table = new CASS_View_Race_User_List();
    ?>

    <div id="app"></div>
    <div class="wrap">
        <?php
        $sql = "SELECT name FROM cass_race WHERE IDRace =" . $_GET["IDRace"] . ";";
        $result = $wpdb->get_row($sql);
        ?>
        <h2>Liste des participants de la course :
            <?php echo ReadGlobal($result->name); ?>
        </h2>

        <?php
        // Ajouter la boîte de recherche
        $table->search_box('Rechercher par nom', 'lastname');
        ?>


        <div style="display: flex; gap: 10px; align-items: center;">
            <form action='<?php echo admin_url() . "admin.php?page=cass-admin-race-user-edit"; ?>' method='POST'>
                <input type="hidden" id="stateForm" name="stateForm" value="create">
                <input type="hidden" id="IDRace" name="IDRace" value="<?php echo intval($_GET['IDRace']) ?>">
                <button type="submit" class="button-secondary" id="refresh-cache">Ajouter</button>
            </form>

            <form action='<?php echo admin_url() . "admin.php?page=cass-admin-race-list"; ?>' method='POST'>
                <button type="submit" class="button">Retour aux courses</button>
            </form>

            <form action='#' method='post'>
                <input type='hidden' id='downloadParticipant' name='downloadParticipant' value='1'>
                <button type='submit' class='button-secondary' id='refresh-cache'>Télécharger la liste des
                    participants</button>
            </form>

            <form action='#' method='post'>
                <input type='hidden' id='downloadParticipantMailCSV' name='downloadParticipantMailCSV' value='1'>
                <button type='submit' class='button-secondary' id='refresh-cache'>Télécharger les mails des participants
                    (CSV)</button>
            </form>
            <form action='#' method='post'>
                <input type='hidden' id='copyParticipantMail' name='copyParticipantMail' value='1'>
                <button type='submit' class='button-secondary' id='refresh-cache'>Copier les mails des participants</button>
            </form>
        </div>


        <button id='btnOpenModal' hidden
            class="modal-open bg-transparent border border-gray-500 hover:border-indigo-500 text-gray-500 hover:text-indigo-500 font-bold py-2 px-4 rounded-full">Validation
            d'un membre</button>
        <button id='btnModalClose' hidden
            class="modal-close bg-transparent border border-gray-500 hover:border-indigo-500 text-gray-500 hover:text-indigo-500 font-bold py-2 px-4 rounded-full">Validation
            d'un membre</button>
        <div class="cass-modal" id="myModal">
            <div class="cass-modal-overlay"></div>

            <div class="cass-modal-container">
                <div class="cass-modal-close" onclick="closeModal()">
                    <svg class="fill-current text-white" xmlns="http://www.w3.org/2000/svg" width="18" height="18"
                        viewBox="0 0 18 18">
                        <path
                            d="M14.53 4.53l-1.06-1.06L9 7.94 4.53 3.47 3.47 4.53 7.94 9l-4.47 4.47 1.06 1.06L9 10.06l4.47 4.47 1.06-1.06L10.06 9z">
                        </path>
                    </svg>
                    <span class="text-sm">(Esc)</span>
                </div>

                <div class="cass-modal-content py-4 text-left px-6">
                    <input type="hidden" id="IDRace_user" value=''>
                    <input type="hidden" id="modalType" value=''>

                    <div class="flex justify-between items-center pb-3">
                        <p id='modalTitle' class="text-2xl font-bold"></p>
                    </div>

                    <label for="mailSubject">Sujet du mail</label>
                    <input type="text" id="mailSubject" name="mailSubject" class="w-full">

                    <label for="mailContent">Contenu du mail</label>
                    <textarea id="mailContent" name="mailContent" rows="8" cols="50" class="w-full"></textarea>

                    <div class="cass-modal-footer flex justify-end pt-2">
                        <button onclick="ModalExecute()" class="cass-button">Envoyer</button>
                        <button class="cass-button" onclick="closeModal()">Annuler</button>
                    </div>
                </div>
            </div>
        </div>


        <script>
            var openmodal = document.querySelectorAll('.modal-open')
            for (var i = 0; i < openmodal.length; i++) {
                openmodal[i].addEventListener('click', function (event) {
                    event.preventDefault()
                    toggleModal()
                })
            }

            function closeModal() {
                var modal = document.querySelector('.cass-modal');
                if (modal) {
                    modal.style.opacity = 0;
                    modal.style.pointerEvents = 'none';
                }
            }

            document.onkeydown = function (evt) {
                evt = evt || window.event
                var isEscape = false
                if ("key" in evt) {
                    isEscape = (evt.key === "Escape" || evt.key === "Esc")
                } else {
                    isEscape = (evt.keyCode === 27)
                }
                if (isEscape && document.body.classList.contains('modal-active')) {
                    toggleModal()
                }
            };


            function toggleModal() {
                const body = document.querySelector('body')
                const modal = document.querySelector('.modal')
                modal.classList.toggle('opacity-0')
                modal.classList.toggle('pointer-events-none')
                body.classList.toggle('modal-active')
            }


        </script>







        <form method="post">
            <?php

            // Prepare table
            $table->prepare_items();
            // Display table
            $table->display();
            echo '</div></form>';


}


class CASS_View_Race_User_List extends WP_List_Table
{
    private $table_data;

    // Define table columns
    function get_columns()
    {
        $columns = array(
            'cb' => '<input type="checkbox" />',
            'lastname' => __('Nom', 'cass-race-user-lastname-content'),
            'firstname' => __('Prénom', 'cass-race-user-firstname-content'),
            'state' => __('Etat', 'cass-race-user-state-content'),
            'subscribed' => __('Inscrit (saison)', 'cass-race-subscribed-content'),
            'participated' => __('Participé (saison)', 'cass-race-participated-content'),
            'memberno' => __('N° de membre', 'cass-race-user-memberno-content'),
            'IDLevel' => __('Niveau', 'cass-race-user-level-content'),
            'user_email' => __('Mail', 'cass-race-user-mail-content'),
            'telephone' => __('N° de téléphone', 'cass-race-user-telephone-content'),
            'locality' => __('Localité', 'cass-race-user-mail-content'),
            'commentInscription' => __('Com. inscription', 'cass-race-user-commentInscription-content'),
            'commentUnscribe' => __('Com. désinscription', 'cass-race-user-commentUnscribe-content'),
        );
        return $columns;
    }


    function prepare_items()
    {
        // Récupérer le paramètre de recherche
        $search = isset($_POST['s']) ? sanitize_text_field($_POST['s']) : '';

        // Charger les données du tableau
        $this->table_data = $this->get_table_data($search);

        $columns = $this->get_columns();
        $hidden = array();
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = array($columns, $hidden, $sortable);

        usort($this->table_data, array(&$this, 'usort_reorder'));

        /* pagination */
        $per_page = 20;
        $current_page = $this->get_pagenum();
        $total_items = count($this->table_data);

        $this->table_data = array_slice($this->table_data, (($current_page - 1) * $per_page), $per_page);

        $this->set_pagination_args(
            array(
                'total_items' => $total_items, // Nombre total d'éléments
                'per_page' => $per_page, // Nombre d'éléments par page
                'total_pages' => ceil($total_items / $per_page), // Total des pages
            )
        );

        $this->items = $this->table_data;
    }

    // Get table data
    private function get_table_data($search = '')
    {
        global $wpdb;
        $race_user = new Race_User();
        $data = $race_user->sqlWPTableRaceUserPerRace(intval($_GET["IDRace"]));

        // Appliquer le filtre si une recherche est effectuée
        if (!empty($search)) {
            $filtered_data = [];

            // Charger tous les utilisateurs avec le rôle 'CASS_MEMBER'
            $args = array(
                'role' => 'CASS_MEMBER',
                'orderby' => 'user_nicename',
                'order' => 'ASC'
            );
            $users = get_users($args);

            // Préparer un tableau pour faire correspondre les IDs aux noms
            $user_map = [];
            foreach ($users as $user) {
                $user_map[$user->id] = $user->user_lastname; // Associe l'ID utilisateur au nom
            }

            // Parcourir les données et appliquer le filtre
            foreach ($data as $item) {
                // Vérifiez si l'ID dans 'lastname' correspond à un utilisateur
                if (isset($item['lastname']) && isset($user_map[$item['lastname']])) {
                    $lastname = $user_map[$item['lastname']]; // Obtenez le nom réel

                    // Ajoutez un journal pour le débogage
                    echo "<script>console.log('Debug Objects: " . $lastname . " " . $search . "' );</script>";

                    // Vérifiez si le nom contient le terme recherché
                    if (stripos($lastname, $search) !== false) {
                        $filtered_data[] = $item; // Ajoutez l'élément filtré
                    }
                }
            }

            $data = $filtered_data; // Remplacez $data par les résultats filtrés
        }


        return $data;
    }

    function column_default($item, $column_name)
    {
        switch ($column_name) {
            case 'state':
                switch ($item[$column_name]) {
                    case 1:
                        return "Inscrit";
                    case 2:
                        return "Validée";
                    case 3:
                        return "Désinscrit";
                    case 4:
                        return "Excusée";
                }
            case 'subscribed':
                return Race_User::countMemberOfCourseParticipation($item["IDRace"], $item["IDWPUser"]);

            case 'participated':
                return Race_User::countMemberOfCourseInscription($item["IDRace"], $item["IDWPUser"]);
            case 'lastname':
            case "firstname":
                $args = array(
                    'role' => 'CASS_MEMBER',
                    'orderby' => 'user_nicename',
                    'order' => 'ASC'
                );
                $users = get_users($args);
                $retuned = "";
                foreach ($users as $user) {
                    if ($item[$column_name] == $user->id) {
                        $retuned = $user->user_firstname;
                    }
                }
                return $retuned;

            case 'memberno':
                return get_metadata('user', intval($item["IDWPUser"]), "cassMemberNo", true);
            case 'IDLevel':
                $level = new Level();
                $level->loadFromId(get_metadata('user', $item["IDWPUser"], "cassLevel", true));
                return ReadGlobal($level->getName());
            case 'user_email':
                return get_userdata($item["IDWPUser"])->user_email;
            case 'telephone':
                return get_metadata('user', $item["IDWPUser"], "cassTelephone", true);
            case 'locality':
                return get_metadata('user', $item["IDWPUser"], "cassLocality", true);
            case 'commentInscription':
            case 'commentUnscribe':
            default:
                return $item[$column_name];
        }
    }

    function column_cb($item)
    {
        return sprintf(
            '<input type="checkbox" name="element[]" value="%s" />',
            $item['IDRace_user']
        );
    }
    protected function get_sortable_columns()
    {
        $sortable_columns = array(
            'lastname' => array('lastname', false),
            'firstname' => array('firstname', false),
            'state' => array('state', false),
            'subscribed' => array('subscribed', false),
            'participated' => array('participated', false),
            'IDLevel' => array('IDLevel', false),
            'memberno' => array('memberno', false),
            'user_email' => array('mail', false),
            'telephone' => array('telephone', false),
            'locality' => array('locality', false),
        );
        return $sortable_columns;
    }

    // Sorting function
    function usort_reorder($a, $b)
    {
        // If no sort, default to user_login
        $orderby = (!empty($_GET['orderby'])) ? $_GET['orderby'] : 'user_login';

        // If no order, default to asc
        $order = (!empty($_GET['order'])) ? $_GET['order'] : 'asc';

        // Determine sort order
        $result = strcmp($a[$orderby], $b[$orderby]);

        // Send final sort direction to usort
        return ($order === 'asc') ? $result : -$result;
    }

    // Adding action links to column
    function column_lastname($item)
    {

        $setting = Setting::getInstance();

        ?>
                <script>

                    var mailContentParticipiantValidationToMemberObject = "<?php echo str_replace(["\r", "\n"], ['\\r', '\\n'], ReadGlobal($setting->getMailContentParticipiantValidationToMemberObject())); ?>";
                    var mailContentParticipiantValidationToMember = "<?php echo str_replace(["\r", "\n"], ['\\r', '\\n'], ReadGlobal($setting->getMailContentParticipiantValidationToMember())); ?>";
                    var mailContentParticipiantExcusationToMemberObject = "<?php echo str_replace(["\r", "\n"], ['\\r', '\\n'], ReadGlobal($setting->getMailContentParticipiantExcusationToMemberObject())); ?>";
                    var mailContentParticipiantExcusationToMember = "<?php echo str_replace(["\r", "\n"], ['\\r', '\\n'], ReadGlobal($setting->getMailContentParticipiantExcusationToMember())); ?>";
                    var IDRace = "<?php echo $_GET['IDRace']; ?>";

                    // The function below will start the confirmation dialog
                    function DeleteRaceUserConfirmAction(IDRace_user) {
                        let confirmAction = confirm("Voulez supprimer le participant de la course ?");
                        if (confirmAction) {
                            var url = window.location.href;
                            url += "&action=delete&IDRace_user=" + IDRace_user;
                            location.href = url;
                        }
                    }

                    // Set deputy
                    function setDeputy(IDRace_user) {
                        let confirmAction = confirm("Voulez définir ce participant comme adjoint ?");
                        if (confirmAction) {
                            var url = window.location.href;
                            url += "&action=setDeputy&IDRace_user=" + IDRace_user;
                            location.href = url;
                        }
                    }

                    // The function below will start the confirmation dialog
                    function ValidateRaceUserConfirmAction(IDRace_user) {
                        document.getElementById("IDRace_user").value = IDRace_user;
                        document.getElementById("modalType").value = "validate";

                        var modal = document.querySelector('.cass-modal');
                        if (modal) {
                            modal.style.opacity = 1;
                            modal.style.pointerEvents = 'auto';
                        }
                        document.getElementById("modalTitle").innerHTML = "<h2 align='center'>Valider un membre</h2>";
                        document.getElementById("mailSubject").value = mailContentParticipiantValidationToMemberObject;
                        document.getElementById("mailContent").value = mailContentParticipiantValidationToMember;

                    }

                    function ModalExecute() {
                        var IDRace_user = encodeURIComponent(document.getElementById("IDRace_user").value);
                        var mailSubject = encodeURIComponent(document.getElementById("mailSubject").value);
                        var mailContent = encodeURIComponent(document.getElementById("mailContent").value);

                        var baseUrl = window.location.href.split('&')[0];

                        let action = '';

                        switch (document.getElementById("modalType").value) {
                            case "excusate":
                                action = "excuse";
                                break;
                            case "validate":
                                action = "validate";
                                break;

                        }

                        var url = baseUrl + "&action=" + action + "&IDRace_user=" + IDRace_user + "&mailSubject=" + mailSubject + "&mailContent=" + mailContent + "&IDRace=" + IDRace;

                        closeModal();

                        setTimeout(function () {
                            location.href = url;
                        }, 1000);
                    }

                    // The function below will start the confirmation dialog
                    function ExcuseRaceUserConfirmAction(IDRace_user) {
                        document.getElementById("IDRace_user").value = IDRace_user;
                        document.getElementById("modalType").value = "excusate";

                        var modal = document.querySelector('.cass-modal');
                        if (modal) {
                            modal.style.opacity = 1;
                            modal.style.pointerEvents = 'auto';
                        }

                        document.getElementById("modalTitle").innerHTML = "<h2 align='center'>Excuser un membre</h2>";
                        document.getElementById("mailSubject").value = mailContentParticipiantExcusationToMemberObject;
                        document.getElementById("mailContent").value = mailContentParticipiantExcusationToMember;
                    }
                </script>

                <?php

                $actions = array(

                    //Race_user
                    'edit' => sprintf('<a href="' . admin_url() . "admin.php?page=cass-admin-race-user-edit&action=edit&IDRace_user=" . $item['IDRace_user'] . "&IDRace=" . $_GET['IDRace'] . '">Modifier</a>', $_REQUEST['page'], 'edit', $item['IDRace_user']),
                    'delete' => sprintf('<a onclick="DeleteRaceUserConfirmAction(' . $item['IDRace_user'] . ')" href="#">' . __('Supprimer', 'cass-admin-race-user-edit') . '</a>', $_REQUEST['page'], 'delete', $item['IDRace_user']),
                    'validate' => sprintf('<a onclick="ValidateRaceUserConfirmAction(' . $item['IDRace_user'] . ')" href="#">' . __('Valider', 'cass-admin-race-user-edit') . '</a>', $_REQUEST['page'], 'validate', $item['IDRace_user']),
                    'excuse' => sprintf('<a onclick="ExcuseRaceUserConfirmAction(' . $item['IDRace_user'] . ')" href="#">' . __('Excuser', 'cass-admin-race-user-edit') . '</a>', $_REQUEST['page'], 'excuse', $item['IDRace_user']),
                    'allCourses' => sprintf('<a href="' . admin_url() . "admin.php?page=cass-admin-race-user-all-courses-list&element=" . $item['IDWPUser'] . '">Liste de ses courses</a>', $_REQUEST['page'], 'allCourses', $item['IDWPUser']),
                    'setDeputy' => sprintf('<a onclick="setDeputy(' . $item['IDRace_user'] . ')" href="#">' . __('Définir adjoint', 'cass-admin-race-user-edit') . '</a>', $_REQUEST['page'], 'setDeputy', $item['IDRace_user']),

                );


                $args = array(
                    'role' => 'CASS_MEMBER',
                    'orderby' => 'user_nicename',
                    'order' => 'ASC'
                );
                $users = get_users($args);
                $lastname = "";
                foreach ($users as $user) {
                    if ($item["lastname"] == $user->id) {
                        $lastname = $user->user_lastname;
                    }
                }

                return sprintf('%1$s %2$s', ReadGlobal($lastname), $this->row_actions($actions));
    }

    // Ajouter un formulaire de recherche au-dessus du tableau
    function search_box($text, $input_id)
    {


        $input_id = $input_id . '-search-input';

        echo '<form method="post">';
        echo '<p class="search-box">';
        echo '<label class="screen-reader-text" for="' . esc_attr($input_id) . '">' . $text . ':</label>';
        echo '<input type="search" id="' . esc_attr($input_id) . '" name="s" value="' . esc_attr($_REQUEST['s'] ?? '') . '" />';
        echo '<button type="submit" class="button">' . esc_attr($text) . '</button>';
        echo '</p>';
        echo '</form>';
    }
}