<?php
/*
Plugin Name: AutoPoly - AI Translation For Polylang
Plugin URI:
Description: simple description
Version: 1.0.0.0
*/

require_once "class-ai-automatic-translations-for-polylang-base.php";
class AIAutomaticTranslationsForPolylang {
    public $plugin_file=ATFPP_FILE;
    public $response_obj;
    public $license_message;
    public $slug="atfpp";
    public static $form_status = false;
    private const OPTION_LICENSE_KEY = 'AIAutomaticTranslationsForPolylang_lic_Key';
    private const OPTION_LICENSE_EMAIL = 'AIAutomaticTranslationsForPolylang_lic_email';
    private $showMessage = false;
    private $licenseMessage = '';
    private $responseObj = null;
    function __construct() {
        $this->atfpp_register_hooks();
        $this->atfpp_initialize_license();
        // Add error notice hook
        add_action('atfpp_display_admin_notices', array($this, 'atfpp_display_license_error_messages'));
        add_action('atfpp_display_admin_notices', array($this, 'atfpp_display_license_key_notice'));
    }

    
    private function atfpp_register_hooks() {
        add_action( 'admin_print_styles', [ $this, 'atfpp_set_admin_style' ] );
        add_action( 'admin_menu', array( $this, 'atfpp_add_submenu_page' ), 11 );
        add_action('admin_post_AIAutomaticTranslationsForPolylang_el_activate_license', [$this, 'atfpp_handle_license_activation']);
        add_action('admin_post_AIAutomaticTranslationsForPolylang_el_deactivate_license', [$this, 'atfpp_handle_license_deactivation']);
        add_action('wp_ajax_atfpp_refresh_license_ajax', [$this, 'atfpp_handle_refresh_license_ajax']);
    }

    private function atfpp_initialize_license() {
        $licenseKey = get_option(self::OPTION_LICENSE_KEY, "");
        $liceEmail = get_option(self::OPTION_LICENSE_EMAIL, get_bloginfo('admin_email'));
        
        AI_Automatic_Translations_For_Polylang_Base::add_on_delete(function(){
           delete_option(self::OPTION_LICENSE_KEY);
           delete_option(self::OPTION_LICENSE_EMAIL);
        });

        if (AI_Automatic_Translations_For_Polylang_Base::CheckWPPlugin($licenseKey, $liceEmail, $this->licenseMessage, $this->responseObj, $this->plugin_file)) {
            self::$form_status = true;
        } else {
            self::$form_status = false;
            if(!empty($licenseKey) && !empty($this->licenseMessage)) {
                $this->showMessage = true;
            }
        }
    }

    function atfpp_set_admin_style() {
        if (isset($_GET['page']) && $_GET['page'] === 'polylang-atfpp-dashboard') {
            wp_enqueue_style(
                'atfpp-dashboard-style',
                ATFPP_URL . 'admin/atfpp-dashboard/css/admin-styles.css',
                array(),
                ATFPP_V,
                'all'
            );
            wp_enqueue_style("atfpp-dashboard-style");

            wp_enqueue_script(
                'atfpp-dashboard-script',
                ATFPP_URL . 'admin/atfpp-dashboard/js/atfpp-glossary.js',
                array('jquery','underscore'), // dependencies
                ATFPP_V,
                true // load in footer
            );

            // Fetch Polylang languages
            $pll_languages_serialized = get_option('_transient_pll_languages_list');
            $pll_languages = [];
            if ($pll_languages_serialized) {
                $pll_languages = maybe_unserialize($pll_languages_serialized);
            }
            $languages = [];
            if (is_array($pll_languages)) {
                foreach ($pll_languages as $pll_lang) {
                    $languages[] = [
                        'code' => $pll_lang['slug'],
                        'alt'  => $pll_lang['name'],
                        'img'  => $pll_lang['flag_url'],
                    ];
                }
            }

            wp_localize_script('atfpp-dashboard-script', 'atfpp_glossary', array(
                'ajaxurl' => admin_url('admin-ajax.php'),
                'atfpp_languages' => $languages,
                'url' => ATFPP_URL,
                'file' => 'file.svg',
                'nonce' => wp_create_nonce('atfpp_glossary_nonce'),
            ));
        }

        wp_enqueue_script(
            'atfpp-dashboard-plugin-setting',
            ATFPP_URL . 'admin/atfpp-dashboard/js/atfpp-plugin-setting.js',
            array('jquery'),
            ATFPP_V,
            true
        );

        wp_enqueue_script(
            'atfpp-dashboard-data-share',
            ATFPP_URL . 'admin/atfpp-dashboard/js/atfpp-data-share-setting.js',
            array('jquery'),
            ATFPP_V,
            true
        );

        wp_localize_script( 'atfpp-dashboard-data-share', 'atfpp_ajax', array(
            'nonce' => wp_create_nonce('atfpp_refresh_license_nonce'),
            'ajaxurl' => admin_url('admin-ajax.php')
        ) );

    }

        /*
		|-------------------------------------------------------
		|   AI Automatic Translate Addon For Polylang admin page
		|-------------------------------------------------------
		*/
		function atfpp_add_submenu_page() {
            add_submenu_page(
                'mlang', // Parent slug
                __( 'AutoPoly - AI Translation For Polylang', 'autopoly-ai-translation-for-polylang-pro' ), // Page title
                __( 'AutoPoly', 'autopoly-ai-translation-for-polylang-pro' ), // Menu title
                'manage_options', // Capability
                // $this->slug, // Menu slug
                'polylang-atfpp-dashboard',  //Menu slug
                array( $this, 'atfpp_dashboard_page' ) // Callback function
            );
		}

                /**
         * Render the dashboard page with dynamic text domain support
         * 
         * @param string $text_domain The text domain for translations (default: 'autopoly-ai-translation-for-polylang-pro')
         */
        function atfpp_dashboard_page() {
            $text_domain = 'autopoly-ai-translation-for-polylang-pro';
            $file_prefix = ATFPP_DIR_PATH . 'admin/atfpp-dashboard/views/';
            
            $valid_tabs = $this->atfpp_get_valid_tabs($text_domain);
            $buttons = $this->atfpp_get_action_buttons($text_domain);

            // Get current tab with fallback
            $tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'dashboard';
            $current_tab = array_key_exists($tab, $valid_tabs) ? $tab : 'dashboard';
            
            ?>
            <div class="atfpp-dashboard-wrapper">
                <div class="atfpp-dashboard-header">
                    <div class="atfpp-dashboard-header-left">
                        <a href="?page=polylang-atfpp-dashboard&tab=dashboard" class="atfpp-dashboard-logo-link">
                            <img src="<?php echo esc_url(ATFPP_URL . 'admin/atfpp-dashboard/images/polylang-addon-logo.svg'); ?>" 
                                alt="<?php esc_attr_e('Polylang Addon Logo', $text_domain); ?>">
                        </a>
                        <div class="atfpp-dashboard-tab-title">
                            <span>↳</span> <?php echo esc_html($valid_tabs[$current_tab]); ?>
                        </div>
                    </div>
                    <div class="atfpp-dashboard-header-right">
                        <span><?php esc_html('AutoPoly - AI Translation For Polylang'); ?></span>
                        <?php foreach ($buttons as $button): ?>
                            <a href="<?php echo esc_url($button['url']); ?>" 
                            class="atfpp-dashboard-btn" 
                            target="_blank"
                            aria-label="<?php echo isset($button['alt']) ? esc_attr($button['alt']) : ''; ?>">
                                <?php if (isset($button['img'])): ?>
                                    <img src="<?php echo esc_url(ATFPP_URL . 'admin/atfpp-dashboard/images/' . $button['img']); ?>" 
                                        alt="<?php echo esc_attr($button['alt']); ?>">
                                <?php endif; ?>
                                <?php if (isset($button['text'])): ?>
                                    <span><?php echo esc_html($button['text']); ?></span>
                                <?php endif; ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <nav class="nav-tab-wrapper" aria-label="<?php esc_attr_e('Dashboard navigation', $text_domain); ?>">
                    <?php foreach ($valid_tabs as $tab_key => $tab_title): ?>
                        <a href="?page=polylang-atfpp-dashboard&tab=<?php echo esc_attr($tab_key); ?>" 
                        class="nav-tab <?php echo esc_attr($tab === $tab_key ? 'nav-tab-active' : ''); ?>">
                            <?php echo esc_html($tab_title); ?>
                        </a>
                    <?php endforeach; ?>
                </nav>
                
                <div class="tab-content">
                    <?php
                    $allowed_tabs = ['dashboard', 'ai-translations', 'settings', 'license', 'support-blocks', 'custom-fields','glossary'];
                    
                    if(!in_array($current_tab, $allowed_tabs)) {
                        $current_tab = 'dashboard';
                    }
                    
                    $view_file = $file_prefix . $current_tab . '.php';
                    if (file_exists($view_file)) {
                        require_once $view_file;
                    }
                    
                    if($current_tab === 'license' || $current_tab === 'settings') {
                        $licenseKey = get_option(self::OPTION_LICENSE_KEY,"");
                        $liceEmail = get_option( self::OPTION_LICENSE_EMAIL,"");
                        AI_Automatic_Translations_For_Polylang_Base::add_on_delete(function(){
                           delete_option(self::OPTION_LICENSE_KEY);
                        });
                        if(AI_Automatic_Translations_For_Polylang_Base::CheckWPPlugin($licenseKey,$liceEmail,$this->licenseMessage,$this->responseObj,$this->plugin_file)){
                            if($current_tab === 'license'){
                                atfpp_render_license_page_pro($this->responseObj);
                            }
                            if($current_tab === 'settings'){
                                atfpp_render_settings_page_pro();
                            }
                        }else{
                            if($current_tab === 'license'){
                                atfpp_render_license_page();
                            }
                            if($current_tab === 'settings'){
                                atfpp_render_settings_page();
                            }
                        }
                    }
                    
                    $sidebar_file = $file_prefix . 'sidebar.php';
                    if (file_exists($sidebar_file) && $current_tab !== 'support-blocks' && $current_tab !== 'custom-fields' && $current_tab !== 'glossary') {
                        require_once $sidebar_file;
                    }
                    ?>
                </div>
                <?php 
                $footer_file = $file_prefix . 'footer.php';
                if (file_exists($footer_file)) {
                    require_once $footer_file;
                }
                ?>
            </div>
            <?php
        }

        private function atfpp_get_valid_tabs($text_domain) {
            return [
                'dashboard'       => __('Dashboard', $text_domain),
                'ai-translations' => __('AI Translations', $text_domain),
                'settings'        => __('Settings', $text_domain),
                'license'         => __('License', $text_domain),
                'support-blocks'  => __('Supported Blocks', $text_domain),
                'custom-fields'   => __('Custom Fields', $text_domain),
                'glossary'        => __('Glossary', $text_domain),
            ];
        }

        private function atfpp_get_action_buttons($text_domain) {
            return [
                [
                    'url'  => 'https://coolplugins.net/products/?utm_source=atfp_plugin&utm_medium=inside&utm_campaign=product_page&utm_content=dashboard_header_pro',
                    'alt'  => __('Explore Cool Plugins', $text_domain),
                    'img'  => 'upgrade-now.svg',
                    'text' => __('Explore Cool Plugins', $text_domain)
                ],
                // [
                //     'url' => 'https://docs.coolplugins.net/docs/ai-translation-for-polylang/',
                //     'img' => 'document.svg',
                //     'alt' => __('document', $text_domain)
                // ],
                [
                    'url' => 'https://coolplugins.net/support/?utm_source=atfp_plugin&utm_medium=inside&utm_campaign=support&utm_content=dashboard_header_pro',
                    'img' => 'contact.svg',
                    'alt' => __('contact', $text_domain)
                ]
            ];
        }

    public function atfpp_handle_license_activation() {
        $this->atfpp_check_user_capabilities();
        check_admin_referer('el-atfpp-license');
        
        // Validate license key
        $license_key = !empty($_POST['license_code']) ? sanitize_text_field(wp_unslash($_POST['license_code'])) : '';
        if (empty($license_key)) {
            $this->atfpp_redirect_with_error('missing_key');
            return;
        }
        
        // Validate email
        $license_email = !empty($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
        if (empty($license_email)) {
            $this->atfpp_redirect_with_error('missing_email');
            return;
        }

        $error = '';
        $responseObj = null;
        
        if (AI_Automatic_Translations_For_Polylang_Base::check_wp_plugin($license_key, $license_email, $error, $responseObj, $this->plugin_file)) {
            update_option(self::OPTION_LICENSE_KEY, $license_key);
            update_option(self::OPTION_LICENSE_EMAIL, $license_email);
            delete_site_transient('update_plugins');
            $this->atfpp_redirect_with_success();
        } else {
            $this->showMessage = true;
            $this->licenseMessage = $error;
            $this->atfpp_redirect_with_error('invalid_key');
        }
    }

    private function atfpp_check_user_capabilities() {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.', 'autopoly-ai-translation-for-polylang-pro'));
        }
    }

    private function atfpp_redirect_with_success() {
        wp_redirect(admin_url('admin.php?page=polylang-atfpp-dashboard&tab=license&activated=true'));
        exit;
    }

    private function atfpp_redirect_with_error($error) {
        wp_redirect(admin_url('admin.php?page=polylang-atfpp-dashboard&tab=license&error=' . urlencode($error)));
        exit;
    }

    public function atfpp_handle_license_deactivation() {
        try {
            $this->atfpp_check_user_capabilities();
            check_admin_referer('el-atfpp-license');
            
            $message = '';
            if (AI_Automatic_Translations_For_Polylang_Base::remove_license_key($this->plugin_file, $message)) {
                delete_option(self::OPTION_LICENSE_KEY);
                delete_option(self::OPTION_LICENSE_EMAIL);
                delete_site_transient('update_plugins');
                
                wp_safe_redirect(admin_url('admin.php?page=polylang-atfpp-dashboard&tab=license&deactivated=true'));
                exit;
            }
            
            wp_safe_redirect(admin_url('admin.php?page=polylang-atfpp-dashboard&tab=license&error=' . urlencode($message)));
            exit;
            
        } catch (\Exception $e) {
            wp_safe_redirect(admin_url('admin.php?page=polylang-atfpp-dashboard&tab=license&error=unexpected_error'));
            exit;
        }
    }

            /**
         * Handle AJAX license refresh request
         */
        function atfpp_handle_refresh_license_ajax() {
            // Check nonce for security
            if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field($_POST['nonce']), 'atfpp_refresh_license_nonce')) {
                wp_send_json_error(array('message' => 'Security check failed.'));
                return;
            }

            $this->atfpp_check_user_capabilities();
            
            // Get existing license key and email
            $license_key    = get_option(self::OPTION_LICENSE_KEY, '');
            $license_email  = get_option(self::OPTION_LICENSE_EMAIL, '');

            if (empty($license_key) || empty($license_email)) {
                wp_send_json_error(array('message' => 'No license information found to refresh.'));
                return;
            }

            $error = '';
            $responseObj = null;

            // Use the same activation logic to refresh the license
            if (AI_Automatic_Translations_For_Polylang_Base::check_wp_plugin($license_key, $license_email, $error, $responseObj, $this->plugin_file)) {
                
                // Get updated license information
                $license_info = array(
                    'is_valid' => $responseObj->is_valid ? $responseObj->is_valid:false,
                    'license_title' => $responseObj->license_title ? $responseObj->license_title : '',
                    'expire_date' => $responseObj->expire_date ? $responseObj->expire_date : '',
                    'market' => $responseObj->market ? $responseObj->market : '',
                    'support_end' => $responseObj->support_end ? $responseObj->support_end : '',
                );
                
                
                wp_send_json_success(array(
                    'message' => 'License Status Updated successfully!',
                    'license_info' => $license_info,
                    'version_available_message' => AutoPolyPro::atfppGetVersionAvailableMessage()
                ));
            } else {
                // Map error message to error code
                $error_code = $this->atfpp_map_error_to_code($error);
                $error_message = $this->atfpp_get_error_message($error_code);
                wp_send_json_error(array('message' => $error_message));
            }
        }

    private function atfpp_is_valid_license_key($licenseKey) {
        // This method appears to be unused - can be removed
        $pattern = '/^[0-9A-F][0-9A-F]{7}-[0-9A-F]{8}-[0-9A-F]{8}-[0-9A-F]{8}$/i';
        return preg_match($pattern, $licenseKey) ? true : false;
    }

    private function atfpp_map_error_to_code($error) {
        // This method appears to be unused - can be removed
        $error = strtolower($error);
        if (strpos($error, 'invalid') !== false) {
            return 'invalid_key';
        } elseif (strpos($error, 'expired') !== false) {
            return 'expired';
        } elseif (strpos($error, 'disabled') !== false) {
            return 'disabled';
        } elseif (strpos($error, 'no activation') !== false) {
            return 'no_activations';
        }
        return 'default';
    }

    public function atfpp_display_license_error_messages() {
        if (isset($_GET['page']) && $_GET['page'] === 'polylang-atfpp-dashboard' && isset($_GET['tab']) && $_GET['tab'] === 'license') {
            if (isset($_GET['error'])) {
                $error_message = $this->atfpp_get_error_message($_GET['error']);
                ?>
                <div class="notice notice-error is-dismissible">
                    <p><?php echo esc_html($error_message); ?></p>
                </div>
                <?php
            }

            if (isset($_GET['activated']) && $_GET['activated'] === 'true') {
                ?>
                <div class="notice notice-success is-dismissible">
                    <p><?php _e('License activated successfully!', 'autopoly-ai-translation-for-polylang-pro'); ?></p>
                </div>
                <?php
            }

            if (isset($_GET['deactivated']) && $_GET['deactivated'] === 'true') {
                ?>
                <div class="notice notice-info is-dismissible">
                    <p><?php _e('License deactivated successfully!', 'autopoly-ai-translation-for-polylang-pro'); ?></p>
                </div>
                <?php
            }

            if ($this->showMessage && !empty($this->licenseMessage)) {
                ?>
                <div class="notice notice-error is-dismissible">
                    <p><?php echo esc_html($this->licenseMessage); ?></p>
                </div>
                <?php
            }
        }
    }

    private function atfpp_get_error_message($error_code) {
        $messages = array(
            'missing_key' => __('License key is required.', 'autopoly-ai-translation-for-polylang-pro'),
            'missing_email' => __('Email address is required.', 'autopoly-ai-translation-for-polylang-pro'),
            'invalid_email' => __('Please enter a valid email address.', 'autopoly-ai-translation-for-polylang-pro'),
            'invalid_format' => __('Invalid license key format. Please check your license key.', 'autopoly-ai-translation-for-polylang-pro'),
            'invalid_key' => __('Invalid license key. Please check your license key and try again.', 'autopoly-ai-translation-for-polylang-pro'),
            'expired' => __('Your license key has expired. Please renew your license.', 'autopoly-ai-translation-for-polylang-pro'),
            'disabled' => __('Your license key has been disabled.', 'autopoly-ai-translation-for-polylang-pro'),
            'no_activations' => __('No activations left for this license key.', 'autopoly-ai-translation-for-polylang-pro'),
            'default' => __('An error occurred while validating your license. Please try again.', 'autopoly-ai-translation-for-polylang-pro')
        );

        return isset($messages[$error_code]) ? $messages[$error_code] : $messages['default'];
    }

    public function atfpp_display_license_key_notice() {
        if ($this->showMessage && !empty($this->licenseMessage)) {
            ?>
            <div class="notice notice-error is-dismissible">
                <p><?php echo esc_html($this->licenseMessage); ?></p>
            </div>
            <?php
        }
    }
}

new AIAutomaticTranslationsForPolylang();