<?php

namespace GriffinForms\Admin\Html\Pages\Settings;

class General extends \GriffinForms\Admin\Html\Pages\Settings\Format
{
    protected function settingsGroupOptions()
    {
        $this->getOptionHtml('required_indicator_mode');
        $this->getOptionHtml('delete_data_on_uninstall');
        $this->getOptionHtml('exclude_admin_submissions_from_lifetime_count');
        echo '</tbody></table>';
        $this->loggingSectionIntro();
        echo '<table class="form-table indent-children" role="presentation"><tbody>';
        $this->getOptionHtml('enable_native_logging');
        $this->getOptionHtml('log_message_types');
        $this->getOptionHtml('log_retention');
        /**
         * Fires after all Core options are rendered in Global Settings -> General.
         * Use this to append additional settings rows inside the open <tbody>.
         */
        do_action('griffinforms_global_settings_general_after');
    }

    protected function getrequiredindicatormodeHtml($input_id)
    {
        $mode        = (string) $this->settings->getOption('required_indicator_mode', 'asterisk');
        $custom_text = (string) $this->settings->getOption('required_indicator_custom_text', '');

        echo '<div>';
        echo '<div class="form-check">';
        echo '<input class="form-check-input" type="radio" name="required_indicator_mode" id="' . esc_attr($input_id) . '_asterisk" value="asterisk" ' . checked($mode, 'asterisk', false) . '>';
        echo '<label class="form-check-label" for="' . esc_attr($input_id) . '_asterisk">' . esc_html__('Asterisk (*)', 'griffinforms-form-builder') . '</label>';
        echo '</div>';
        echo '<div class="form-check">';
        echo '<input class="form-check-input" type="radio" name="required_indicator_mode" id="' . esc_attr($input_id) . '_custom" value="custom_text" ' . checked($mode, 'custom_text', false) . '>';
        echo '<label class="form-check-label" for="' . esc_attr($input_id) . '_custom">' . esc_html__('Custom text', 'griffinforms-form-builder') . '</label>';
        echo '</div>';
        echo '<div id="gf-required-custom-text-wrap" class="mt-2"' . ($mode !== 'custom_text' ? ' style="display:none"' : '') . '>';
        echo '<input type="text" class="form-control form-control-sm" name="required_indicator_custom_text" id="' . esc_attr($input_id) . '_custom_text" value="' . esc_attr($custom_text === 'none' ? '' : $custom_text) . '" maxlength="100" placeholder="' . esc_attr__('Leave blank to show nothing', 'griffinforms-form-builder') . '">';
        echo '<p class="mt-1 text-secondary small">' . esc_html__('Leave blank to show nothing.', 'griffinforms-form-builder') . '</p>';
        echo '</div>';
        echo '</div>';
        echo '<script>';
        echo 'document.querySelectorAll(\'[name="required_indicator_mode"]\').forEach(function(r){r.addEventListener(\'change\',function(){document.getElementById(\'gf-required-custom-text-wrap\').style.display=this.value===\'custom_text\'?\'\':\'none\';});});';
        echo '</script>';

        $this->getOptionDescription('requiredIndicatorMode');
        $this->displayOptionHistory();
    }

    protected function getdeleteDataOnUninstallHtml($input_id)
    {
        $this->option = $this->settings->getOptionHistory('delete_data_on_uninstall');
        $current_value = isset($this->option['current_value']) ? (int) $this->option['current_value'] : 0;

        echo '<label for="' . esc_attr($input_id) . '">';
        echo '<input type="checkbox" id="' . esc_attr($input_id) . '" name="delete_data_on_uninstall" value="1" ' . checked(1, $current_value, false) . ' />';
        echo esc_html($this->lang->getText('delete_data_on_uninstall', 'label'));
        echo '</label>';

        $this->getOptionDescription('deleteDataOnUninstall');
        $this->displayOptionHistory();
    }

    protected function getexcludeAdminSubmissionsFromLifetimeCountHtml($input_id)
    {
        $this->option = $this->settings->getOptionHistory('exclude_admin_submissions_from_lifetime_count');
        $current_value = isset($this->option['current_value']) ? (int) $this->option['current_value'] : 0;

        echo '<label for="' . esc_attr($input_id) . '">';
        echo '<input type="checkbox" id="' . esc_attr($input_id) . '" name="exclude_admin_submissions_from_lifetime_count" value="1" ' . checked(1, $current_value, false) . ' />';
        echo esc_html($this->lang->getText('exclude_admin_submissions_from_lifetime_count', 'label'));
        echo '</label>';

        $this->getOptionDescription('excludeAdminSubmissionsFromLifetimeCount');
        $this->displayOptionHistory();
    }

    protected function getenableNativeLoggingHtml($input_id)
    {
        $this->option = $this->settings->getOptionHistory('enable_native_logging');
        $current_value = isset($this->option['current_value']) ? (int) $this->option['current_value'] : 1;

        echo '<label for="' . esc_attr($input_id) . '">';
        echo '<input type="checkbox" id="' . esc_attr($input_id) . '" name="enable_native_logging" value="1" ' . checked(1, $current_value, false) . ' />';
        echo esc_html($this->lang->getText('enable_native_logging', 'label'));
        echo '</label>';

        $this->getOptionDescription('enableNativeLogging');
        $this->displayOptionHistory();
    }

    /**
     * Render log_message_types option as a checkbox group
     */
    protected function getlogMessageTypesHtml($input_id)
    {
        $this->option  = $this->settings->getOptionHistory('log_message_types');
        $choices       = $this->choices->getChoices('log_message_types');
        $selected      = [];

        if (!empty($this->option) && isset($this->option['current_value']) && $this->option['current_value'] !== '') {
            $val = $this->option['current_value'];
            $selected = is_array($val) ? $val : (array) maybe_unserialize($val);
        } else {
            // Default: all selected (choices are value => label)
            $selected = array_keys($choices);
        }

        echo '<div class="griffinforms-setting-field">';
        echo '<div class="griffinforms-setting-label">' . esc_html($this->lang->getText('log_message_types', 'label')) . '</div>';

        echo '<div class="griffinforms-checkbox-group" id="' . esc_attr($input_id) . '" style="margin: 6px 0;">';
        foreach ($choices as $value => $label) {
            if ($value === '') { continue; }
            $checkbox_id = $input_id . '_' . sanitize_key($value);

            echo '<label for="' . esc_attr($checkbox_id) . '" class="griffinforms-checkbox" style="line-height: 1.5;">';
            echo '<input type="checkbox" id="' . esc_attr($checkbox_id) . '" name="log_message_types[]" value="' . esc_attr($value) . '" ' . checked(in_array($value, $selected, true), true, false) . ' />';
            echo ' ' . esc_html($label);
            echo '</label><br>';
        }
        echo '</div>';

        $this->getOptionDescription('log_message_types');
        $this->displayOptionHistory();
        echo '</div>';
    }
    
    /**
     * Render log_retention option as a <select>
     */
    protected function getlogRetentionHtml($input_id)
    {
        // Saved value (default 10000)
        $this->option = $this->settings->getOptionHistory('log_retention');
        $current_value = isset($this->option['current_value']) && $this->option['current_value'] !== ''
            ? (string) $this->option['current_value']
            : 'latest_10000';

        $choices = $this->choices->getChoices('log_retention');

        echo '<div class="griffinforms-setting-field">';

        echo '<select id="' . esc_attr($input_id) . '" name="log_retention">';
        
        foreach ($choices as $value => $label) {
            // If choices were returned as a numeric array of arrays/strings, normalize
            if (is_int($value)) {
                if (is_array($label)) {
                    $value = isset($label['value']) ? (string) $label['value'] : '';
                    $label = isset($label['label']) ? (string) $label['label'] : $value;
                } else {
                    $value = (string) $label;
                }
            }

            if ($value === '') { continue; }
            echo '<option value="' . esc_attr($value) . '" ' . selected($current_value, (string) $value, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select>';

        $this->getOptionDescription('logRetention');
        $this->displayOptionHistory();
        echo '</div>';
    }

    /**
     * Intro copy for the Logging settings section.
     */
    protected function loggingSectionIntro()
    {
        echo '<h2 class="title">' . esc_html__('Logging', 'griffinforms-form-builder') . '</h2>';
        echo '<p>' . esc_html__('Configure native logging for GriffinForms: enable or disable logging, choose which message types to record (success, error, info, warning), and set how many recent entries to retain.', 'griffinforms-form-builder') . '</p>';
    }
}
