<?php
/**
 * Atomic Events Settings
 * 
 * Handles the plugin settings page with tabbed interface
 * 
 * @package AtomicEvents
 * @since 1.0.0
 */

defined('WPINC') or die;

class ATMCEVNTS_Settings {

    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $plugin_name    The ID of this plugin.
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $version    The current version of this plugin.
     */
    private $version;

    /**
     * General options
     *
     * @since    1.0.0
     * @access   private
     * @var      array    $general_options    The general settings.
     */
    private $general_options;



    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param      string    $plugin_name       The name of this plugin.
     * @param      string    $version    The version of this plugin.
     */
    public function __construct($plugin_name, $version) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
    }

    /**
     * Setup the plugin options menu
     */
    public function setup_plugin_options_menu() {
        add_submenu_page(
            'options-general.php',
            'Atomic Events Calendar Settings',
            'Atomic Events Calendar',
            'manage_options',
            'atomic_events_options',
            array($this, 'render_settings_page_content')
        );
        
        // Add action handler for cache clearing
        add_action('admin_post_atomic_events_clear_cache', array($this, 'handle_clear_cache'));
    }

    /**
     * Initialize settings
     */
    public function initialize_settings() {
        // Initialize general options
        $this->initialize_general_options();
    }

    /**
     * Initialize general options
     */
    public function initialize_general_options() {
        if (false == get_option('atomic_events_general_options')) {
            $default_array = $this->default_general_options();
            update_option('atomic_events_general_options', $default_array);
        }

        // Add Section
        add_settings_section(
            'atomic_events_general_section',
            			'<span class="dashicons dashicons-admin-network settings-page-icon"></span> ' . __('General Settings','atomic-events-calendar'),
            array($this, 'general_options_callback'),
            'atomic_events_general_options'
        );



        // Register setting
        register_setting(
            'atomic_events_general_options',
            'atomic_events_general_options',
            array($this, 'validate_general_options')
        );
    }



    /**
     * Default general options
     */
    private function default_general_options() {
        return array();
    }

    /**
     * General options callback
     */
    public function general_options_callback() {
        		echo '<p>' . esc_html__('Configure general settings for Atomic Events Calendar.','atomic-events-calendar') . '</p>';
    }

    /**
     * Number field render
     */
    public function number_field_render($args) {
        $field = $args['field'];
        $default = $args['default'];
        $options = get_option('atomic_events_' . str_replace('_options', '', current_filter()) . '_options');
        $value = isset($options[$field]) ? $options[$field] : $default;
        
        echo '<input type="number" id="' . esc_attr($field) . '" name="atomic_events_' . esc_attr(str_replace('_options', '', current_filter())) . '_options[' . esc_attr($field) . ']" value="' . esc_attr($value) . '" class="regular-text" />';
    }

    /**
     * Select field render
     */
    public function select_field_render($args) {
        $field = $args['field'];
        $options = $args['options'];
        $default = $args['default'];
        $current_options = get_option('atomic_events_' . str_replace('_options', '', current_filter()) . '_options');
        $value = isset($current_options[$field]) ? $current_options[$field] : $default;
        
        echo '<select id="' . esc_attr($field) . '" name="atomic_events_' . esc_attr(str_replace('_options', '', current_filter())) . '_options[' . esc_attr($field) . ']">';
        foreach ($options as $key => $label) {
            echo '<option value="' . esc_attr($key) . '" ' . selected($value, $key, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select>';
    }

    /**
     * Validate general options
     */
    public function validate_general_options($input) {
        $output = array();
        
        foreach ($input as $key => $value) {
            if (isset($input[$key])) {
                $output[$key] = sanitize_text_field($input[$key]);
            }
        }
        
        return apply_filters('atmcevnts_validate_general_options', $output, $input);
    }

    /**
     * Clear shortcode cache
     */
    private function clear_shortcode_cache() {
        // Use the EventQueryService to clear cache
        $event_query_service = new ATMCEVNTS_Event_Query_Service();
        $event_query_service->clear_cache();
    }

/**
 * Render settings page content
 */
public function render_settings_page_content($active_tab = '') {
    $this->general_options = get_option('atomic_events_general_options');

    // Define valid tabs
    $valid_tabs = ['general_options', 'cache', 'dev', 'theme', 'support'];

    // Determine active tab
    $raw_tab = filter_input(INPUT_GET, 'tab', FILTER_SANITIZE_SPECIAL_CHARS);
    $active_tab = ($raw_tab && in_array($raw_tab, $valid_tabs, true)) 
        ? sanitize_text_field(wp_unslash($raw_tab)) 
        : 'general_options';

    ?>
    <div class="wrap">
        		<h2><?php esc_html_e('Atomic Events Calendar Settings','atomic-events-calendar'); ?></h2>
        
        <?php settings_errors(); ?>

        <div class="atomic-events-admin-header mt-10">
            <div class="atomic-events-admin-banner">
                <h2 class="atomic-events-banner-title" style="display: flex; align-items: center; gap: 8px; margin: 0;">
                    <img src="<?php echo esc_url(plugin_dir_url(__FILE__) . '../assets/img/atomic-events-dark-128.png'); ?>" alt="AtomicEvents" style="height: 32px; width: auto;">
                    AtomicEvents.io
                </h2>
            </div>
        </div>

        <h2 class="nav-tab-wrapper">
            <a href="?page=atomic_events_options&tab=general_options" class="nav-tab <?php echo esc_attr($active_tab === 'general_options' ? 'nav-tab-active' : ''); ?>">
                			<span class="dashicons dashicons-admin-network"></span> <?php esc_html_e('General','atomic-events-calendar'); ?>
            </a>
            <a href="?page=atomic_events_options&tab=cache" class="nav-tab <?php echo esc_attr($active_tab === 'cache' ? 'nav-tab-active' : ''); ?>">
                			<span class="dashicons dashicons-performance"></span> <?php esc_html_e('Cache','atomic-events-calendar'); ?>
            </a>
            <a href="?page=atomic_events_options&tab=dev" class="nav-tab <?php echo esc_attr($active_tab === 'dev' ? 'nav-tab-active' : ''); ?>">
                			<span class="dashicons dashicons-editor-code"></span> <?php esc_html_e('Dev','atomic-events-calendar'); ?>
            </a>
            <a href="?page=atomic_events_options&tab=theme" class="nav-tab <?php echo esc_attr($active_tab === 'theme' ? 'nav-tab-active' : ''); ?>">
                			<span class="dashicons dashicons-admin-appearance"></span> <?php esc_html_e('Theme','atomic-events-calendar'); ?>
            </a>
            <a href="?page=atomic_events_options&tab=support" class="nav-tab <?php echo esc_attr($active_tab === 'support' ? 'nav-tab-active' : ''); ?>">
                			<span class="dashicons dashicons-businessman"></span> <?php esc_html_e('Support','atomic-events-calendar'); ?>
            </a>
        </h2>

        <?php if ($active_tab === 'general_options') { ?>
        <div class="atomic-events-outer">
            <div class="atomic-events-support-section" style="margin-bottom: 30px; padding: 20px; background: #f9f9f9; border-left: 4px solid #6366f1; border-radius: 4px;">
                <h3 style="margin-top: 0; color: #6366f1;">
                    <span class="dashicons dashicons-editor-code"></span> 
                    Atomic Events Calendar
                </h3>
                
                <p><strong>This plugin is designed for developers and advanced WordPress users.</strong></p>
                
                <p>Atomic Events Calendar provides a flexible, developer-friendly solution for managing and displaying events on WordPress sites. The plugin offers extensive customization options through template overrides, hooks, filters, and theme configurations.</p>
                
                <h4>Key Features:</h4>
                <ul>
                    <li><strong>Custom Post Type:</strong> Dedicated 'atomic-event' post type with comprehensive meta fields</li>
                    <li><strong>Template System:</strong> Multiple theme options with full template override capabilities</li>
                    <li><strong>Shortcode Support:</strong> Flexible <code>[atomic-events]</code> shortcode with multiple parameters</li>
                    <li><strong>Developer Hooks:</strong> Extensive filter and action hooks for customization</li>
                    <li><strong>Structured Data:</strong> Built-in JSON-LD schema markup for SEO</li>
                    <li><strong>Caching:</strong> Intelligent query caching for performance optimization</li>
                </ul>
                
                <p>Use the tabs above to explore configuration options, cache management, developer documentation, theme customization, and support resources.</p>
            </div>
        </div>
        <?php } elseif ($active_tab === 'cache') { ?>
        <div class="atomic-events-outer">
            <h2><span class="dashicons dashicons-performance settings-page-icon"></span> Cache Management</h2>
            
            <?php
            // Handle cache clearing
            $nonce = filter_input(INPUT_POST, '_wpnonce', FILTER_SANITIZE_SPECIAL_CHARS);
            if (filter_input(INPUT_POST, 'clear_shortcode_cache', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) && $nonce && wp_verify_nonce(wp_unslash($nonce), 'atomic_events_clear_cache')) {
                $this->clear_shortcode_cache();
                echo '<div class="notice notice-success"><p>Event query cache has been cleared successfully!</p></div>';
            }
            ?>
            
            <div class="atomic-events-support-section" style="margin-bottom: 30px; padding: 20px; background: #f9f9f9; border-left: 4px solid #6366f1; border-radius: 4px;">
                <h3 style="margin-top: 0; color: #6366f1;">
                    <span class="dashicons dashicons-performance"></span> 
                    Event Query Cache
                </h3>
                
                <p>The plugin caches event query results for 1 hour to improve performance. This cache stores the results of database queries for event lists used by shortcodes and other features.</p>
                
                <form method="post" style="margin-top: 15px;">
                    <?php wp_nonce_field('atomic_events_clear_cache'); ?>
                    <input type="submit" name="clear_shortcode_cache" class="button button-secondary" value="Clear Event Query Cache">
                    <p class="description">Use this if you need to immediately see changes to your events without waiting for the cache to expire.</p>
                </form>
            </div>
        </div>
        <?php } elseif ($active_tab === 'theme') { ?>
        <div class="atomic-events-outer">
            <h2><span class="dashicons dashicons-admin-appearance settings-page-icon"></span> Theme Configuration</h2>
            
            <div class="atomic-events-support-section" style="margin-bottom: 30px; padding: 20px; background: #f9f9f9; border-left: 4px solid #6366f1; border-radius: 4px;">
                <?php
                // Display current theme information
                $selected_theme = ATMCEVNTS_Theme_Manager::get_selected_theme();
                $theme_config = ATMCEVNTS_Theme_Manager::get_theme_config($selected_theme);
                ?>
                <table class="form-table" style="margin-top: 0px;">
                    <tr style="line-height: 1;">
                        <th scope="row" style="width: 150px; padding: 2px 0;">Selected Theme:</th>
                        <td style="padding: 2px 0;">
                            <strong><?php echo esc_html(ucfirst($selected_theme)); ?></strong>
                            <?php if (!ATMCEVNTS_Theme_Manager::theme_exists($selected_theme)): ?>
                                <span style="color: #d63638; margin-left: 10px;">
                                    <span class="dashicons dashicons-warning"></span> 
                                    Theme not found - using default
                                </span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php if ($theme_config && isset($theme_config['name'])): ?>
                    <tr style="line-height: 1;">
                        <th scope="row" style="padding: 2px 0;">Theme Name:</th>
                        <td style="padding: 2px 0;"><?php echo esc_html($theme_config['name']); ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if ($theme_config && isset($theme_config['description'])): ?>
                    <tr style="line-height: 1;">
                        <th scope="row" style="padding: 2px 0;">Description:</th>
                        <td style="padding: 2px 0;"><?php echo esc_html($theme_config['description']); ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if ($theme_config && isset($theme_config['version'])): ?>
                    <tr style="line-height: 1;">
                        <th scope="row" style="padding: 2px 0;">Version:</th>
                        <td style="padding: 2px 0;"><?php echo esc_html($theme_config['version']); ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if ($theme_config && isset($theme_config['author'])): ?>
                    <tr style="line-height: 1;">
                        <th scope="row" style="padding: 2px 0;">Author:</th>
                        <td style="padding: 2px 0;"><?php echo esc_html($theme_config['author']); ?></td>
                    </tr>
                    <?php endif; ?>
                    <tr style="line-height: 1;">
                        <th scope="row" style="padding: 2px 0;">Configuration File:</th>
                        <td style="padding: 2px 0;">
                            <?php
                            $child_config = get_stylesheet_directory() . '/atomic-events/atomic-events-settings.yml';
                            $parent_config = get_template_directory() . '/atomic-events/atomic-events-settings.yml';
                            
                            if (file_exists($child_config)) {
                                echo '<code>' . esc_html(str_replace(get_stylesheet_directory(), 'child-theme', $child_config)) . '</code>';
                                echo ' <span style="color: #00a32a;">✓ Found</span>';
                            } elseif (file_exists($parent_config)) {
                                echo '<code>' . esc_html(str_replace(get_template_directory(), 'parent-theme', $parent_config)) . '</code>';
                                echo ' <span style="color: #00a32a;">✓ Found</span>';
                            } else {
                                echo '<span style="color: #d63638;">No configuration file found - using default theme</span>';
                            }
                            ?>
                        </td>
                    </tr>
                </table>
            </div>

            <p>
                There are two ways to change the event templates:
            </p>
            <ol>
                <li>
                    <strong>Selecting a prebuilt theme</strong>
                </li>
                <li>
                    <strong>Overwriting template files</strong>
                </li>
            </ol>

            <div class="atomic-events-support-section">
                <h3>1. Selecting a Prebuilt Theme</h3>
                <ol>
                    <li>Create a new file: <code>[wordpress-theme]/atomic-events/atomic-events-settings.yml</code> in your theme directory</li>
                    <li>Add the following content to the file:</li>
                    <pre><code>theme: "default"</code></pre>
                    <li>Change <code>theme: "default"</code> to your preferred theme. Example: theme: "hydrogen" or theme: "hydrogen-dark"</li>
                    <li>Refresh this page to verify</li>
                </ol>
            </div>

            <div class="atomic-events-support-section">
                <h3>2. Overriding a Template File</h3>
                <h4>Example: Override Card Template</h4>
                <p>To override how event cards appear in shortcodes, create:</p>
                <pre><code>[wordpress-theme]/atomic-events/cards/card-item-default.php</code></pre>
                <p>This will override the selected theme's card template for all shortcode displays.</p>
            </div>

            <div class="atomic-events-support-section">
                <h3>Creating a Custom Theme</h3>
                <p>You can override any template in your wordpress theme:</p>
                <p>Templates are loaded in this priority order:</p>
                <ol>
                    <li><strong>Template Override:</strong> <code>[wordpress-theme]/atomic-events/[template-name].php</code></li>
                    <li><strong>Your Selected Theme:</strong> <code>[wordpress-theme]/atomic-events/themes/[selected-atomic-theme]/[template-name].php</code></li>
                    <li><strong>AtomicEvents Theme:</strong> <code>atomic-events/templates/themes/[selected-atomic-theme]/[template-name].php</code></li>
                    <li><strong>AtomicEvents Default Theme:</strong> <code>atomic-events/templates/themes/default/[template-name].php</code></li>
                </ol>
                
                <h4>Complete Template Structure</h4>
                <pre><code>[wordpress-theme]/
└── atomic-events/
    ├── atomic-events-settings.yml          # Make theme selection here
    ├── themes/
    │   ├── [your-custom-atomic-theme]/
    │   │   ├── theme.yaml                  # Custom theme description
    │   │   ├── cards/
    │   │   │   ├── card-item-default.php
    │   │   │   ├── card-item-featured.php
    │   │   │   ├── card-list-header-default.php
    │   │   │   └── card-list-footer-default.php
    │   │   ├── content/
    │   │   │   └── single-event.php
    │   │   └── single/
    │   │       └── single-atomic-event.php
    │   └── [another-atomic-theme]/
    │       └── [same structure]
    ├── cards/                              # Direct overrides (highest priority)
    ├── content/                            # Direct overrides
    └── single/                             # Direct overrides</code></pre>
                
                <h4>Available Templates</h4>
                <ul>
                    <li><strong>Shortcode Templates:</strong> <code>cards/card-item-default.php</code>, <code>cards/card-item-featured.php</code>, etc.</li>
                    <li><strong>Single Event Templates:</strong> <code>single/single-atomic-event.php</code></li>
                    <li><strong>Content Templates:</strong> <code>content/single-event.php</code></li>
                </ul>
                
                <h4>Available Variables in Templates</h4>
                <ul>
                    <li><code>$event</code> - Event model object with all event data</li>
                    <li><code>$header_atts</code> - Header attributes (columns, etc.)</li>
                    <li><code>$counter</code> - Current item number in the list</li>
                    <li><code>$data</code> - Template data object (when using template loader)</li>
                </ul>
            </div>
        </div>
        <?php } elseif ($active_tab === 'dev') { ?>
        <div class="atomic-events-outer">
            <h2><span class="dashicons dashicons-editor-code settings-page-icon"></span> Developer Documentation</h2>
            
            <div class="atomic-events-support-section">
                <h3>Shortcode Usage</h3>
                <p>Use the <code>[atomic-events]</code> shortcode to display events anywhere on your site:</p>
                <ul>
                    <li><strong>Basic Usage:</strong> <code>[atomic-events]</code></li>
                    <li><strong>With Parameters:</strong> <code>[atomic-events filter="future" max="20" columns="3"]</code></li>
                    <li><strong>Featured Events:</strong> <code>[atomic-events featured="true"]</code></li>
                    <li><strong>Past Events:</strong> <code>[atomic-events filter="past" max="10"]</code></li>
                    <li><strong>Custom Layout:</strong> <code>[atomic-events columns="2" order="DESC"]</code></li>
                </ul>
                
                <h4>Available Parameters</h4>
                <ul>
                    <li><code>filter</code> - "future", "past", or "all" (default: "future")</li>
                    <li><code>max</code> - Maximum number of events to display (default: 20)</li>
                    <li><code>columns</code> - Number of columns in grid layout (default: 3)</li>
                    <li><code>featured</code> - "true" or "false" to show only featured events</li>
                    <li><code>order</code> - "ASC" or "DESC" for date ordering</li>
                    <li><code>skip_first_x</code> - Skip the first X events</li>
                    <li><code>skip_first_x_featured</code> - Skip the first X featured events</li>
                </ul>
            </div>

            <div class="atomic-events-support-section">
                <h3>Hooks and Filters</h3>
                <p>The plugin provides hooks and filters for customization:</p>
                
                <h4>Event Query Results Filter</h4>
                <p>Filter the final event results from the EventQueryService:</p>
                <pre><code>add_filter('atomic_events_query_results', function($events, $params) {
    // Modify the array of ATMCEVNTS_Event_Model objects
    // Example: Sort events by venue
    usort($events, function($a, $b) {
        return strcmp($a->get_event_venue(), $b->get_event_venue());
    });
    return $events;
}, 10, 2);</code></pre>
            </div>
        </div>
        <?php } elseif ($active_tab === 'support') { ?>
        <div class="atomic-events-outer">
            <h2><span class="dashicons dashicons-businessman settings-page-icon"></span> Support</h2>
            
            <div class="atomic-events-support-section">
                <h3>Need Help?</h3>
                <p>For support, questions, or feature requests, please contact us:</p>
                <p><strong>Contact:</strong> <a href="https://matyus.me" target="_blank">matyus.me</a></p>
            </div>
        </div>
        <?php } ?>
    </div>
    <?php
}
}
