<?php

// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: nedap_hooks.class.php,v 1.1.4.5 2026/04/04 13:55:23 qvarin Exp $

if (stristr($_SERVER['REQUEST_URI'], ".class.php")) {
    die("no access");
}

global $base_path, $class_path;
require_once $class_path . '/event/hook.class.php';
require_once $base_path . '/plugins/nedap/classes/nedap.class.php';

class nedap_hooks extends hook implements hook_interface
{
    public static function get_subcriptions()
    {
        return [
            'dashboard' => [
                'show' => [
                    ['nedap_hooks', 'display_stations'],
                ],
            ],
            'init' => [
                'finished' => [
                    ['nedap_hooks', 'set_parameters'],
                ],
            ],
        ];
    }

    private static function isActive(): bool
    {
    	global $pmb_rfid_driver, $param_rfid_activate, $pmb_rfid_activate;
    	return $pmb_rfid_driver === 'nedap_v3' && $param_rfid_activate  && $pmb_rfid_activate;
    }

    public static function set_parameters()
    {
        if (!self::isActive()) {
            return;
        }

        global $pmb_rfid_serveur_url;
        [$websocket, $token, $rcr] = explode(',', $pmb_rfid_serveur_url);

        // On modifie le paramètre
        $pmb_rfid_serveur_url = implode(',', [
            $websocket,
            $token,
            $rcr,
            $_SESSION['pmb_rfid_nedap_station'] ?? 'DEFAULT',
        ]);


        // On redefinie le template
        global $rfid_js_header;
        $rfid_js_header = "";
        get_rfid_js_header();
    }

    public static function display_stations(event_dashboard $event)
    {
        if (!self::isActive()) {
            return;
        }

        $nedap = new Nedap();
        if (empty($nedap->getConfig())) {
            $errorMessage = \plugins::get_message("nedap", "error_config_station");
            $content = <<<HTML
                <div id="nedap"><p class="erreur">{$errorMessage}</p></div>
                HTML;
        } else {
            global $msg, $deflt2docs_location;

            $configOptions = $nedap->generateConfigOptions($deflt2docs_location ?? 0, $_SESSION['pmb_rfid_nedap_station'] ?? '');
            $titleMessage = \plugins::get_message("nedap", "alert_title");
            $descMessage = \plugins::get_message("nedap", "alert_desc");
            $labelMessage = \plugins::get_message("nedap", "alert_label_station");

            $content = <<<HTML
                <div id="nedap">
                    <form class="form-{$event->get_module()}" action="#" method="post" style="min-width: 500px;" onsubmit="return saveStation(event)">
                        <h3>{$titleMessage}</h3>
                        <span>{$descMessage}</span>
                        <div class="form-contenu">
                            <div class="row">
                                <div class="colonne2">
                                    <label for="rfid_nedap_station" class="etiquette">{$labelMessage}</label>
                                </div>
                                <div class="colonne2">
                                    <select name="station" class="saisie-20em" id="rfid_nedap_station" require>
                                        {$configOptions}
                                    </select>
                                    <input type="button" class="bouton" value="{$msg['raz']}" onclick="razSation(event)">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="left">
                                <input type="submit" class="bouton" value="{$msg['77']}">
                            </div>
                        </div>
                    </form>

                    <script>
                        function nedap_notification(type, msg) {
                            require(["dojo/topic"], function(topic) {
                                topic.publish("dGrowl", msg, { sticky: false, duration: 5000, channel: type });
                            });
                        }

                        function razSation(event) {
                            event.preventDefault();

                            fetch("./ajax.php?module=dashboard&categ=plugin&plugin=nedap&sub=user&action=raz")
                            .then((result) => result.json())
                            .then((response) => {
                                if (response.success) {
                                    const select = document.getElementById("rfid_nedap_station");
                                    select.value = "";
                                    nedap_notification("info", pmbDojo.messages.getMessage("common", "success_save"));
                                } else {
                                    nedap_notification("error", pmbDojo.messages.getMessage("common", "failed_save"));
                                }
                            })
                            .catch((_) => {
                                nedap_notification("error", pmbDojo.messages.getMessage("common", "failed_save"));
                            });
                        }

                        function saveStation(event) {
                            event.preventDefault();

                            fetch("./ajax.php?module=dashboard&categ=plugin&plugin=nedap&sub=user&action=set", {
                                method: "POST",
                                body: new FormData(event.target),
                            })
                            .then((result) => result.json())
                            .then((response) => {
                                if (response.success) {
                                    nedap_notification("info", pmbDojo.messages.getMessage("common", "success_save"));
                                } else {
                                    nedap_notification("error", pmbDojo.messages.getMessage("common", "failed_save"));
                                }
                            })
                            .catch((_) => {
                                nedap_notification("error", pmbDojo.messages.getMessage("common", "failed_save"));
                            });
                            return false;
                        }
                    </script>
                </div>
                HTML;
        }

        $event->add_content($content);
    }
}
