<?php
/**
 * Biscotti Elementor Widgets
 * 
 * Provides Elementor widgets for all Biscotti shortcodes:
 * - Cookie Table
 * - Consent Link
 * - Settings Link
 * - Data Export
 * - Do Not Sell (CCPA)
 * - Impressum
 * - Privacy Policy
 * - Cookie Policy
 * 
 * IMPORTANT: All classes extending \Elementor\Widget_Base MUST be defined
 * inside the plugins_loaded callback to avoid fatal errors when Elementor
 * is not installed or not yet loaded.
 */

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

// Guard: Only define Elementor widget classes if Elementor is fully loaded.
// Using class_exists() is the ONLY safe check — did_action('elementor/loaded')
// can return true before classes are autoloaded, causing fatal errors.
if (!class_exists('\\Elementor\\Widget_Base')) {
    return; // Elementor not installed or not loaded yet — skip entirely
}

// =========================================================================
// MANAGER CLASS (hooks into Elementor registration)
// =========================================================================
class Biscotti_Elementor_Widgets
{
    private static $instance = null;

    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __construct()
    {
        add_action('elementor/widgets/register', [$this, 'register_widgets']);
        add_action('elementor/elements/categories_registered', [$this, 'add_widget_category']);
    }

    public function add_widget_category($elements_manager)
    {
        $elements_manager->add_category('biscotti', [
            'title' => esc_html__('Biscotti CMP', 'biscotti-cmp'),
            'icon' => 'fa fa-cookie',
        ]);
    }

    public function register_widgets($widgets_manager)
    {
        $widgets_manager->register(new Biscotti_Cookie_Table_Widget());
        $widgets_manager->register(new Biscotti_Consent_Link_Widget());
        $widgets_manager->register(new Biscotti_Settings_Link_Widget());
        $widgets_manager->register(new Biscotti_Data_Export_Widget());
        $widgets_manager->register(new Biscotti_Do_Not_Sell_Widget());
        $widgets_manager->register(new Biscotti_Impressum_Widget());
        $widgets_manager->register(new Biscotti_Privacy_Policy_Widget());
        $widgets_manager->register(new Biscotti_Cookie_Policy_Widget());
    }
}

// =========================================================================
// BASE WIDGET CLASS
// =========================================================================
class Biscotti_Widget_Base extends \Elementor\Widget_Base
{
    protected $shortcode_name = '';
    protected $widget_name = '';
    protected $widget_title = '';
    protected $widget_icon = 'eicon-code';

    public function get_name()
    {
        return 'biscotti_' . $this->widget_name;
    }

    public function get_title()
    {
        // The literal title msgids ("Biscotti Cookie Table", …) are registered for
        // extraction in the Divi/Beaver modules; translate the per-widget value here.
        // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText
        return esc_html__( $this->widget_title, 'biscotti-cmp' );
    }

    public function get_icon()
    {
        return $this->widget_icon;
    }

    public function get_categories()
    {
        return ['biscotti'];
    }

    public function get_keywords()
    {
        return ['biscotti', 'cookie', 'consent', 'gdpr', 'privacy'];
    }

    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $atts = $this->build_shortcode_atts($settings);
        // Shortcode output is escaped within each shortcode's render method
        echo do_shortcode('[' . esc_attr($this->shortcode_name) . $atts . ']');
    }

    protected function build_shortcode_atts($settings)
    {
        return '';
    }
}

// =============================================================================
// COOKIE TABLE WIDGET
// =============================================================================
class Biscotti_Cookie_Table_Widget extends Biscotti_Widget_Base
{
    protected $shortcode_name = 'biscotti_cookies';
    protected $widget_name = 'cookie_table';
    protected $widget_title = 'Biscotti Cookie Table';
    protected $widget_icon = 'eicon-table';

    protected function register_controls()
    {
        $this->start_controls_section('content_section', [
            'label' => esc_html__('Settings', 'biscotti-cmp'),
            'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
        ]);

        $this->add_control('category', [
            'label' => esc_html__('Category', 'biscotti-cmp'),
            'type' => \Elementor\Controls_Manager::SELECT,
            'default' => 'all',
            'options' => [
                'all' => esc_html__('All', 'biscotti-cmp'),
                'essential' => esc_html__('Essential', 'biscotti-cmp'),
                'functional' => esc_html__('Functional', 'biscotti-cmp'),
                'analytics' => esc_html__('Analytics', 'biscotti-cmp'),
                'marketing' => esc_html__('Marketing', 'biscotti-cmp'),
            ],
        ]);

        $this->add_control('show_duration', [
            'label' => esc_html__('Show Duration', 'biscotti-cmp'),
            'type' => \Elementor\Controls_Manager::SWITCHER,
            'default' => 'yes',
        ]);

        $this->add_control('show_provider', [
            'label' => esc_html__('Show Provider', 'biscotti-cmp'),
            'type' => \Elementor\Controls_Manager::SWITCHER,
            'default' => 'yes',
        ]);

        $this->end_controls_section();
    }

    protected function build_shortcode_atts($settings)
    {
        $atts = ' category="' . esc_attr($settings['category']) . '"';
        $atts .= ' show_duration="' . ($settings['show_duration'] === 'yes' ? 'true' : 'false') . '"';
        $atts .= ' show_provider="' . ($settings['show_provider'] === 'yes' ? 'true' : 'false') . '"';
        return $atts;
    }
}

// =============================================================================
// CONSENT LINK WIDGET
// =============================================================================
class Biscotti_Consent_Link_Widget extends Biscotti_Widget_Base
{
    protected $shortcode_name = 'biscotti_consent_link';
    protected $widget_name = 'consent_link';
    protected $widget_title = 'Biscotti Consent Link';
    protected $widget_icon = 'eicon-link';

    protected function register_controls()
    {
        $this->start_controls_section('content_section', [
            'label' => esc_html__('Settings', 'biscotti-cmp'),
            'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
        ]);

        $this->add_control('text', [
            'label' => esc_html__('Link text', 'biscotti-cmp'),
            'type' => \Elementor\Controls_Manager::TEXT,
            'default' => esc_html__('Change cookie settings', 'biscotti-cmp'),
        ]);

        $this->add_control('css_class', [
            'label' => esc_html__('CSS Class', 'biscotti-cmp'),
            'type' => \Elementor\Controls_Manager::TEXT,
            'default' => 'biscotti-consent-link',
        ]);

        $this->end_controls_section();
    }

    protected function build_shortcode_atts($settings)
    {
        $atts = ' text="' . esc_attr($settings['text']) . '"';
        $atts .= ' class="' . esc_attr($settings['css_class']) . '"';
        return $atts;
    }
}

// =============================================================================
// SETTINGS LINK WIDGET
// =============================================================================
class Biscotti_Settings_Link_Widget extends Biscotti_Widget_Base
{
    protected $shortcode_name = 'biscotti_settings_link';
    protected $widget_name = 'settings_link';
    protected $widget_title = 'Biscotti Settings Link';
    protected $widget_icon = 'eicon-settings';

    protected function register_controls()
    {
        $this->start_controls_section('content_section', [
            'label' => esc_html__('Settings', 'biscotti-cmp'),
            'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
        ]);

        $this->add_control('text', [
            'label' => esc_html__('Link text', 'biscotti-cmp'),
            'type' => \Elementor\Controls_Manager::TEXT,
            'default' => esc_html__('Cookie Settings', 'biscotti-cmp'),
        ]);

        $this->add_control('css_class', [
            'label' => esc_html__('CSS Class', 'biscotti-cmp'),
            'type' => \Elementor\Controls_Manager::TEXT,
            'default' => 'biscotti-settings-link',
        ]);

        $this->end_controls_section();
    }

    protected function build_shortcode_atts($settings)
    {
        $atts = ' text="' . esc_attr($settings['text']) . '"';
        $atts .= ' class="' . esc_attr($settings['css_class']) . '"';
        return $atts;
    }
}

// =============================================================================
// DATA EXPORT WIDGET
// =============================================================================
class Biscotti_Data_Export_Widget extends Biscotti_Widget_Base
{
    protected $shortcode_name = 'biscotti_data_export';
    protected $widget_name = 'data_export';
    protected $widget_title = 'Biscotti Data Export';
    protected $widget_icon = 'eicon-download-button';

    protected function register_controls()
    {
        $this->start_controls_section('content_section', [
            'label' => esc_html__('Info', 'biscotti-cmp'),
            'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
        ]);

        $this->add_control('info', [
            'type' => \Elementor\Controls_Manager::RAW_HTML,
            'raw' => esc_html__('This widget displays a GDPR Art. 15 data export button for users.', 'biscotti-cmp'),
        ]);

        $this->end_controls_section();
    }
}

// =============================================================================
// DO NOT SELL WIDGET (CCPA)
// =============================================================================
class Biscotti_Do_Not_Sell_Widget extends Biscotti_Widget_Base
{
    protected $shortcode_name = 'biscotti_do_not_sell';
    protected $widget_name = 'do_not_sell';
    protected $widget_title = 'Biscotti Do Not Sell (CCPA)';
    protected $widget_icon = 'eicon-ban';

    protected function register_controls()
    {
        $this->start_controls_section('content_section', [
            'label' => esc_html__('Settings', 'biscotti-cmp'),
            'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
        ]);

        $this->add_control('text', [
            'label' => esc_html__('Link text', 'biscotti-cmp'),
            'type' => \Elementor\Controls_Manager::TEXT,
            'default' => esc_html__('Do Not Sell My Data', 'biscotti-cmp'),
        ]);

        $this->end_controls_section();
    }

    protected function build_shortcode_atts($settings)
    {
        return ' text="' . esc_attr($settings['text']) . '"';
    }
}

// =============================================================================
// IMPRESSUM WIDGET
// =============================================================================
class Biscotti_Impressum_Widget extends Biscotti_Widget_Base
{
    protected $shortcode_name = 'biscotti_impressum';
    protected $widget_name = 'impressum';
    protected $widget_title = 'Biscotti Impressum';
    protected $widget_icon = 'eicon-document-file';

    protected function register_controls()
    {
        $this->start_controls_section('content_section', [
            'label' => esc_html__('Settings', 'biscotti-cmp'),
            'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
        ]);

        $this->add_control('cache', [
            'label' => esc_html__('Enable Cache', 'biscotti-cmp'),
            'type' => \Elementor\Controls_Manager::SWITCHER,
            'default' => 'yes',
        ]);

        $this->add_control('lang', [
            'label' => esc_html__('Language', 'biscotti-cmp'),
            'type' => \Elementor\Controls_Manager::SELECT,
            'default' => 'auto',
            'options' => Biscotti_Languages::select_options( true, esc_html__( 'Auto (from WordPress)', 'biscotti-cmp' ) ),
        ]);

        $this->end_controls_section();
    }

    protected function build_shortcode_atts($settings)
    {
        $atts = ' cache="' . ($settings['cache'] === 'yes' ? 'true' : 'false') . '"';
        if ($settings['lang'] !== 'auto') {
            $atts .= ' lang="' . esc_attr($settings['lang']) . '"';
        }
        return $atts;
    }
}

// =============================================================================
// PRIVACY POLICY WIDGET
// =============================================================================
class Biscotti_Privacy_Policy_Widget extends Biscotti_Widget_Base
{
    protected $shortcode_name = 'biscotti_privacy_policy';
    protected $widget_name = 'privacy_policy';
    protected $widget_title = 'Biscotti Privacy Policy';
    protected $widget_icon = 'eicon-lock';

    protected function register_controls()
    {
        $this->start_controls_section('content_section', [
            'label' => esc_html__('Settings', 'biscotti-cmp'),
            'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
        ]);

        $this->add_control('cache', [
            'label' => esc_html__('Enable Cache', 'biscotti-cmp'),
            'type' => \Elementor\Controls_Manager::SWITCHER,
            'default' => 'yes',
        ]);

        $this->add_control('lang', [
            'label' => esc_html__('Language', 'biscotti-cmp'),
            'type' => \Elementor\Controls_Manager::SELECT,
            'default' => 'auto',
            'options' => Biscotti_Languages::select_options( true, esc_html__( 'Auto (from WordPress)', 'biscotti-cmp' ) ),
        ]);

        $this->end_controls_section();
    }

    protected function build_shortcode_atts($settings)
    {
        $atts = ' cache="' . ($settings['cache'] === 'yes' ? 'true' : 'false') . '"';
        if ($settings['lang'] !== 'auto') {
            $atts .= ' lang="' . esc_attr($settings['lang']) . '"';
        }
        return $atts;
    }
}

// =============================================================================
// COOKIE POLICY WIDGET
// =============================================================================
class Biscotti_Cookie_Policy_Widget extends Biscotti_Widget_Base
{
    protected $shortcode_name = 'biscotti_cookie_policy';
    protected $widget_name = 'cookie_policy';
    protected $widget_title = 'Biscotti Cookie Policy';
    protected $widget_icon = 'eicon-info-circle';

    protected function register_controls()
    {
        $this->start_controls_section('content_section', [
            'label' => esc_html__('Settings', 'biscotti-cmp'),
            'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
        ]);

        $this->add_control('cache', [
            'label' => esc_html__('Enable Cache', 'biscotti-cmp'),
            'type' => \Elementor\Controls_Manager::SWITCHER,
            'default' => 'yes',
        ]);

        $this->add_control('lang', [
            'label' => esc_html__('Language', 'biscotti-cmp'),
            'type' => \Elementor\Controls_Manager::SELECT,
            'default' => 'auto',
            'options' => Biscotti_Languages::select_options( true, esc_html__( 'Auto (from WordPress)', 'biscotti-cmp' ) ),
        ]);

        $this->end_controls_section();
    }

    protected function build_shortcode_atts($settings)
    {
        $atts = ' cache="' . ($settings['cache'] === 'yes' ? 'true' : 'false') . '"';
        if ($settings['lang'] !== 'auto') {
            $atts .= ' lang="' . esc_attr($settings['lang']) . '"';
        }
        return $atts;
    }
}

// Initialize the widget manager
Biscotti_Elementor_Widgets::get_instance();
