<?php
/**
 * Plugin Name: Docswrite – Export Google Docs to Your Site ✨
 * Plugin URI: https://docswrite.com/
 * Description: Official Docswrite Integration. Google Docs to WordPress in One-Click. Save 100s of hours every month. No more copy-pasting. No more formatting issues.
 * Version: 1.2.26
 * Tested up to: 6.7
 * Requires PHP: 5.3
 * Author: Docswrite
 * Text Domain: docswrite
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Stable tag: 1.2.26
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) exit;

require_once __DIR__ . '/DocswriteAPI.php';

if ( ! class_exists( 'Docswrite' ) ) {
    class Docswrite {
        const DOCSWRITE_CONNECTION_ENDPOINT = 'https://docswrite.com/dashboard/integrations/wordpress_plugin?uuid={website_id}&name={name}&url={url}';
        const DOCSWRITE_CONNECTION_OPTION = 'docswrite_connection';
        const DOCSWRITE_WEBSITE_ID_OPTION = 'docswrite_website_id';
        const DOCSWRITE_POST_RAW_META_KEY = 'docswrite_raw_post_object';
        const DOCSWRITE_POST_ID_META_KEY = 'docswrite_post_id';

        /**
         * Initializes the Docswrite plugin by setting up the necessary actions.
         * @return void
         */
        public static function init() {
            add_action('admin_menu', array('Docswrite', 'docswrite_settings_menu'));
            add_action('init', array('Docswrite', 'handle_disconnection'));
            add_action('admin_enqueue_scripts', array('Docswrite', 'enqueue_admin_assets'));

            /**
             * Register REST endpoints
             */
            DocswriteAPI::register_api_endpoints();
            add_action('rest_api_init', array('Docswrite', 'register_rest_routes'));
        }

        /**
         * Handles disconnection request from the user.
         */
        public static function handle_disconnection() {
            if (isset($_POST['action']) && $_POST['action'] === 'docswrite_disconnect' && isset($_POST['disconnect']) && $_POST['disconnect'] === '1') {
                // Verify nonce
                if (!isset($_POST['docswrite_disconnect_nonce']) || !wp_verify_nonce(wp_unslash($_POST['docswrite_disconnect_nonce']), 'docswrite_disconnect_action')) {
                    wp_die('Security check failed', 'Security Error', array('response' => 403));
                }
                update_option(self::DOCSWRITE_CONNECTION_OPTION, 0);
                wp_safe_redirect(admin_url('admin.php?page=docswrite'));
                exit;
            }
        }

        /**
         * Adds the Docswrite Settings menu page to the WordPress admin menu.
         */
        public static function docswrite_settings_menu() {
            add_menu_page(
                __('Docswrite Settings', 'docswrite'),
                __('Docswrite', 'docswrite'),
                'manage_options',
                'docswrite',
                array('Docswrite', 'docswrite_settings_page'),
                plugin_dir_url(__FILE__) . 'assets/logos/docswrite-logo.png',
                80
            );
        }

        /**
         * Renders the Docswrite settings page.
         */
        public static function docswrite_settings_page() {
            $website_id    = self::get_website_id();
            $website_name  = self::get_website_name();
            $website_url   = self::get_website_url();
            $connection    = self::is_connected() ? 'Connected' : 'Disconnected';
            $plugin_data   = get_plugin_data(__FILE__);
            $is_first_time = get_option('docswrite_first_time', true);

            // Set the default tab to 'getting-started' if the connection is 'Disconnected'
            $active_tab    = ($connection === 'Disconnected' && !isset($_GET['tab'])) ? 'getting-started' : (isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'settings');

            $connection_url = $connection === 'Disconnected' 
                ? str_replace(
                    ['{website_id}', '{name}', '{url}'], 
                    [$website_id, urlencode($website_name), urlencode($website_url)], 
                    self::DOCSWRITE_CONNECTION_ENDPOINT
                ) 
                : '#';
            ?>
            <div class="wrap docswrite-container">
                <div class="docswrite-header">
                    <img src="<?php echo esc_url(plugin_dir_url(__FILE__) . 'assets/logos/docswrite-logo.svg'); ?>" alt="Docswrite Logo" class="docswrite-logo">
                    <h2><?php esc_html_e('Docswrite Settings', 'docswrite'); ?></h2>
                </div>

                <nav class="nav-tab-wrapper">
                    <?php if ($connection === 'Disconnected') : ?>
                        <a href="<?php echo esc_url(add_query_arg('tab', 'getting-started', remove_query_arg('settings-updated'))); ?>" 
                           class="nav-tab <?php echo $active_tab === 'getting-started' ? 'nav-tab-active' : ''; ?>">
                            <?php esc_html_e('Getting Started', 'docswrite'); ?>
                        </a>
                    <?php endif; ?>
                    <a href="<?php echo esc_url(add_query_arg('tab', 'settings', remove_query_arg('settings-updated'))); ?>" 
                       class="nav-tab <?php echo $active_tab === 'settings' ? 'nav-tab-active' : ''; ?>">
                        <?php esc_html_e('Settings', 'docswrite'); ?>
                    </a>
                </nav>

                <?php if ($active_tab === 'settings') : ?>
                    <!-- Settings Tab Content -->
                    <div class="docswrite-settings-content">
                        <!-- Your existing settings page content here -->
                        <div class="docswrite-connection-status">
                            <h3><?php esc_html_e('Connection Status', 'docswrite'); ?></h3>
                            <form action="<?php echo esc_url($connection_url); ?>" method="post" target="_blank">
                            <p>
                                    <label for="website-id"><?php esc_html_e('Website ID', 'docswrite'); ?></label>
                                    <input type="text" id="website-id" name="website-id" size="32" value="<?php echo esc_attr($website_id); ?>" readonly>
                                </p>
                                <p>
                                    <label for="connection-status"><?php esc_html_e('Connection', 'docswrite'); ?></label>
                                    <span class="status-badge <?php echo strtolower($connection); ?>"><?php echo esc_html($connection); ?></span>
                                </p>
                                <?php if ($connection === 'Connected') { ?>
                                    <input type="hidden" name="action" value="docswrite_disconnect">
                                    <input type="hidden" name="disconnect" value="1">
                                    <?php wp_nonce_field('docswrite_disconnect_action', 'docswrite_disconnect_nonce'); ?>
                                    <?php submit_button(esc_html__('Disconnect', 'docswrite'), 'disconnect', 'connection-button', false, array(
                                        'onclick' => 'return confirmDisconnect()',
                                        'class' => 'button disconnect'
                                    )); ?>
                                <?php } else { ?>
                                    <?php submit_button(esc_html__('Connect', 'docswrite'), 'connect', 'connection-button', false, array(
                                        'class' => 'button connect'
                                    )); ?>
                                <?php } ?>
                            </form>
                        </div>
                    </div>
                <?php else : ?>
                    <!-- Getting Started Tab Content -->
                    <div class="docswrite-wizard">
                        <div class="getting-started-container">
                            <!-- Steps Section -->
                            <div class="setup-steps">
                                <div class="step">
                                    <div class="step-indicator">
                                        <div class="step-number">1</div>
                                    </div>
                                    <div class="step-content">
                                        <h3><?php esc_html_e('Create Account', 'docswrite'); ?></h3>
                                        <p><?php esc_html_e('Sign up for free and start your Docswrite journey - you get free 5 exports.', 'docswrite'); ?></p>
                                        <a href="https://docswrite.com/accounts/signup" class="button-modern" target="_blank" rel="noopener noreferrer">
                                            <?php esc_html_e('Register Now', 'docswrite'); ?>
                                        </a>
                                    </div>
                                </div>

                                <div class="step">
                                    <div class="step-indicator">
                                        <div class="step-number">2</div>
                                    </div>
                                    <div class="step-content">
                                        <h3><?php esc_html_e('Connect Site', 'docswrite'); ?></h3>
                                        <p><?php esc_html_e('Link your WordPress site with one click.', 'docswrite'); ?></p>
                                        <a href="<?php echo esc_url(add_query_arg('tab', 'settings', remove_query_arg('settings-updated'))); ?>" class="button-modern">
                                            <?php esc_html_e('Go to Settings', 'docswrite'); ?>
                                        </a>
                                    </div>
                                </div>
                            </div>

                            <!-- Tutorial Section -->
                            <div class="tutorial-section">
                                <h2 class="tutorial-title"><?php esc_html_e('Quick Start Guide', 'docswrite'); ?></h2>
                                <div class="tutorial-content">
                                    <div class="video-wrapper">
                                        <div class="video-container">
                                            <iframe 
                                                src="https://www.youtube.com/embed/DTOnGy-8iE0" 
                                                title="How to use Docswrite with WordPress" 
                                                frameborder="0" 
                                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                                                allowfullscreen>
                                            </iframe>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
            <?php
        }

        /**
         * Gets the unique website ID for the current site.
         */
        public static function get_website_id() {
            return get_option(self::DOCSWRITE_WEBSITE_ID_OPTION);
        }

        /**
         * Gets the website URL for the current site.
         */
        public static function get_website_url() {
            return get_bloginfo('url');
        }

        /**
         * Gets the website name for the current site.
         */
        public static function get_website_name() {
            $name = get_bloginfo('name');
            
            // If name is empty, get hostname from URL
            if (empty($name)) {
                $url = get_bloginfo('url');
                // Parse URL to get host component
                $parsed_url = parse_url($url);
                $name = $parsed_url['host'];
                // Remove www. if present
                $name = preg_replace('/^www\./', '', $name);
            }
            
            return $name;
        }

        /**
         * Generate Website ID
         */
        private static function generate_website_id() {
            return md5(get_site_url() . wp_generate_uuid4());
        }

        /**
         * Activates the Docswrite plugin by checking and setting the necessary options.
         */
        public static function activate() {
            // If website ID option is empty, set value.
            if (!self::get_website_id()) {
                update_option(self::DOCSWRITE_WEBSITE_ID_OPTION, self::generate_website_id());
            }
        }

        /**
         * Checks if the Docswrite connection is active.
         */
        public static function is_connected() {
            return (bool) get_option(self::DOCSWRITE_CONNECTION_OPTION);
        }

        /**
         * Registers custom REST API routes.
         */
        public static function register_rest_routes() {
            register_rest_route('docswrite/v1', '/docswrite', array(
                'methods' => 'GET',
                'callback' => array('Docswrite', 'rest_callback'),
            ));

            register_rest_route('docswrite/v1', '/update-rank-math', array(
                'methods' => 'POST',
                'callback' => array('Docswrite', 'update_rankmath'),
                'permission_callback' => array('Docswrite', 'permission_check'),
            ));

            register_rest_route('docswrite/v1', '/update-yoast', array(
                'methods' => 'POST',
                'callback' => array('Docswrite', 'update_yoast'),
                'permission_callback' => array('Docswrite', 'permission_check'),
            ));
        }

        /**
         * Callback for the sample GET endpoint.
         */
        public static function rest_callback() {
            return array(
                'message' => 'Hello from the Docswrite REST API endpoint!',
            );
        }

        /**
         * Checks if the current user has permission to modify posts.
         */
        public static function permission_check() {
            if (current_user_can('edit_posts')) {
                return true;
            }
            return new WP_Error('rest_forbidden', 'You do not have permission to modify posts.', array('status' => 401));
        }

        /**
         * Updates Rank Math focus keyword.
         */
        public static function update_rankmath($request) {
            if (!function_exists('rank_math')) {
                return new WP_Error('rank_math_not_installed', 'The Rank Math plugin is not installed.', array('status' => 500));
            }

            $focus_keyword = $request->get_param('rank_math_focus_keyword');
            $post_id = $request->get_param('post_id');

            if (empty($focus_keyword)) {
                return new WP_Error('rank_math_focus_keyword_empty', 'The rank_math_focus_keyword is empty.', array('status' => 500));
            }

            if (empty($post_id)) {
                return new WP_Error('post_id_empty', 'The post_id is empty.', array('status' => 500));
            }

            update_post_meta($post_id, 'rank_math_focus_keyword', $focus_keyword);

            return array(
                'message' => 'The focus keyword has been updated.',
            );
        }

        /**
         * Updates Yoast SEO fields.
         */
        public static function update_yoast($request) {
            if (!class_exists('WPSEO_Options')) {
                return new WP_Error('yoast_not_installed', 'The Yoast plugin is not installed.', array('status' => 500));
            }

            $post_id = $request->get_param('post_id');
            $focuskw = $request->get_param('yoast_wpseo_focuskw');
            $title = $request->get_param('yoast_wpseo_title');
            $metadesc = $request->get_param('yoast_wpseo_metadesc');
            $canonical = $request->get_param('yoast_wpseo_canonical');

            $meta_input = array(
                '_yoast_wpseo_focuskw' => $focuskw,
                '_yoast_wpseo_title' => $title,
                '_yoast_wpseo_metadesc' => $metadesc,
                '_yoast_wpseo_canonical' => $canonical,
            );

            // Social media fields are only written when explicitly provided,
            // so we don't clobber values set manually in Yoast's UI.
            $social_param_map = array(
                'yoast_wpseo_opengraph-title'       => '_yoast_wpseo_opengraph-title',
                'yoast_wpseo_opengraph-description' => '_yoast_wpseo_opengraph-description',
                'yoast_wpseo_opengraph-image'       => '_yoast_wpseo_opengraph-image',
                'yoast_wpseo_twitter-title'         => '_yoast_wpseo_twitter-title',
                'yoast_wpseo_twitter-description'   => '_yoast_wpseo_twitter-description',
                'yoast_wpseo_twitter-image'         => '_yoast_wpseo_twitter-image',
            );
            foreach ( $social_param_map as $param_key => $meta_key ) {
                $value = $request->get_param( $param_key );
                if ( ! empty( $value ) ) {
                    $meta_input[ $meta_key ] = $value;
                }
            }

            $args = array(
                'ID' => $post_id,
                'meta_input' => $meta_input,
            );

            $result = wp_update_post($args);

            if (is_wp_error($result)) {
                return new WP_Error('update_failed', __('Failed to update Yoast SEO fields.', 'docswrite'), array('status' => 500));
            }

            // Resolve attachment IDs for any social images that were just set.
            DocswriteAPI::setup_yoast_social_image_ids( $post_id );

            return array('success' => true);
        }

        /**
         * Enqueues admin assets.
         */
        public static function enqueue_admin_assets($hook) {
            if ('toplevel_page_docswrite' !== $hook) {
                return;
            }   
            
            wp_enqueue_style('docswrite-admin-style', plugin_dir_url(__FILE__) . 'assets/css/admin-style.css', array(), '1.2.22');

            // Enqueue JavaScript
            wp_enqueue_script('docswrite-admin-script', plugin_dir_url(__FILE__) . 'assets/js/admin-script.js', array('jquery'), '1.0.0', true);
            wp_localize_script('docswrite-admin-script', 'docswriteData', array(
                'disconnectConfirmMessage' => __('Do you really want to disconnect the website? Your content synchronization will be stopped.', 'docswrite'),
                'disconnectButtonText' => __('Disconnect', 'docswrite')
            ));
        }
    }

    Docswrite::init();
}

/**
 * Set website_id when plugin is activated
 */
register_activation_hook(__FILE__, array('Docswrite', 'activate'));
