<?php
/**
 * Categories Widget.
 *
 * @package    Edocman_Lite
 * @subpackage Edocman_Lite/includes
 */

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

class Edocman_Lite_Categories_Widget extends WP_Widget {

    /**
     * Allowed values for show_image setting.
     *
     * @var array
     */
    private static $allowed_show_image = array( 'yes', 'no' );

    /**
     * Constructor.
     */
    public function __construct() {
        parent::__construct(
            'edocman_lite_categories_widget',
            __( 'Edocman Lite Categories', 'edocman-lite' ),
            array(
                'description' => __( 'Display categories from Edocman Lite plugin', 'edocman-lite' ),
                'classname'   => 'edocman-lite-categories-widget',
            )
        );
    }

    /**
     * Front-end display of widget.
     *
     * @param array $args     Widget display arguments.
     * @param array $instance Saved widget settings.
     */
    public function widget( $args, $instance ) {
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $args['before_widget'];

        if ( ! empty( $instance['title'] ) ) {
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
        }

        $limit      = ! empty( $instance['limit'] )      ? absint( $instance['limit'] )      : 5;
        $show_image = ! empty( $instance['show_image'] ) ? $instance['show_image']            : 'yes';
        $parent_id  = ! empty( $instance['parent_id'] )  ? absint( $instance['parent_id'] )  : 0;

        // ✅ Validate show_image — chỉ chấp nhận 'yes' hoặc 'no'.
        if ( ! in_array( $show_image, self::$allowed_show_image, true ) ) {
            $show_image = 'yes';
        }

        $database   = new Edocman_Lite_Database();
        $categories = $database->get_categories( $parent_id, true );

        if ( $limit > 0 && count( $categories ) > $limit ) {
            $categories = array_slice( $categories, 0, $limit );
        }

        // ✅ Build image base URL từ config — không dùng $category->image trực tiếp làm URL.
        $upload_dir     = wp_upload_dir();
        $documents_path = Edocman_Lite_Helper::get_config( 'documents_path', $upload_dir['basedir'] . '/edocman-lite' );
        $documents_url  = str_replace(
            wp_normalize_path( $upload_dir['basedir'] ),
            $upload_dir['baseurl'],
            wp_normalize_path( $documents_path )
        );

        if ( ! empty( $categories ) ) {
            echo '<ul class="edocman-lite-widget-categories">';

            foreach ( $categories as $category ) {
                echo '<li class="category-item">';

                if ( 'yes' === $show_image && ! empty( $category->image ) ) {
                    $category_image_url = rtrim( $documents_url, '/' ) . '/categories/thumb/' . ltrim( $category->image, '/' );
                    echo '<div class="category-image">';
                    echo '<img src="' . esc_url( $category_image_url ) . '" alt="' . esc_attr( $category->title ) . '">';
                    echo '</div>';
                }

                echo '<a href="' . esc_url( add_query_arg( 'cat_id', $category->id, get_permalink() ) ) . '">';
                echo esc_html( $category->title );
                echo '</a>';

                echo '</li>';
            }

            echo '</ul>';
        } else {
            echo '<p class="edocman-lite-widget-no-items">' . esc_html__( 'No categories found.', 'edocman-lite' ) . '</p>';
        }

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $args['after_widget'];
    }

    /**
     * Back-end widget form.
     *
     * @param array $instance Previously saved values from database.
     */
    public function form( $instance ) {
        $title      = ! empty( $instance['title'] )      ? $instance['title']      : __( 'Document Categories', 'edocman-lite' );
        $limit      = ! empty( $instance['limit'] )      ? $instance['limit']      : 5;
        $show_image = ! empty( $instance['show_image'] ) ? $instance['show_image'] : 'yes';
        $parent_id  = ! empty( $instance['parent_id'] )  ? $instance['parent_id']  : 0;
        ?>

        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>">
                <?php esc_html_e( 'Title:', 'edocman-lite' ); ?>
            </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( 'limit' ) ); ?>">
                <?php esc_html_e( 'Number of categories to show:', 'edocman-lite' ); ?>
            </label>
            <input class="tiny-text"
                   id="<?php echo esc_attr( $this->get_field_id( 'limit' ) ); ?>"
                   name="<?php echo esc_attr( $this->get_field_name( 'limit' ) ); ?>"
                   type="number"
                   step="1"
                   min="0"
                   value="<?php echo absint( $limit ); ?>"
                   size="3">
        </p>

        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'show_image' ) ); ?>">
                <?php esc_html_e( 'Show images:', 'edocman-lite' ); ?>
            </label>
            <select class="widefat"
                    id="<?php echo esc_attr( $this->get_field_id( 'show_image' ) ); ?>"
                    name="<?php echo esc_attr( $this->get_field_name( 'show_image' ) ); ?>">
                <option value="yes" <?php selected( $show_image, 'yes' ); ?>><?php esc_html_e( 'Yes', 'edocman-lite' ); ?></option>
                <option value="no"  <?php selected( $show_image, 'no' ); ?>><?php esc_html_e( 'No', 'edocman-lite' ); ?></option>
            </select>
        </p>

        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'parent_id' ) ); ?>">
                <?php esc_html_e( 'Parent category:', 'edocman-lite' ); ?>
            </label>
            <select class="widefat"
                    id="<?php echo esc_attr( $this->get_field_id( 'parent_id' ) ); ?>"
                    name="<?php echo esc_attr( $this->get_field_name( 'parent_id' ) ); ?>">
                <option value="0"><?php esc_html_e( 'Root categories', 'edocman-lite' ); ?></option>
                <?php
                $database       = new Edocman_Lite_Database();
                $all_categories = $database->get_categories( 0, false );
                foreach ( $all_categories as $cat ) {
                    echo '<option value="' . absint( $cat->id ) . '" ' . selected( $parent_id, $cat->id, false ) . '>';
                    echo esc_html( $cat->title );
                    echo '</option>';
                }
                ?>
            </select>
        </p>

        <?php
    }

    /**
     * Sanitize widget form values as they are saved.
     *
     * @param array $new_instance New settings for this instance.
     * @param array $old_instance Old settings for this instance.
     * @return array Sanitized settings.
     */
    public function update( $new_instance, $old_instance ) {
        $instance = array();

        $instance['title']    = ! empty( $new_instance['title'] )
            ? sanitize_text_field( $new_instance['title'] )
            : '';

        $instance['limit']    = ! empty( $new_instance['limit'] )
            ? absint( $new_instance['limit'] )
            : 5;

        // ✅ Validate show_image — chỉ lưu 'yes' hoặc 'no'.
        $instance['show_image'] = ( ! empty( $new_instance['show_image'] ) && in_array( $new_instance['show_image'], self::$allowed_show_image, true ) )
            ? $new_instance['show_image']
            : 'yes';

        $instance['parent_id'] = ! empty( $new_instance['parent_id'] )
            ? absint( $new_instance['parent_id'] )
            : 0;

        return $instance;
    }
}
