<?php

/**
 * HTML Sitemap Widget
 *
 * @package ProRank\SEO\Widgets
 * @since   0.1.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Widgets;

use ProRank\SEO\Core\Config\Settings;
use WP_Widget;

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


/**
 * Class HtmlSitemapWidget
 * 
 * Widget for displaying HTML sitemap
 */


class HtmlSitemapWidget extends WP_Widget {
    /**
     * Constructor
     */
    public function __construct() {
        parent::__construct(
            'prorank_html_sitemap',
            __('ProRank HTML Sitemap', 'prorank-seo'),
            [
                'description' => __('Display an HTML sitemap of your site', 'prorank-seo'),
                'customize_selective_refresh' => true,
            ]
        );
    }

    /**
     * Widget output
     *
     * @param array $args     Widget arguments
     * @param array $instance Widget instance
     * @return void
     */
    public function widget($args, $instance) {
        $stored_title = (string) Settings::get('modules.html_sitemap.widget_title', '');
        $default_title = $stored_title !== '' ? $stored_title : __('Sitemap', 'prorank-seo');

        $stored_sections = Settings::get('modules.html_sitemap.widget_sections', ['pages', 'posts']);
        $default_sections = is_array($stored_sections) && !empty($stored_sections) ? $stored_sections : ['pages', 'posts'];
        $default_include = implode(',', array_filter(array_map('sanitize_key', $default_sections)));
        if ($default_include === '') {
            $default_include = 'pages,posts';
        }

        $title = !empty($instance['title']) ? $instance['title'] : $default_title;
        $title = apply_filters('widget_title', $title, $instance, $this->id_base);

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Widget args contain HTML
		echo wp_kses_post( $args['before_widget'] ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

        if ($title) {
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Widget args contain HTML
            echo $args['before_title'] . esc_html($title) . $args['after_title'];
        }

        // Build shortcode attributes
        $shortcode_atts = [
            'include' => $instance['include'] ?? $default_include,
            'exclude' => $instance['exclude'] ?? '',
            'depth' => $instance['depth'] ?? '0',
            'show_date' => !empty($instance['show_date']) ? 'true' : 'false',
            'style' => $instance['style'] ?? 'list',
            'heading_tag' => 'h4',
            'class' => 'widget-sitemap',
        ];

        $shortcode = '[prorank_sitemap';
        foreach ($shortcode_atts as $key => $value) {
            $shortcode .= ' ' . $key . '="' . esc_attr($value) . '"';
        }
        $shortcode .= ']';

        echo do_shortcode($shortcode);

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Widget args contain HTML
		echo wp_kses_post( $args['after_widget'] ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    }

    /**
     * Widget settings form
     *
     * @param array $instance Widget instance
     * @return void
     */
    public function form($instance) {
        $stored_title = (string) Settings::get('modules.html_sitemap.widget_title', '');
        $default_title = $stored_title !== '' ? $stored_title : __('Sitemap', 'prorank-seo');

        $stored_sections = Settings::get('modules.html_sitemap.widget_sections', ['pages', 'posts']);
        $default_sections = is_array($stored_sections) && !empty($stored_sections) ? $stored_sections : ['pages', 'posts'];
        $default_include = implode(',', array_filter(array_map('sanitize_key', $default_sections)));
        if ($default_include === '') {
            $default_include = 'pages,posts';
        }

        $title = $instance['title'] ?? $default_title;
        $include = $instance['include'] ?? $default_include;
        $exclude = $instance['exclude'] ?? '';
        $depth = $instance['depth'] ?? 0;
        $show_date = $instance['show_date'] ?? false;
        $style = $instance['style'] ?? 'list';
        ?>
        
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('title')); ?>">
                <?php esc_html_e('Title:', 'prorank-seo'); ?>
            </label>
            <input 
                class="widefat" 
                id="<?php echo esc_attr($this->get_field_id('title')); ?>" 
                name="<?php echo esc_attr($this->get_field_name('title')); ?>" 
                type="text" 
                value="<?php echo esc_attr($title); ?>"
            />
        </p>

        <p>
            <label for="<?php echo esc_attr($this->get_field_id('include')); ?>">
                <?php esc_html_e('Include:', 'prorank-seo'); ?>
            </label>
            <input 
                class="widefat" 
                id="<?php echo esc_attr($this->get_field_id('include')); ?>" 
                name="<?php echo esc_attr($this->get_field_name('include')); ?>" 
                type="text" 
                value="<?php echo esc_attr($include); ?>"
                placeholder="pages,posts,categories,tags"
            />
            <small><?php esc_html_e('Comma-separated list of content types', 'prorank-seo'); ?></small>
        </p>

        <p>
            <label for="<?php echo esc_attr($this->get_field_id('exclude')); ?>">
                <?php esc_html_e('Exclude:', 'prorank-seo'); ?>
            </label>
            <input 
                class="widefat" 
                id="<?php echo esc_attr($this->get_field_id('exclude')); ?>" 
                name="<?php echo esc_attr($this->get_field_name('exclude')); ?>" 
                type="text" 
                value="<?php echo esc_attr($exclude); ?>"
                placeholder="authors"
            />
            <small><?php esc_html_e('Comma-separated list of content types to exclude', 'prorank-seo'); ?></small>
        </p>

        <p>
            <label for="<?php echo esc_attr($this->get_field_id('depth')); ?>">
                <?php esc_html_e('Depth:', 'prorank-seo'); ?>
            </label>
            <input 
                class="small-text" 
                id="<?php echo esc_attr($this->get_field_id('depth')); ?>" 
                name="<?php echo esc_attr($this->get_field_name('depth')); ?>" 
                type="number" 
                value="<?php echo esc_attr($depth); ?>"
                min="0"
                max="10"
            />
            <small><?php esc_html_e('0 = all levels', 'prorank-seo'); ?></small>
        </p>

        <p>
            <label for="<?php echo esc_attr($this->get_field_id('style')); ?>">
                <?php esc_html_e('Style:', 'prorank-seo'); ?>
            </label>
            <select 
                class="widefat" 
                id="<?php echo esc_attr($this->get_field_id('style')); ?>" 
                name="<?php echo esc_attr($this->get_field_name('style')); ?>"
            >
                <option value="list" <?php selected($style, 'list'); ?>><?php esc_html_e('List', 'prorank-seo'); ?></option>
                <option value="grid" <?php selected($style, 'grid'); ?>><?php esc_html_e('Grid', 'prorank-seo'); ?></option>
            </select>
        </p>

        <p>
            <input 
                class="checkbox" 
                type="checkbox" 
                id="<?php echo esc_attr($this->get_field_id('show_date')); ?>" 
                name="<?php echo esc_attr($this->get_field_name('show_date')); ?>" 
                value="1" 
                <?php checked($show_date); ?>
            />
            <label for="<?php echo esc_attr($this->get_field_id('show_date')); ?>">
                <?php esc_html_e('Show dates', 'prorank-seo'); ?>
            </label>
        </p>

        <?php
    }

    /**
     * Update widget settings
     *
     * @param array $new_instance New settings
     * @param array $old_instance Old settings
     * @return array
     */
    public function update($new_instance, $old_instance) {
        $instance = [];
        
        $instance['title'] = !empty($new_instance['title']) ? sanitize_text_field($new_instance['title']) : '';
        $instance['include'] = !empty($new_instance['include']) ? sanitize_text_field($new_instance['include']) : 'pages,posts';
        $instance['exclude'] = !empty($new_instance['exclude']) ? sanitize_text_field($new_instance['exclude']) : '';
        $instance['depth'] = !empty($new_instance['depth']) ? absint($new_instance['depth']) : 0;
        $instance['show_date'] = !empty($new_instance['show_date']);
        $instance['style'] = !empty($new_instance['style']) ? sanitize_text_field($new_instance['style']) : 'list';
        
        return $instance;
    }
}
