<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp
class AutoToolBox {
    private $title;
    private $img;
    private $content;
    private $link;
    private $active_option_name;
    private $active;
    private $premium;
    private static $modal_initialized = false;

    public function __construct($title, $content, $link, $active_option_name, $active,$img='',$premium=false) {
        $this->title = $title;
        $this->content = $content;
        $this->link = $link;
        $this->active_option_name = $active_option_name;
        $this->active = $active;
        $this->img = $img;
        $this->premium = $premium;
    }

    /**
     * Strip HTML tags and get plain text preview
     */
    private function getContentPreview($content, $length = 100) {
        $plain_text = wp_strip_all_tags($content);
        $plain_text = preg_replace('/\s+/', ' ', $plain_text);
        $plain_text = trim($plain_text);
        
        if (mb_strlen($plain_text) > $length) {
            return mb_substr($plain_text, 0, $length) . '...';
        }
        return $plain_text;
    }

    /**
     * Generate unique modal ID for this box
     */
    private function getModalId() {
        return 'aiautotool_modal_' . sanitize_key($this->active_option_name);
    }

    /**
     * Sanitize title - allow icon tags (<i>) for Font Awesome icons
     * This is safe because we only allow <i> tags with class attribute
     */
    private function sanitizeTitle($title) {
        $allowed_html = array(
            'i' => array(
                'class' => array(),
                'aria-hidden' => array(),
            ),
            'span' => array(
                'class' => array(),
            ),
        );
        return wp_kses($title, $allowed_html);
    }

    /**
     * Extract icon from title if it contains HTML icon
     * Returns array ['icon' => '...', 'text' => '...']
     */
    private function parseTitle($title) {
        // Check if title contains icon HTML
        if (preg_match('/<i[^>]*>.*?<\/i>\s*/i', $title, $matches)) {
            $icon = $matches[0];
            $text = trim(str_replace($icon, '', $title));
            return array(
                'icon' => $this->sanitizeTitle($icon),
                'text' => esc_html($text)
            );
        }
        
        // No icon found, return sanitized text
        return array(
            'icon' => '',
            'text' => esc_html($title)
        );
    }

    public function generateHTML() {
        ?>
        
        <?php
        $modal_id = $this->getModalId();
        $content_preview = $this->getContentPreview($this->content, 100);
        $has_more_content = mb_strlen(wp_strip_all_tags($this->content)) > 100;
        
        // Parse title to extract icon and text
        $parsed_title = $this->parseTitle($this->title);
        $title_with_icon = $parsed_title['icon'] ? $parsed_title['icon'] . ' ' . $parsed_title['text'] : $parsed_title['text'];
        $title_text_only = $parsed_title['text'];
        
        $new_badge = '';
        
        // Build box_head with either image or Font Awesome icon
        if (!empty($this->img)) {
            // Use image if provided
            $box_head = '<div class="aiautotool_box_f_box-head "><img src="'.esc_url($this->img).'" width="16px" height="16px" /></div>';
        } elseif (!empty($parsed_title['icon'])) {
            // Use Font Awesome icon from title if available
            $box_head = '<div class="aiautotool_box_f_box-head ">' . $parsed_title['icon'] . '</div>';
        } else {
            // Default icon if neither image nor icon available
            $box_head = '<div class="aiautotool_box_f_box-head "><i class="fa-solid fa-cog"></i></div>';
        }
        
        // Build modal icon for modal header
        if (!empty($this->img)) {
            // Use image if provided
            $modal_icon = '<img src="' . esc_url($this->img) . '" width="24px" height="24px" style="margin-right: 10px;" />';
        } elseif (!empty($parsed_title['icon'])) {
            // Use Font Awesome icon from title if available
            $modal_icon = '<span style="margin-right: 10px; font-size: 24px;">' . $parsed_title['icon'] . '</span>';
        } else {
            // Default icon if neither image nor icon available
            $modal_icon = '<i class="fa-solid fa-cog" style="margin-right: 10px; font-size: 24px;"></i>';
        }
        
        $box_content = '
            <div class="aiautotool_box_f_box-content ">
                <h3>' . $title_with_icon . '</h3>
                <div class="aiautotool_box_f_content-wrapper">
                    <p class="aiautotool_box_f_content-short">' . esc_html($content_preview) . '</p>
                    ' . ($has_more_content ? '<button class="aiautotool_box_f_view-more" onclick="window.aiautotoolOpenModal && window.aiautotoolOpenModal(\'' . $modal_id . '\')">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="12" cy="12" r="10"/>
                            <line x1="12" y1="8" x2="12" y2="16"/>
                            <line x1="8" y1="12" x2="16" y2="12"/>
                        </svg>
                        ' . esc_html__('View Details', 'ai-auto-tool') . '
                    </button>' : '') . '
                </div>
                <div class="aiautotool_box_f_box-link">
                  
                </div>
            </div>
        ';

        if($this->premium==true){
            if ( !aiautotool_premium()->is__premium_only() ) {
                $active_checkbox = '<div class="aiautotool_box_f_box-footer">';
                if ( aiautotool_premium()->is_not_paying() ) {
                    $active_checkbox .= '<section>';
                    $active_checkbox .= '<a href="' . aiautotool_premium()->get_upgrade_url() . '">' .
                        __('Upgrade Now!', 'ai-auto-tool') .
                        '</a>';
                    $active_checkbox .= '
                </section>';
                }
                 $active_checkbox .='   </div>
                ';
            }else{
                $active_checkbox = '<div class="aiautotool_box_f_box-footer">
                <label class="aiautotool_box_f_radio-label" for="' . $this->active_option_name . '_box_f_toggle2"></label>
                <label class="aiautotool_box_f_toggle-switch">
                    <input type="checkbox" id="' . esc_html($this->active_option_name) . '_box_f_feature2" name="' . esc_html($this->active_option_name) . '_box_f_feature2" ' . ($this->active == 'true' ? 'checked' : '') . '>
                    <span class="aiautotool_box_f_toggle-slider"></span>
                </label>
                </div>
            ';
            }
        }else{
            $active_checkbox = '<div class="aiautotool_box_f_box-footer">
                <label class="aiautotool_box_f_radio-label" for="' . $this->active_option_name . '_box_f_toggle2"></label>
                <label class="aiautotool_box_f_toggle-switch">
                    <input type="checkbox" id="' . esc_html($this->active_option_name) . '_box_f_feature2" name="' . esc_html($this->active_option_name) . '_box_f_feature2" ' . ($this->active == 'true' ? 'checked' : '') . '>
                    <span class="aiautotool_box_f_toggle-slider"></span>
                </label>
                </div>
            ';
        }
        
        

        // Modal content
        $modal_content = '';
        if ($has_more_content) {
            $modal_content = '
            <div id="' . $modal_id . '" class="aiautotool_box_f_modal" style="display: none;">
                <div class="aiautotool_box_f_modal-overlay" onclick="window.aiautotoolCloseModal && window.aiautotoolCloseModal(\'' . $modal_id . '\')"></div>
                <div class="aiautotool_box_f_modal-content">
                    <div class="aiautotool_box_f_modal-header">
                        <div class="aiautotool_box_f_modal-title">
                            ' . $modal_icon . '
                            <h2>' . $title_with_icon . '</h2>
                        </div>
                        <button class="aiautotool_box_f_modal-close" onclick="window.aiautotoolCloseModal && window.aiautotoolCloseModal(\'' . $modal_id . '\')" aria-label="' . esc_attr__('Close', 'ai-auto-tool') . '">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <line x1="18" y1="6" x2="6" y2="18"/>
                                <line x1="6" y1="6" x2="18" y2="18"/>
                            </svg>
                        </button>
                    </div>
                    <div class="aiautotool_box_f_modal-body">
                        <div class="aiautotool_box_f_modal-description">
                            ' . wp_kses_post($this->content) . '
                        </div>
                        <div class="aiautotool_box_f_modal-footer">
                            <a class="aiautotool_box_f_modal-doc-link" target="_blank" href="' . esc_url($this->link) . '">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                                    <polyline points="14 2 14 8 20 8"/>
                                    <line x1="16" y1="13" x2="8" y2="13"/>
                                    <line x1="16" y1="17" x2="8" y2="17"/>
                                    <polyline points="10 9 9 9 8 9"/>
                                </svg>
                                ' . esc_html__('View Full Documentation', 'ai-auto-tool') . '
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            ';
        }

        // Initialize modal scripts only once - check both PHP flag and JavaScript existence
        $modal_scripts = '';
        if (!self::$modal_initialized) {
            self::$modal_initialized = true;
            $modal_scripts = '
            <script>
               
                if (typeof window.aiautotoolOpenModal !== "function") {
                    window.aiautotoolOpenModal = function(modalId) {
                        const modal = document.getElementById(modalId);
                        if (modal) {
                            // Close any open modals first - use computed style for better detection
                            const allModals = document.querySelectorAll(".aiautotool_box_f_modal");
                            allModals.forEach(m => {
                                const computedStyle = window.getComputedStyle(m);
                                if (computedStyle.display === "flex" && m.id !== modalId) {
                                    window.aiautotoolCloseModal(m.id);
                                }
                            });
                            
                            // Open the requested modal
                            modal.style.display = "flex";
                            document.body.style.overflow = "hidden";
                            // Accessibility
                            modal.setAttribute("aria-hidden", "false");
                        }
                    };
                }

                if (typeof window.aiautotoolCloseModal !== "function") {
                    window.aiautotoolCloseModal = function(modalId) {
                        const modal = document.getElementById(modalId);
                        if (modal) {
                            modal.style.display = "none";
                            document.body.style.overflow = "";
                            // Accessibility
                            modal.setAttribute("aria-hidden", "true");
                        }
                    };
                }

                // Close modal on Escape key - only register once
                if (!window.aiautotoolModalEscapeHandler) {
                    window.aiautotoolModalEscapeHandler = function(event) {
                        if (event.key === "Escape") {
                            const allModals = document.querySelectorAll(".aiautotool_box_f_modal");
                            allModals.forEach(modal => {
                                const computedStyle = window.getComputedStyle(modal);
                                if (computedStyle.display === "flex") {
                                    window.aiautotoolCloseModal(modal.id);
                                }
                            });
                        }
                    };
                    document.addEventListener("keydown", window.aiautotoolModalEscapeHandler);
                }
            </script>
            ';
        }

        $script = '
        <script>
            document.addEventListener("DOMContentLoaded", function () {
                const checkbox = document.getElementById("' . esc_js($this->active_option_name) . '_box_f_feature2");
                if (!checkbox) return;

                checkbox.addEventListener("change", function () {
                    const active = this.checked ? "true" : "false";
                    const optionName = "' . esc_js($this->active_option_name) . '";
                    
                    // Check if aiautotool_js_setting is available, if not, use fallback
                    const ajaxUrl = (typeof aiautotool_js_setting !== "undefined" && aiautotool_js_setting && aiautotool_js_setting.ajax_url) 
                        ? aiautotool_js_setting.ajax_url 
                        : "' . esc_js(admin_url('admin-ajax.php')) . '";
                    
                    const security = (typeof aiautotool_js_setting !== "undefined" && aiautotool_js_setting && aiautotool_js_setting.security) 
                        ? aiautotool_js_setting.security 
                        : "";
                    
                    // Validate required data
                    if (!security) {
                        console.error("AI Auto Tool: Security token not found. Please refresh the page.");
                        console.error("aiautotool_js_setting:", typeof aiautotool_js_setting !== "undefined" ? aiautotool_js_setting : "undefined");
                        alert("Security token missing. Please refresh the page and try again.");
                        checkbox.checked = !checkbox.checked; // Revert
                        return;
                    }
                    
                    // Debug logging
                    console.log("AI Auto Tool: Toggling feature", {
                        option: optionName,
                        active: active,
                        hasSecurity: !!security,
                        securityLength: security ? security.length : 0,
                        securityValue: security ? security.substring(0, 20) + "..." : "empty",
                        ajaxUrl: ajaxUrl
                    });
                    
                    // Try unified handler first (new method)
                    const data = {
                        action: "aiautotool_toggle_feature",
                        option: optionName,
                        active: active,
                        security: security
                    };
                    
                    // Create URLSearchParams to ensure proper encoding
                    const formData = new URLSearchParams();
                    formData.append("action", data.action);
                    formData.append("option", data.option);
                    formData.append("active", data.active);
                    formData.append("security", data.security);
                    
                    // Debug: Log the data being sent
                    console.log("AI Auto Tool: Sending data", {
                        action: data.action,
                        option: data.option,
                        active: data.active,
                        security: data.security.substring(0, 20) + "...",
                        securityLength: data.security.length
                    });

                    fetch(ajaxUrl, {
                        method: "POST",
                        body: formData,
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded"
                        }
                    })
                    .then(response => {
                        // Check if response is OK
                        if (!response.ok) {
                            throw new Error("HTTP error! status: " + response.status);
                        }
                        return response.json();
                    })
                    .then(result => {
                        if (result.success) {
                            // Success - reload page to reflect changes
                            location.reload();
                        } else {
                            // Show error message from server
                            const errorMsg = result.data && result.data.message 
                                ? result.data.message 
                                : "Failed to update feature. Please refresh the page and try again.";
                            alert(errorMsg);
                            console.error("Unified handler failed:", result);
                            
                            // Revert checkbox state
                            checkbox.checked = !checkbox.checked;
                            
                            // Try legacy handler as fallback
                            return legacyToggle(optionName, active, ajaxUrl, security);
                        }
                    })
                    .catch(error => {
                        console.error("Error during AJAX request:", error);
                        alert("Network error occurred. Please check your connection and try again.");
                        // Revert checkbox state
                        checkbox.checked = !checkbox.checked;
                        // Try legacy handler as fallback
                        legacyToggle(optionName, active, ajaxUrl, security).catch(legacyError => {
                            console.error("Legacy handler also failed:", legacyError);
                        });
                    });
                    
                    // Legacy handler function for backward compatibility
                    function legacyToggle(optionName, active, ajaxUrl, security) {
                        const legacyData = {
                            action: "update_active_option_canonical_" + optionName,
                            active: active,
                            security: security
                        };
                        
                        return fetch(ajaxUrl, {
                            method: "POST",
                            body: new URLSearchParams(legacyData),
                            headers: {
                                "Content-Type": "application/x-www-form-urlencoded"
                            }
                        })
                        .then(response => response.json())
                        .then(result => {
                            if (result.success) {
                                location.reload();
                            } else {
                                console.error("Failed to update option:", result);
                                alert("Failed to update feature. Please refresh the page and try again.");
                                // Revert checkbox state
                                checkbox.checked = !checkbox.checked;
                            }
                        })
                        .catch(error => {
                            console.error("Error during legacy AJAX request:", error);
                            alert("An error occurred. Please refresh the page and try again.");
                            // Revert checkbox state
                            checkbox.checked = !checkbox.checked;
                        });
                    }
                });
            });
        </script>
        ';

        $html = '
        <div class="aiautotool_box_f_box ">
            ' . $new_badge . '
            ' . $box_head . '
            ' . $box_content . '
            ' . $active_checkbox . '
        </div>
        ' . $modal_content . '
        ' . $modal_scripts . '
        ' . $script;

        return $html;
    }
}

