<?php

namespace GriffinForms\Admin\Html\Pages\Settings;

class Format extends \GriffinForms\Admin\Html\Pages\Format
{
    protected $config;
    protected $meta;
    protected $type;
    protected $sql;
    protected $lang;
    protected $secure;
    protected $css;
    protected $js_data;
    protected $js_object;
    protected $js;
    protected $option;
    
    protected function pageModals()
    {

    }
    
    protected function setJsData()
    {
        $this->js_data = array(
            'group' => strtolower($this->meta)
        );
    }
    
    protected function setCss()
    {
        $css_file = $this->config->getRootUrl() . 'admin/css/griffinforms-settings.css';
        wp_enqueue_style('griffinforms-settings-css', $css_file, [], '1.0', false);
    }
    
    protected function setJs()
    {
        $js_file = $this->config->getRootUrl() . 'admin/js/griffinforms-settings.js';
        wp_enqueue_script('griffinforms-settings', $js_file, [], '1.0', false);
    }

    protected function hasHistory()
    {
        // Check if the necessary elements for option history are set in $this->option
        if (!isset($this->option['last_value'], $this->option['last_editor'], $this->option['last_edited_on'])) {
            return false; // Return false if any required data is missing
        }

        // Check if the last value is 'none', indicating no meaningful history exists
        if ($this->option['last_value'] === 'none') {
            return false;
        }

        // Return true if all checks pass and a valid history exists
        return true;
    }

    protected function settingsTabBar()
    {
        $pages = \GriffinForms\Admin\Pages::getInstance();
        $settings_pages = $pages->settings_pages;
    
        // Ensure $settings_pages is a non-empty array
        if (!is_array($settings_pages) || empty($settings_pages)) {
            return; // Optionally, you could display a message or handle this case differently
        }
    
        $current_page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
    
        echo '<div class="griffinforms-settings-header">';
        $this->settingsHeader();
        echo '<nav class="griffinforms-settings-tabs-wrapper" aria-label="Settings tabs">';
        echo '<div class="griffinforms-settings-tabs" role="tablist">';

        foreach ($settings_pages as $settings_page) {
            $page_slug = 'griffinforms-settings-' . $settings_page;
            $url = add_query_arg('page', $page_slug, admin_url('admin.php'));

            $is_active = ($current_page === $page_slug);
            $active_class = $is_active ? ' active' : '';
            $aria_current = $is_active ? ' aria-current="page"' : '';

            echo '<a href="' . esc_url($url) . '" class="griffinforms-settings-tab' . esc_attr($active_class) . '"' . esc_attr($aria_current) . '>';
            echo esc_html($this->lang->getText($settings_page . 'Title'));
            echo '</a>';
        }

        echo '<span class="griffinforms-settings-tab-indicator" aria-hidden="true"></span>';
        echo '</div>';
        echo '<div class="griffinforms-settings-tabs-overflow">';
        echo '<button type="button" class="griffinforms-settings-tabs-more" aria-haspopup="true" aria-expanded="false">';
        echo esc_html(__('More', 'griffinforms-form-builder'));
        echo '</button>';
        echo '<div class="griffinforms-settings-tabs-more-menu" role="menu"></div>';
        echo '</div>';
        echo '</nav>';
        echo '</div>';
    }

    protected function settingsHeader()
    {
        echo '<div class="griffinforms-settings-title-section"><h1>';
        echo esc_html($this->lang->getText('settings_title'));
		echo '</h1></div>';
    }

    protected function pageNoticeError()
    {
        echo '<div class="griffinforms-settings-notice griffinforms-settings-notice-errors gf-is-dismissible" style="display: none;">';
        echo '<p></p>';
        echo '<button type="button" class="gf-dismiss-notice">&times;</button>';
        echo '</div>';
    }

    protected function pageNoticeSuccess()
    {
        echo '<div class="griffinforms-settings-notice griffinforms-settings-notice-success gf-is-dismissible" style="display: none;">';
        echo '<p>' . esc_html($this->lang->getText('settings_saved_successfully')) . '</p>';
        echo '<button type="button" class="gf-dismiss-notice">&times;</button>';
        echo '</div>';
    }
    
    public function html()
    {
        $this->pageModals();
        $this->settingsTabBar();
        $this->pageNoticeError();
        $this->pageNoticeSuccess();
        echo '<table class="form-table griffinforms-settings-form-table" role="presentation">';
        echo '<tbody>';

        $this->settingsGroupOptions();
        
        echo '</tbody>';
        echo '</table>';
        $this->getSubmitBtn();
    }

    protected function getSubmitBtn()
    {
        $btn_id = 'griffinforms-settings-' . sanitize_text_field(strtolower($this->meta)) . '-update-btn';

        echo '<p class="submit">';
        echo '<input type="submit" name="submit" id="' . esc_attr($btn_id) . '" class="button button-primary" value="';
        echo esc_html($this->lang->getText('submit_btn_settings'));
        echo '">';
        echo '<span class="spinner" style="float: none; margin-top: 4px;"></span>';
        echo '</p>';
    }

    protected function settingsGroupOptions()
    {

    }

    protected function getOptionHtml($option_name = '')
    {

        if (empty($option_name) || !is_string($option_name)) {
            return;
        }

        $option_name = sanitize_text_field($this->purgeString($option_name));

        $input_id = 'griffinforms-settings-' . sanitize_text_field(strtolower($this->meta)) . '-' . strtolower($option_name);
        $method = 'get' . $option_name . 'Html';

        echo '<tr>';
        echo '<th scope="row"><label for="' . esc_attr($input_id) . '">';
        echo esc_html($this->lang->getText($option_name, 'label'));
        echo '</label></th>';
        echo '<td>';

        if (method_exists($this, $method) || is_callable([$this, $method])) {
            $this->$method($input_id);
        }

        echo '</td></tr>';
    }

    protected function getOptionDescription($option_name)
    {
        echo '<p class="description">';
        echo wp_kses_post($this->lang->getText($option_name, 'description'));
        echo '</p>';
    }

    protected function displayOptionHistory()
    {
        // Ensure the option history is loaded correctly
        if (!$this->hasHistory()) {
            return; // If the data is missing, don't output the history
        }
    
        $history = $this->option['history'] ?? [];
        $history_count = is_array($history) ? count($history) : 0;
        $max_len = 160;

        $latest_entry = $history_count > 0 ? $history[0] : null;
        $latest_value = $latest_entry['value'] ?? $this->option['last_value'];
        $last_editor_id = $latest_entry['editor'] ?? $this->option['last_editor'];
        $last_edited_on = $latest_entry['edited_on'] ?? $this->option['last_edited_on'];

        [$last_value_trimmed, $last_value_full, $last_value_truncated] = $this->getHistoryValueDisplay($latest_value, $max_len);
    
        // Fetch editor details based on user ID
        $editor = get_user_by('id', $last_editor_id);
        $editor_name = $editor ? $editor->display_name : __('Unknown User', 'griffinforms-form-builder');
    
        // Get the user's Gravatar
        $gravatar = $editor ? get_avatar($editor->user_email, 32, 'retro') : get_avatar('', 32, 'mystery', '', ['class' => 'unknown-user-avatar']);
    
        // Format the edited time
        $formatted_time = wp_date(get_option('date_format') . ' ' . get_option('time_format'), strtotime($last_edited_on));
    
        // Output the history
        echo '<div class="griffinforms-settings-option-history">';
        echo '<span><span class="dashicons dashicons-clock"></span> ' . esc_html(__('Last changed by', 'griffinforms-form-builder')) . ' ' . wp_kses_post($gravatar) . ' ' . esc_html($editor_name) . '</span> ';
        echo '<span>' . esc_html(__('on', 'griffinforms-form-builder')) . ' ' . esc_html($formatted_time) . '</span>. ';
        echo '<span>' . esc_html(__('Its previous value was', 'griffinforms-form-builder')) . ' <code>' . esc_html($last_value_trimmed) . '</code>';
        if ($last_value_truncated) {
            echo ' <a href="#" class="gf-settings-history-view-full" data-gf-full-value="' . esc_attr($last_value_full) . '">' . esc_html__('View full', 'griffinforms-form-builder') . '</a>';
        }
        echo '</span>';

        if ($history_count > 1) {
            $toggle_text = sprintf(__('View history (%d)', 'griffinforms-form-builder'), $history_count - 1);
            echo ' <a href="#" class="gf-settings-history-toggle" data-gf-collapsed-text="' . esc_attr($toggle_text) . '" data-gf-expanded-text="' . esc_attr(__('Hide history', 'griffinforms-form-builder')) . '" aria-expanded="false">' . esc_html($toggle_text) . '</a>';

            echo '<div class="gf-settings-history-list" style="display: none;">';
            echo '<ul class="gf-settings-history-items">';
            for ($i = 1; $i < $history_count; $i++) {
                $entry = $history[$i];
                $entry_editor_id = $entry['editor'] ?? null;
                $entry_editor = $entry_editor_id ? get_user_by('id', $entry_editor_id) : null;
                $entry_editor_name = $entry_editor ? $entry_editor->display_name : __('Unknown User', 'griffinforms-form-builder');
                $entry_time = $entry['edited_on'] ?? '';
                $entry_time_formatted = $entry_time ? wp_date(get_option('date_format') . ' ' . get_option('time_format'), strtotime($entry_time)) : '';

                $previous_value = $entry['value'] ?? '';
                $new_value = $history[$i - 1]['value'] ?? '';

                [$prev_trimmed, $prev_full, $prev_truncated] = $this->getHistoryValueDisplay($previous_value, $max_len);
                [$new_trimmed, $new_full, $new_truncated] = $this->getHistoryValueDisplay($new_value, $max_len);

                echo '<li class="gf-settings-history-item">';
                echo esc_html($entry_editor_name) . ' ' . esc_html(__('changed value from', 'griffinforms-form-builder')) . ' <code>' . esc_html($prev_trimmed) . '</code>';
                if ($prev_truncated) {
                    echo ' <a href="#" class="gf-settings-history-view-full" data-gf-full-value="' . esc_attr($prev_full) . '">' . esc_html__('View full', 'griffinforms-form-builder') . '</a>';
                }
                echo ' ' . esc_html(__('to', 'griffinforms-form-builder')) . ' <code>' . esc_html($new_trimmed) . '</code>';
                if ($new_truncated) {
                    echo ' <a href="#" class="gf-settings-history-view-full" data-gf-full-value="' . esc_attr($new_full) . '">' . esc_html__('View full', 'griffinforms-form-builder') . '</a>';
                }
                if (!empty($entry_time_formatted)) {
                    echo ' ' . esc_html(__('on', 'griffinforms-form-builder')) . ' ' . esc_html($entry_time_formatted) . '.';
                }
                echo '</li>';
            }
            echo '</ul>';
            echo '</div>';
        }
        echo '</div>';
    }

    /**
     * Format an option history value for display.
     *
     * @param mixed $value
     * @return string
     */
    protected function formatOptionHistoryValue($value): string
    {
        if ($value === '1' || $value === 1) {
            return 'enabled';
        }
        if ($value === '0' || $value === 0) {
            return 'disabled';
        }
        if (is_array($value)) {
            return implode(', ', array_map('sanitize_text_field', $value));
        }
        return (string) $value;
    }

    protected function getHistoryValueDisplay($value, $max_len): array
    {
        $formatted = $this->formatOptionHistoryValue($value);
        $full = (string) $formatted;
        $trimmed = $full;
        $truncated = false;
        if (strlen($full) > $max_len) {
            $trimmed = substr($full, 0, $max_len) . '...';
            $truncated = true;
        }
        return [$trimmed, $full, $truncated];
    }
}
