<?php

if (!defined('ABSPATH')) {
    exit;
}

class Ansico_Diagnosekoder_Admin {
    public static function init() {
        add_action('admin_menu', [__CLASS__, 'register_admin_page']);
        add_action('admin_post_ansico_diagnosekoder_save_settings', [__CLASS__, 'handle_save_settings']);
        add_action('admin_post_ansico_diagnosekoder_import_data', [__CLASS__, 'handle_import_data']);
        add_action('admin_post_ansico_diagnosekoder_remove_data', [__CLASS__, 'handle_remove_data']);
        add_action('admin_post_ansico_diagnosekoder_remove_favorite', [__CLASS__, 'handle_remove_favorite']);
        add_action('admin_post_ansico_diagnosekoder_remove_link', [__CLASS__, 'handle_remove_link']);
    }

    public static function register_admin_page() {
        add_options_page(
            __('Ansico Diagnosekoder', 'ansico-diagnosekoder'),
            __('Ansico Diagnosekoder', 'ansico-diagnosekoder'),
            'manage_options',
            'ansico-diagnosekoder',
            [__CLASS__, 'render_admin_page']
        );
    }

    public static function render_admin_page() {
        if (!current_user_can('manage_options')) {
            return;
        }

        $meta = get_option(ANSICO_DIAGNOSEKODER_OPTION_META, []);
        $results_url = get_option(ANSICO_DIAGNOSEKODER_OPTION_RESULTS_URL, '');
        $status = isset($_GET['status']) ? sanitize_key(wp_unslash($_GET['status'])) : '';
        $favorite_rows = self::get_results_page_favorite_rows();
        $link_rows = self::get_results_page_link_rows();
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Ansico Diagnosekoder', 'ansico-diagnosekoder'); ?></h1>

            <?php if ($status === 'success') : ?>
                <div class="notice notice-success is-dismissible"><p><?php esc_html_e('Filen blev importeret.', 'ansico-diagnosekoder'); ?></p></div>
            <?php elseif ($status === 'settings_saved') : ?>
                <div class="notice notice-success is-dismissible"><p><?php esc_html_e('Indstillingerne blev gemt.', 'ansico-diagnosekoder'); ?></p></div>
            <?php elseif ($status === 'data_removed') : ?>
                <div class="notice notice-success is-dismissible"><p><?php esc_html_e('Datakilden blev fjernet.', 'ansico-diagnosekoder'); ?></p></div>
            <?php elseif ($status === 'no_file') : ?>
                <div class="notice notice-warning is-dismissible"><p><?php esc_html_e('Vælg en ny fil for at importere og erstatte det eksisterende datagrundlag.', 'ansico-diagnosekoder'); ?></p></div>
            <?php elseif ($status === 'favorite_removed') : ?>
                <div class="notice notice-success is-dismissible"><p><?php esc_html_e('Favoritten blev fjernet.', 'ansico-diagnosekoder'); ?></p></div>
            <?php elseif ($status === 'link_removed') : ?>
                <div class="notice notice-success is-dismissible"><p><?php esc_html_e('URL-tilknytningen blev fjernet.', 'ansico-diagnosekoder'); ?></p></div>
            <?php elseif ($status === 'error') : ?>
                <div class="notice notice-error is-dismissible"><p><?php echo esc_html(get_transient('ansico_diagnosekoder_admin_error') ?: __('Importen mislykkedes.', 'ansico-diagnosekoder')); ?></p></div>
            <?php endif; ?>

            <h2><?php esc_html_e('Favoritter på resultatsiden', 'ansico-diagnosekoder'); ?></h2>
                <?php if (!empty($favorite_rows)) : ?>
                    <table class="widefat striped" style="max-width: 1100px; margin-bottom: 24px;">
                        <thead>
                            <tr>
                                <th><?php esc_html_e('Kode', 'ansico-diagnosekoder'); ?></th>
                                <th><?php esc_html_e('Beskrivelse', 'ansico-diagnosekoder'); ?></th>
                                <th style="width: 120px;"><?php esc_html_e('Handling', 'ansico-diagnosekoder'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($favorite_rows as $row) : ?>
                                <tr>
                                    <td><strong><?php echo esc_html($row['code']); ?></strong></td>
                                    <td><?php echo esc_html($row['text']); ?></td>
                                    <td>
                                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                                            <?php wp_nonce_field('ansico_diagnosekoder_remove_favorite_' . $row['code']); ?>
                                            <input type="hidden" name="action" value="ansico_diagnosekoder_remove_favorite" />
                                            <input type="hidden" name="code" value="<?php echo esc_attr($row['code']); ?>" />
                                            <?php submit_button(__('Fjern', 'ansico-diagnosekoder'), 'secondary small', '', false); ?>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else : ?>
                    <p><?php esc_html_e('Der er endnu ikke gemt nogen side-favoritter for den valgte resultatside.', 'ansico-diagnosekoder'); ?></p>
                <?php endif; ?>

                <h2><?php esc_html_e('Kode-URL-tilknytninger på resultatsiden', 'ansico-diagnosekoder'); ?></h2>
                <?php if (!empty($link_rows)) : ?>
                    <table class="widefat striped" style="max-width: 1200px; margin-bottom: 24px;">
                        <thead>
                            <tr>
                                <th><?php esc_html_e('Kode', 'ansico-diagnosekoder'); ?></th>
                                <th><?php esc_html_e('Beskrivelse', 'ansico-diagnosekoder'); ?></th>
                                <th><?php esc_html_e('URL', 'ansico-diagnosekoder'); ?></th>
                                <th style="width: 120px;"><?php esc_html_e('Handling', 'ansico-diagnosekoder'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($link_rows as $row) : ?>
                                <tr>
                                    <td><strong><?php echo esc_html($row['code']); ?></strong></td>
                                    <td><?php echo esc_html($row['text']); ?></td>
                                    <td><a href="<?php echo esc_url($row['url']); ?>"><?php echo esc_html($row['url']); ?></a></td>
                                    <td>
                                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                                            <?php wp_nonce_field('ansico_diagnosekoder_remove_link_' . $row['code']); ?>
                                            <input type="hidden" name="action" value="ansico_diagnosekoder_remove_link" />
                                            <input type="hidden" name="code" value="<?php echo esc_attr($row['code']); ?>" />
                                            <?php submit_button(__('Fjern', 'ansico-diagnosekoder'), 'secondary small', '', false); ?>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else : ?>
                    <p><?php esc_html_e('Der er endnu ikke gemt nogen kode-URL-tilknytninger for den valgte resultatside.', 'ansico-diagnosekoder'); ?></p>
                <?php endif; ?>

                <h2><?php esc_html_e('Aktuelt datagrundlag', 'ansico-diagnosekoder'); ?></h2>
                <?php if (!empty($meta)) : ?>
                    <table class="widefat striped" style="max-width: 900px;">
                        <tbody>
                            <tr>
                                <td><strong><?php esc_html_e('Kilde', 'ansico-diagnosekoder'); ?></strong></td>
                                <td><?php echo esc_html($meta['source_name'] ?? ''); ?></td>
                            </tr>
                            <tr>
                                <td><strong><?php esc_html_e('Importeret', 'ansico-diagnosekoder'); ?></strong></td>
                                <td><?php echo esc_html($meta['imported_at'] ?? ''); ?></td>
                            </tr>
                            <tr>
                                <td><strong><?php esc_html_e('Antal rækker', 'ansico-diagnosekoder'); ?></strong></td>
                                <td><?php echo esc_html((string) ($meta['row_count'] ?? 0)); ?></td>
                            </tr>
                            <tr>
                                <td><strong><?php esc_html_e('Header fundet', 'ansico-diagnosekoder'); ?></strong></td>
                                <td><?php echo !empty($meta['header_found']) ? esc_html__('Ja', 'ansico-diagnosekoder') : esc_html__('Nej', 'ansico-diagnosekoder'); ?></td>
                            </tr>
                        </tbody>
                    </table>
                <?php else : ?>
                    <p><?php esc_html_e('Ingen data importeret endnu.', 'ansico-diagnosekoder'); ?></p>
                <?php endif; ?>

            <h2><?php esc_html_e('Datakilde', 'ansico-diagnosekoder'); ?></h2>
            <p><?php esc_html_e('Upload en tekstfil med SKS/ICD-10 koder. En ny import erstatter kun det eksisterende datagrundlag, hvis der er valgt en ny fil.', 'ansico-diagnosekoder'); ?></p>

            <div style="display:flex; align-items:flex-end; gap:8px; flex-wrap:wrap; margin-bottom:40px;">
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" enctype="multipart/form-data" style="margin:0;">
                    <?php wp_nonce_field('ansico_diagnosekoder_import_data'); ?>
                    <input type="hidden" name="action" value="ansico_diagnosekoder_import_data" />

                    <table class="form-table" role="presentation">
                        <tr>
                            <th scope="row"><label for="ansico_diagnosekoder_file"><?php esc_html_e('Datafil', 'ansico-diagnosekoder'); ?></label></th>
                            <td>
                                <input type="file" name="ansico_diagnosekoder_file" id="ansico_diagnosekoder_file" accept=".txt,.csv,text/plain" />
                                <p class="description"><?php esc_html_e('Forventet format: semikolon-separeret tekstfil med kolonnerne "Kode" og "Tekst".', 'ansico-diagnosekoder'); ?></p>
                            </td>
                        </tr>
                    </table>

                    <?php submit_button(__('Importer datakilde', 'ansico-diagnosekoder'), 'primary', 'submit', false); ?>
                </form>

                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" onsubmit="return confirm('<?php echo esc_js(__('Er du sikker på, at du vil fjerne datakilden?', 'ansico-diagnosekoder')); ?>');" style="margin:0 0 8px 0;">
                    <?php wp_nonce_field('ansico_diagnosekoder_remove_data'); ?>
                    <input type="hidden" name="action" value="ansico_diagnosekoder_remove_data" />
                    <?php submit_button(__('Fjern datakilde', 'ansico-diagnosekoder'), 'delete', 'submit', false); ?>
                </form>
            </div>

            <h2><?php esc_html_e('Opsætning', 'ansico-diagnosekoder'); ?></h2>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <?php wp_nonce_field('ansico_diagnosekoder_save_settings'); ?>
                <input type="hidden" name="action" value="ansico_diagnosekoder_save_settings" />

                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><label for="ansico_diagnosekoder_results_url"><?php esc_html_e('URL til resultatside', 'ansico-diagnosekoder'); ?></label></th>
                        <td>
                            <input type="url" name="ansico_diagnosekoder_results_url" id="ansico_diagnosekoder_results_url" class="regular-text code" value="<?php echo esc_attr($results_url); ?>" placeholder="https://example.dk/diagnosekoder/" />
                            <p class="description"><?php esc_html_e('Bruges af blokken med kun søgefelt. Ved submit sendes brugeren til denne side med søgetermen i URL-parameteren q.', 'ansico-diagnosekoder'); ?></p>
                        </td>
                    </tr>
                </table>

                <?php submit_button(__('Gem indstillinger', 'ansico-diagnosekoder')); ?>
            </form>
        </div>
        <?php
        delete_transient('ansico_diagnosekoder_admin_error');
    }

    public static function handle_save_settings() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Du har ikke rettigheder til dette.', 'ansico-diagnosekoder'));
        }

        check_admin_referer('ansico_diagnosekoder_save_settings');

        $results_url = isset($_POST['ansico_diagnosekoder_results_url']) ? esc_url_raw(wp_unslash($_POST['ansico_diagnosekoder_results_url'])) : '';
        update_option(ANSICO_DIAGNOSEKODER_OPTION_RESULTS_URL, $results_url, false);

        wp_safe_redirect(add_query_arg([
            'page' => 'ansico-diagnosekoder',
            'status' => 'settings_saved',
        ], admin_url('options-general.php')));
        exit;
    }

    public static function handle_import_data() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Du har ikke rettigheder til dette.', 'ansico-diagnosekoder'));
        }

        check_admin_referer('ansico_diagnosekoder_import_data');

        if (empty($_FILES['ansico_diagnosekoder_file']) || empty($_FILES['ansico_diagnosekoder_file']['tmp_name'])) {
            wp_safe_redirect(add_query_arg([
                'page' => 'ansico-diagnosekoder',
                'status' => 'no_file',
            ], admin_url('options-general.php')));
            exit;
        }

        $file = $_FILES['ansico_diagnosekoder_file'];
        $overrides = [
            'test_form' => false,
            'mimes' => [
                'txt' => 'text/plain',
                'csv' => 'text/plain',
            ],
        ];

        require_once ABSPATH . 'wp-admin/includes/file.php';
        $uploaded = wp_handle_upload($file, $overrides);

        if (!empty($uploaded['error'])) {
            self::redirect_with_error($uploaded['error']);
        }

        $parsed = Ansico_Diagnosekoder_Parser::parse_file($uploaded['file']);
        if (!empty($parsed['meta']['error'])) {
            self::redirect_with_error($parsed['meta']['error']);
        }

        if (empty($parsed['rows'])) {
            self::redirect_with_error(__('Filen indeholdt ingen importerbare diagnosekoder.', 'ansico-diagnosekoder'));
        }

        update_option(ANSICO_DIAGNOSEKODER_OPTION_DATA, $parsed['rows'], false);
        update_option(ANSICO_DIAGNOSEKODER_OPTION_META, $parsed['meta'], false);

        wp_safe_redirect(add_query_arg([
            'page' => 'ansico-diagnosekoder',
            'status' => 'success',
        ], admin_url('options-general.php')));
        exit;
    }

    public static function handle_remove_data() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Du har ikke rettigheder til dette.', 'ansico-diagnosekoder'));
        }

        check_admin_referer('ansico_diagnosekoder_remove_data');

        delete_option(ANSICO_DIAGNOSEKODER_OPTION_DATA);
        delete_option(ANSICO_DIAGNOSEKODER_OPTION_META);

        wp_safe_redirect(add_query_arg([
            'page' => 'ansico-diagnosekoder',
            'status' => 'data_removed',
        ], admin_url('options-general.php')));
        exit;
    }

    public static function handle_remove_favorite() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Du har ikke rettigheder til dette.', 'ansico-diagnosekoder'));
        }

        $code = isset($_POST['code']) ? sanitize_text_field(wp_unslash($_POST['code'])) : '';
        if ($code === '') {
            self::redirect_with_error(__('Der mangler en kode.', 'ansico-diagnosekoder'));
        }

        check_admin_referer('ansico_diagnosekoder_remove_favorite_' . $code);

        $results_page_id = self::get_results_page_id();
        if (!$results_page_id) {
            self::redirect_with_error(__('Resultatsiden kunne ikke findes.', 'ansico-diagnosekoder'));
        }

        $favorites = Ansico_Diagnosekoder_REST::get_page_favorites($results_page_id);
        $normalized_code = strtoupper(preg_replace('/\s+/', '', $code));
        $favorites = array_values(array_filter($favorites, static function ($item) use ($normalized_code) {
            return $item !== $normalized_code;
        }));
        update_post_meta($results_page_id, ANSICO_DIAGNOSEKODER_PAGE_FAVORITES_META, $favorites);

        wp_safe_redirect(add_query_arg([
            'page' => 'ansico-diagnosekoder',
            'status' => 'favorite_removed',
        ], admin_url('options-general.php')));
        exit;
    }

    public static function handle_remove_link() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Du har ikke rettigheder til dette.', 'ansico-diagnosekoder'));
        }

        $code = isset($_POST['code']) ? sanitize_text_field(wp_unslash($_POST['code'])) : '';
        if ($code === '') {
            self::redirect_with_error(__('Der mangler en kode.', 'ansico-diagnosekoder'));
        }

        check_admin_referer('ansico_diagnosekoder_remove_link_' . $code);

        $results_page_id = self::get_results_page_id();
        if (!$results_page_id) {
            self::redirect_with_error(__('Resultatsiden kunne ikke findes.', 'ansico-diagnosekoder'));
        }

        $normalized_code = strtoupper(preg_replace('/\s+/', '', $code));
        $links = Ansico_Diagnosekoder_REST::get_page_links($results_page_id);
        unset($links[$normalized_code]);
        update_post_meta($results_page_id, ANSICO_DIAGNOSEKODER_PAGE_LINKS_META, $links);

        wp_safe_redirect(add_query_arg([
            'page' => 'ansico-diagnosekoder',
            'status' => 'link_removed',
        ], admin_url('options-general.php')));
        exit;
    }

    protected static function get_results_page_favorite_rows() {
        $results_page_id = self::get_results_page_id();
        if (!$results_page_id) {
            return [];
        }

        return Ansico_Diagnosekoder_Parser::get_rows_by_codes(Ansico_Diagnosekoder_REST::get_page_favorites($results_page_id));
    }

    protected static function get_results_page_id() {
        $results_url = (string) get_option(ANSICO_DIAGNOSEKODER_OPTION_RESULTS_URL, '');
        if ($results_url === '') {
            return 0;
        }

        $page_id = url_to_postid($results_url);
        return absint($page_id);
    }

    protected static function get_results_page_link_rows() {
        $results_page_id = self::get_results_page_id();
        if (!$results_page_id) {
            return [];
        }

        $links = Ansico_Diagnosekoder_REST::get_page_links($results_page_id);
        if (empty($links)) {
            return [];
        }

        $rows = Ansico_Diagnosekoder_Parser::get_rows_by_codes(array_keys($links));
        foreach ($rows as &$row) {
            $row['url'] = isset($links[$row['code']]) ? $links[$row['code']] : '';
        }
        unset($row);

        return $rows;
    }

    protected static function redirect_with_error($message) {
        set_transient('ansico_diagnosekoder_admin_error', wp_strip_all_tags((string) $message), 60);
        wp_safe_redirect(add_query_arg([
            'page' => 'ansico-diagnosekoder',
            'status' => 'error',
        ], admin_url('options-general.php')));
        exit;
    }
}
