<?php

namespace Wpxero\Marqueex\Traits\PostQuery;

use Elementor\Controls_Manager;

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

/**
 * Reusable Post Query Controls Trait (Free Version)
 *
 * Provides basic query controls and query builder for any Elementor widget.
 * Premium features (Manual Selection, Include/Exclude) are shown as
 * disabled controls with PRO badges. All premium logic lives in marqueex-pro.
 *
 * Usage:
 *   use PostQueryControls;
 *   // Inside register_controls():
 *   $this->register_query_controls();
 *   // Inside render():
 *   $args = $this->get_query_args( $this->get_settings_for_display() );
 */
trait PostQueryControls {

    // ─── Helpers ─────────────────────────────────────────────────

    /**
     * Get available public post types for the Source dropdown
     */
    protected function get_post_types_options() {
        $post_types = get_post_types(['public' => true], 'objects');
        $options    = [];
        $ignore     = ['elementor_library', 'attachment'];

        foreach ($post_types as $post_type) {
            if (!in_array($post_type->name, $ignore, true)) {
                $options[$post_type->name] = $post_type->label;
            }
        }

        return $options;
    }

    // ─── PRO Badge Markup ────────────────────────────────────────

    /**
     * Build a locked-feature card shown to free users
     *
     * Mimics the Elementor Pro "Display Conditions" lock style:
     * lock icon + label + PRO pill + description + Upgrade button.
     *
     * @param string   $title       Feature title
     * @param string   $description Short description
     * @param string[] $bullets     Optional feature bullets
     * @return string  HTML
     */
    private function get_pro_locked_card($title, $description, $bullets = []) {
        $html  = '<div style="background:#f8f8f9;border:1px solid #d5d8dc;border-radius:4px;padding:14px;margin:8px 0 4px;">';

        // Header: lock + title + PRO badge
        $html .= '<div style="display:flex;align-items:center;gap:6px;margin-bottom:4px;">';
        $html .= '<i class="eicon-lock" style="color:#93003c;font-size:14px;"></i>';
        $html .= '<span style="font-weight:600;color:#495157;font-size:13px;">' . esc_html($title) . '</span>';
        $html .= '<span style="background:#93003c;color:#fff;font-size:9px;padding:2px 6px;'
            . 'border-radius:3px;font-weight:700;letter-spacing:.5px;">PRO</span>';
        $html .= '</div>';

        // Description
        $html .= '<p style="color:#6d7882;font-size:12px;margin:4px 0 0;line-height:1.5;">'
            . esc_html($description) . '</p>';

        // Bullet list
        if (!empty($bullets)) {
            $html .= '<ul style="margin:8px 0 0;padding:0;list-style:none;">';
            foreach ($bullets as $item) {
                $html .= '<li style="color:#6d7882;font-size:11px;padding:2px 0;'
                    . 'display:flex;align-items:center;gap:4px;">'
                    . '<span style="color:#93003c;">&#10022;</span> '
                    . esc_html($item) . '</li>';
            }
            $html .= '</ul>';
        }

        // Upgrade button
        $html .= '<a href="https://wpxero.com/plugins/marqueex/pricing/" target="_blank" '
            . 'style="display:inline-block;background:#93003c;color:#fff;padding:7px 16px;'
            . 'border-radius:3px;font-size:12px;font-weight:600;text-decoration:none;margin-top:10px;">'
            . esc_html__('Upgrade Now', 'marqueex') . '</a>';

        $html .= '</div>';

        return $html;
    }

    // ─── Controls Registration ───────────────────────────────────

    /**
     * Register query controls
     *
     * Call this inside your widget's register_controls() method.
     * Registers:
     *  - Basic controls (free)
     *  - Disabled PRO placeholders (when marqueex-pro is not active)
     *  - Hook for marqueex-pro to inject working premium controls
     */
    protected function register_query_controls() {
        $this->start_controls_section(
            'query_section',
            ['label' => __('Query', 'marqueex')]
        );

        // ── Posts per page ──
        $this->add_control(
            'posts_per_page',
            [
                'label'   => __('Number of Posts', 'marqueex'),
                'type'    => Controls_Manager::NUMBER,
                'default' => 6,
                'min'     => 1,
                'max'     => 50,
            ]
        );

        // ── Source (post types only in free) ──
        $this->add_control(
            'posts_source',
            [
                'label'   => __('Source', 'marqueex'),
                'type'    => Controls_Manager::SELECT,
                'options' => $this->get_post_types_options(),
                'default' => 'post',
            ]
        );

        // ── PRO Placeholders (disabled badges) ──
        // Use the canonical premium check (pro plugin loaded AND valid license).
        $is_pro_active = class_exists('\\Wpxero\\Marqueex\\MarqueeX')
            && \Wpxero\Marqueex\MarqueeX::is_premium_active();

        if (!$is_pro_active) {
            // Manual Selection — locked
            $this->add_control(
                'pro_manual_selection_notice',
                [
                    'type'            => Controls_Manager::RAW_HTML,
                    'raw'             => $this->get_pro_locked_card(
                        __('Manual Selection', 'marqueex'),
                        __('Hand-pick specific posts to display in your marquee.', 'marqueex')
                    ),
                    'content_classes' => 'marqueex-pro-locked-control',
                ]
            );

            // Include / Exclude — locked
            $this->add_control(
                'pro_include_exclude_notice',
                [
                    'type'            => Controls_Manager::RAW_HTML,
                    'raw'             => $this->get_pro_locked_card(
                        __('Include / Exclude', 'marqueex'),
                        __('Advanced post filtering with include and exclude options.', 'marqueex'),
                        [
                            __('Filter by Authors', 'marqueex'),
                            __('Filter by Terms (Categories, Tags)', 'marqueex'),
                            __('Exclude Current Post', 'marqueex'),
                            __('Exclude Specific Posts', 'marqueex'),
                        ]
                    ),
                    'content_classes' => 'marqueex-pro-locked-control',
                ]
            );
        }

        /**
         * Hook for marqueex-pro to inject premium controls.
         *
         * When Pro is active the placeholders above are skipped and
         * this action registers the real working controls instead:
         *  - manual_selection option added to posts_source
         *  - posts_selected_ids  (post picker)
         *  - Include / Exclude tabs (authors, terms)
         *
         * @param \Elementor\Widget_Base $widget
         */
        do_action('marqueex/query/premium_controls', $this);

        // ── Basic Controls ──
        $this->add_control(
            'posts_divider',
            ['type' => Controls_Manager::DIVIDER]
        );

        $this->add_control(
            'posts_offset',
            [
                'label'     => __('Offset', 'marqueex'),
                'type'      => Controls_Manager::NUMBER,
                'default'   => 0,
                'condition' => ['posts_source!' => 'manual_selection'],
            ]
        );

        $this->add_control(
            'posts_select_date',
            [
                'label'     => __('Date', 'marqueex'),
                'type'      => Controls_Manager::SELECT,
                'default'   => 'anytime',
                'options'   => [
                    'anytime' => __('All', 'marqueex'),
                    'today'   => __('Past Day', 'marqueex'),
                    'week'    => __('Past Week', 'marqueex'),
                    'month'   => __('Past Month', 'marqueex'),
                    'quarter' => __('Past Quarter', 'marqueex'),
                    'year'    => __('Past Year', 'marqueex'),
                    'exact'   => __('Custom', 'marqueex'),
                ],
                'condition' => ['posts_source!' => 'manual_selection'],
            ]
        );

        $this->add_control(
            'posts_date_before',
            [
                'label'       => __('Before', 'marqueex'),
                'type'        => Controls_Manager::DATE_TIME,
                'description' => __('Setting a Before date will show all posts published until the chosen date (inclusive).', 'marqueex'),
                'condition'   => [
                    'posts_select_date' => 'exact',
                    'posts_source!'     => 'manual_selection',
                ],
            ]
        );

        $this->add_control(
            'posts_date_after',
            [
                'label'       => __('After', 'marqueex'),
                'type'        => Controls_Manager::DATE_TIME,
                'description' => __('Setting an After date will show all posts published since the chosen date (inclusive).', 'marqueex'),
                'condition'   => [
                    'posts_select_date' => 'exact',
                    'posts_source!'     => 'manual_selection',
                ],
            ]
        );

        $this->add_control(
            'posts_orderby',
            [
                'label'   => __('Order By', 'marqueex'),
                'type'    => Controls_Manager::SELECT,
                'default' => 'date',
                'options' => [
                    'title'         => __('Title', 'marqueex'),
                    'ID'            => __('ID', 'marqueex'),
                    'date'          => __('Date', 'marqueex'),
                    'author'        => __('Author', 'marqueex'),
                    'comment_count' => __('Comment Count', 'marqueex'),
                    'menu_order'    => __('Menu Order', 'marqueex'),
                    'modified'      => __('Last Modified', 'marqueex'),
                    'rand'          => __('Random', 'marqueex'),
                ],
            ]
        );

        $this->add_control(
            'posts_order',
            [
                'label'   => __('Order', 'marqueex'),
                'type'    => Controls_Manager::SELECT,
                'default' => 'desc',
                'options' => [
                    'asc'  => __('ASC', 'marqueex'),
                    'desc' => __('DESC', 'marqueex'),
                ],
            ]
        );

        $this->add_control(
            'posts_ignore_sticky_posts',
            [
                'label'        => __('Ignore Sticky Posts', 'marqueex'),
                'type'         => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default'      => 'yes',
                'condition'    => ['posts_source' => 'post'],
            ]
        );

        $this->add_control(
            'posts_only_with_featured_image',
            [
                'label'        => __('Only Featured Image Post', 'marqueex'),
                'description'  => __('Enable to display posts only when featured image is present.', 'marqueex'),
                'type'         => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'condition'    => ['posts_source!' => 'manual_selection'],
            ]
        );

        $this->end_controls_section();
    }

    // ─── Query Builder ───────────────────────────────────────────

    /**
     * Build WP_Query arguments from widget settings (free version)
     *
     * Handles basic parameters only. Premium logic (manual selection,
     * include/exclude) is applied by marqueex-pro via the
     * `marqueex/query/args` filter.
     *
     * @param array $settings Widget settings from get_settings_for_display()
     * @return array WP_Query compatible arguments
     */
    protected function get_query_args($settings = []) {
        $settings = wp_parse_args($settings, [
            'posts_per_page'                 => 6,
            'posts_source'                   => 'post',
            'posts_offset'                   => 0,
            'posts_select_date'              => 'anytime',
            'posts_date_before'              => '',
            'posts_date_after'               => '',
            'posts_orderby'                  => 'date',
            'posts_order'                    => 'desc',
            'posts_ignore_sticky_posts'      => 'yes',
            'posts_only_with_featured_image' => '',
            'post_categories'                => [],
        ]);

        $posts_per_page = min(50, max(1, intval($settings['posts_per_page'])));
        $post_source    = sanitize_text_field($settings['posts_source']);

        $args = [
            'post_status'    => 'publish',
            'posts_per_page' => $posts_per_page,
            'no_found_rows'  => true,
            'post_type'      => $post_source ?: 'post',
        ];

        // Ignore sticky posts
        if ($post_source === 'post' && $settings['posts_ignore_sticky_posts'] === 'yes') {
            $args['ignore_sticky_posts'] = true;
        }

        // Backward compat: old post_categories setting
        if (!empty($settings['post_categories'])) {
            $category_ids = array_map('intval', (array) $settings['post_categories']);
            $category_ids = array_filter($category_ids, function ($id) {
                return $id > 0;
            });
            if (!empty($category_ids)) {
                $args['category__in'] = $category_ids;
            }
        }

        // Order
        $args['orderby'] = sanitize_text_field($settings['posts_orderby']);
        $args['order']   = strtoupper(sanitize_text_field($settings['posts_order']));

        // Offset
        if (!empty($settings['posts_offset']) && intval($settings['posts_offset']) > 0) {
            $args['offset'] = intval($settings['posts_offset']);
        }

        // Only with featured image
        if ($settings['posts_only_with_featured_image'] === 'yes') {
            $args['meta_key'] = '_thumbnail_id';
        }

        // Date filter
        $selected_date = $settings['posts_select_date'];
        if (!empty($selected_date) && $selected_date !== 'anytime') {
            $date_query = [];
            switch ($selected_date) {
                case 'today':
                    $date_query['after'] = '-1 day';
                    break;
                case 'week':
                    $date_query['after'] = '-1 week';
                    break;
                case 'month':
                    $date_query['after'] = '-1 month';
                    break;
                case 'quarter':
                    $date_query['after'] = '-3 month';
                    break;
                case 'year':
                    $date_query['after'] = '-1 year';
                    break;
                case 'exact':
                    if (!empty($settings['posts_date_after'])) {
                        $date_query['after'] = $settings['posts_date_after'];
                    }
                    if (!empty($settings['posts_date_before'])) {
                        $date_query['before'] = $settings['posts_date_before'];
                    }
                    $date_query['inclusive'] = true;
                    break;
            }
            if (!empty($date_query)) {
                $args['date_query'] = $date_query;
            }
        }

        /**
         * Filter query arguments.
         *
         * marqueex-pro hooks here to apply premium logic:
         *  - Manual selection (post__in, post_type = any)
         *  - Include by authors / terms
         *  - Exclude by posts / authors / terms / current post
         *
         * @param array              $args     WP_Query arguments
         * @param array              $settings Widget settings
         * @param \Elementor\Widget_Base $widget  Current widget instance
         */
        return apply_filters('marqueex/query/args', $args, $settings, $this);
    }
}
