<?php

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

use Elementor\Controls_Manager;
use Elementor\Plugin;
use Elementor\Widget_Base;

/**
 * Elementor Proofwp Widget.
 *
 * Elementor widget for displaying a Proofwp widget.
 *
 * @since 1.0.0
 */
class DSProofwp_Widget extends Widget_Base
{

    /**
     * Get widget name.
     *
     * Retrieve Proofwp widget name.
     *
     * @since 1.0.0
     * @access public
     * @return string Widget name.
     */
    public function get_name()
    {
        return 'dsproofwp_widget';
    }

    /**
     * Get widget title.
     *
     * Retrieve Proofwp widget title.
     *
     * @since 1.0.0
     * @access public
     * @return string Widget title.
     */
    public function get_title()
    {
        return esc_html__('Proofwp', 'proofwp');
    }

    /**
     * Get widget icon.
     *
     * Retrieve Proofwp widget icon.
     *
     * @since 1.0.0
     * @access public
     * @return string Widget icon.
     */
    public function get_icon()
    {
        return 'dsproofwp-icon';
    }

    /**
     * Get widget categories.
     *
     * Retrieve the list of categories the Proofwp widget belongs to.
     *
     * @since 1.0.0
     * @access public
     * @return array Widget categories.
     */
    public function get_categories()
    {
        return ['general'];
    }

    /**
     * Get widget script dependencies.
     *
     * Retrieve the list of script handles the widget depends on.
     *
     * @since 1.0.0
     * @access public
     * @return array Widget script handles.
     */
    public function get_script_depends()
    {
        return [];
    }

    /**
     * Get widget style dependencies.
     *
     * Retrieve the list of style handles the widget depends on.
     *
     * @since 1.0.0
     * @access public
     * @return array Widget style handles.
     */
    public function get_style_depends()
    {
        return [];
    }

    /**
     * Register Proofwp widget controls.
     *
     * Add input fields to allow the user to customize the widget settings.
     *
     * @since 1.0.0
     * @access protected
     */
    protected function register_controls()
    {
        $this->start_controls_section(
            'dsproofwp_content_section',
            [
                'label' => esc_html__('Content', 'proofwp'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'dsproofwp_selected_widget',
            [
                'label' => esc_html__('Widget', 'proofwp'),
                'type' => Controls_Manager::SELECT2,
                'options' => $this->get_widgets(),
                'default' => '',
                'select2options' => [
                    'placeholder' => esc_html__('-- Select a Widget --', 'proofwp'),
                    'allowClear' => true,
                ],
            ]
        );

        $this->add_control(
            'preview_notice',
            [
                'type' => Controls_Manager::NOTICE,
                'heading' => esc_html__('Live preview is limited', 'proofwp'),
                'content' => esc_html__('The selected widget will render on the live page. Save and preview the page to verify the final output.', 'proofwp'),
                'show_icon' => true,
                'notice_type' => 'info',
                'condition' => [
                    'dsproofwp_selected_widget!' => '',
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Render Proofwp widget output on the frontend.
     *
     * Written in PHP and used to generate the final HTML.
     *
     * @since 1.0.0
     * @access protected
     */
    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $selected_widget = isset($settings['dsproofwp_selected_widget']) ? explode('-', $settings['dsproofwp_selected_widget']) : array();
        $widget_id       = isset($selected_widget[0]) ? absint($selected_widget[0]) : 0;
        $widget_type     = isset($selected_widget[1]) ? sanitize_key($selected_widget[1]) : '';

        if ($widget_id < 1) {
            if (Plugin::$instance->editor->is_edit_mode()) {
                echo '<div class="dsproofwp-elementor-container">' .
                    esc_html__('Please select a widget to display.', 'proofwp') .
                    '</div>';
            }
            return;
        }

        if ('' === $widget_type) {
            if (Plugin::$instance->editor->is_edit_mode()) {
                echo '<div class="dsproofwp-elementor-container">' .
                    esc_html__('The selected widget is missing a valid widget type.', 'proofwp') .
                    '</div>';
            }
            return;
        }

        echo do_shortcode('[proofwp id="' . esc_attr((string) $widget_id) . '" wt="' . esc_attr($widget_type) . '"]');
    }

    private function get_widgets()
    {
        if (!current_user_can('manage_options')) {
            return ['' => esc_html__('You do not have permission to view widgets.', 'proofwp')];
        }

        $endpoint = '/dsproofwp/v1/widgets';

        if (
            class_exists('DSProofwp_Plugin')
            && method_exists('DSProofwp_Plugin', 'is_license_active')
            && method_exists('DSProofwp_Plugin', 'is_pro_active')
            && DSProofwp_Plugin::is_license_active()
            && DSProofwp_Plugin::is_pro_active()
        ) {
            $endpoint = '/dsproofwp/v1/widgets-pro';
        }

        $request = new \WP_REST_Request('GET', $endpoint);
        $request->set_param('per_page', '999');
        $response = rest_do_request($request);

        if ($response->is_error()) {
            return ['' => esc_html__('Error loading widgets.', 'proofwp')];
        }

        $data = $response->get_data();
        $items = isset($data['items']) && is_array($data['items']) ? $data['items'] : [];

        if (empty($items)) {
            return ['' => esc_html__('No widgets found.', 'proofwp')];
        }

        $options = [];
        foreach ($items as $widget) {
            if (isset($widget['id']) && isset($widget['title'])) {
                $options[$widget['id'] . '-' . $widget['widget_type']] = (string) $widget['title'];
            }
        }

        return $options;
    }
}
