<?php
/*
* Plugin Name: SWPanel AI Builder
* Description: AI Web Builder for WordPress
* Version: 1.0.3
* Author: SWPanel
* License: GPLv2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: swpanel-ai
* Domain Path: /languages
* Requires at least: 6.8
* Requires PHP: 7.4
*/

defined('ABSPATH') || exit;

if (file_exists(__DIR__ . '/vendor/autoload.php')) {
    require_once __DIR__ . '/vendor/autoload.php';
}
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

if (!class_exists('SWPanelAI')) :
    final class SWPanelAI {
        public static $loaded = false;

        public function __invoke()
        {
            if (!self::$loaded) {
                self::$loaded = true;
                define('SWPANEL_PATH', plugin_dir_path(__FILE__));
                
                foreach (glob(SWPANEL_PATH . 'includes/*.php') as $file) require_once $file;
                foreach (glob(SWPANEL_PATH . 'admin/*.php') as $file) require_once $file;
                foreach (glob(SWPANEL_PATH . 'admin/pages/*.php') as $file) require_once $file;

                new \SWPanel\AdminMenu();
                new \SWPanel\Pages\TokenPage();
                if (\SWPanel\Auth::validate()){
                    new \SWPanel\Pages\ConceptPage();
                    if (\get_option('stylesheet') === 'twentytwentyfive') {
                        new \SWPanel\Pages\StructurePage();
                        new \SWPanel\Pages\StylePage();
                        new \SWPanel\Pages\TemplatePage();
                        new \SWPanel\Pages\CreatingPage();
                    }
                    add_option('swpanel_ai_site_id', wp_generate_uuid4());
                    add_action('admin_init', function () {
                        $request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
                        $basename    = basename(wp_parse_url($request_uri, PHP_URL_PATH));
                        $current_page = isset($_GET['page']) ? sanitize_key($_GET['page']) : '';
                        $target_page  = sanitize_key(get_option('swpanel_ai_page', 'swpanel_ai_concept'));
                        $redirect_flag = (int) get_option('swpanel_ai_redirect', 0);

                        $whitelist = [
                            'admin-ajax.php',
                            'admin-post.php',
                            'async-upload.php',
                            'update.php',
                            'themes.php',
                            'theme-install.php',
                        ];
                        if (
                            defined('DOING_AJAX') ||
                            in_array($basename, $whitelist, true) ||
                            !current_user_can('administrator') ||
                            $redirect_flag >= 1 ||
                            $current_page === $target_page
                        ) {
                            return;
                        }
                        update_option('swpanel_ai_redirect', get_option('swpanel_ai_redirect', -1) + 1);
                        wp_safe_redirect(admin_url('admin.php?page=' . $target_page));
                        exit;
                    });
                }
                else {
                    add_action('admin_init', function () {
                        $request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
                        if (
                            defined('DOING_AJAX') ||
                            strpos($request_uri, 'admin-post.php') !== false ||
                            (isset($_GET['page']) && $_GET['page'] === 'swpanel_ai_token') ||
                            !current_user_can('administrator') ||
                            (int) get_option('swpanel_ai_redirect_token', 0) >= 1
                        ) {
                            return;
                        }
                        update_option('swpanel_ai_redirect_token', get_option('swpanel_ai_redirect_token', 0) + 1);
                        wp_safe_redirect(admin_url('admin.php?page=' . get_option('swpanel_ai_page', 'swpanel_ai_token')));
                        exit;
                    });
                }
            }
        }
    }

    add_action('plugins_loaded', function () {
        $swpanelai = new SWPanelAI();
        add_action('init', function() use ($swpanelai) {
            $swpanelai();
        });
    });


    register_uninstall_hook(__FILE__, 'swpanel_ai_uninstall');
    function swpanel_ai_uninstall() {
        global $wpdb;
        $options = $wpdb->get_col(
            "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '%swpanel_ai%'"
        );
        foreach ($options as $option_name) {
            delete_option($option_name);
        }
    }

    if (defined('WP_CLI') && WP_CLI) {
        WP_CLI::add_command('swpanel-ai token', function ($args) {
    
            if (count($args) < 2) {
                WP_CLI::error('Token not specified.');
            }

            list($token, $secret) = $args;

            try {
                update_option('swpanel_ai_license_token_entered', 1);
                $decoded = JWT::decode($token, new Key($secret, 'HS256'));
                update_option('swpanel_ai_license_token', $decoded->token);
                update_option('swpanel_ai_url', $decoded->url);
                delete_transient('swpanel_ai_license_status');
                WP_CLI::success('Token added.');
            } catch (\Exception $e) {
                delete_option('swpanel_ai_license_token');
                delete_option('swpanel_ai_url');
                delete_transient('swpanel_ai_license_status');
                WP_CLI::error('Invalid token.');
            }
        });
    }

    add_filter('show_admin_bar', function($show) {
        if (isset($_GET['noadminbar']) && $_GET['noadminbar'] == 1) {
            return false;
        }
        return $show;
    });
    
    add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), 'swpanel_ai_action_link' );
    function swpanel_ai_action_link($links) {
		$custom['swpanel-ai-settings'] = sprintf(
			'<a href="%s" aria-label="%s">%s</a>',
			esc_url( admin_url('admin.php?page=swpanel_ai' )),
			esc_attr__( 'Go to SWPanel AI Settings page', 'swpanel-ai' ),
			esc_html__( 'Settings', 'swpanel-ai' )
		);
		return array_merge( $custom, (array) $links );
    }
endif;
