<?php
/**
 * SocialPilot Settings Handler
 *
 * @package SocialPilot
 * @subpackage Settings
 * @since 1.0.0
 */

/**
 * Class to handle plugin settings and admin interface
 */
class SocialPilot_Settings {

    /**
     * Instance of this class
     *
     * @since 1.0.0
     * @var object
     */
    private static $instance = null;

    /**
     * Settings page slug
     *
     * @since 1.0.0
     * @var string
     */
    private $page_slug = 'socialpilot-settings';

    /**
     * Settings group name
     *
     * @since 1.0.0
     * @var string
     */
    private $option_group = 'socialpilot_options';

    /**
     * Get singleton instance
     *
     * @since 1.0.0
     * @return SocialPilot_Settings
     */
    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function enqueue_admin_assets() {
        wp_enqueue_style(
            'socialpilot-admin-settings',
            SOCIALPILOT_PLUGIN_URL . 'assets/css/admin-settings.css',
            array(),
            SOCIALPILOT_VERSION
        );
        wp_enqueue_script(
            'socialpilot-admin-popup',
            SOCIALPILOT_PLUGIN_URL . 'assets/js/admin-popup.js',
            array('jquery'),
            SOCIALPILOT_VERSION,
            true
        );
    }

    
    /**
     * Constructor
     *
     * @since 1.0.0
     */
    private function __construct() {
        add_action( 'admin_menu', array( $this, 'add_menu_page' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'admin_notices', array( $this, 'display_admin_notices' ) );
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
        add_action('wp_ajax_socialpilot_save_api_key', array($this,'socialpilot_save_api_key'));
    }


    public function socialpilot_save_api_key() {
        if (isset($_POST['api_key'])) {
            $api_key = sanitize_text_field($_POST['api_key']);

            $options = get_option('socialpilot_options', []);
            $options['api_key'] = $api_key;
            update_option('socialpilot_options', $options);

            wp_send_json_success(['message' => 'API key saved.']);
        } else {
            wp_send_json_error(['message' => 'No API key provided.']);
        }
    }

    /**
     * Add settings menu page
     *
     * @since 1.0.0
     * @return void
     */
    public function add_menu_page() {
        add_options_page(
            __( 'SocialPilot Settings', 'socialpilot-wp' ),
            __( '😊 SocialPilot', 'socialpilot-wp' ),
            'manage_options',
            $this->page_slug,
            array( $this, 'render_settings_page' ),
        );
    }

    /**
     * Register plugin settings
     *
     * @since 1.0.0
     * @return void
     */
    public function register_settings() {
        register_setting(
            $this->option_group,
            'socialpilot_options',
            array( $this, 'sanitize_settings' )
        );

        add_settings_section(
            'socialpilot_main_section',
            __( 'API Configuration', 'socialpilot-wp' ),
            array( $this, 'render_section_info' ),
            $this->page_slug
        );

        add_settings_field(
            'api_key',
            __( 'API Key', 'socialpilot-wp' ),
            array( $this, 'render_api_key_field' ),
            $this->page_slug,
            'socialpilot_main_section'
        );

        add_settings_field(
            'post_types',
            __( 'Enable for Post Types', 'socialpilot-wp' ),
            array( $this, 'render_post_types_field' ),
            $this->page_slug,
            'socialpilot_main_section'
        );
    }

    /**
     * Sanitize settings input
     *
     * @since 1.0.0
     * @param array $input Raw input data.
     * @return array Sanitized input
     */
    public function sanitize_settings( $input ) {
        $sanitized_input = array();
        
        if ( isset( $input['api_key'] ) ) {
            $api_key = sanitize_text_field( $input['api_key'] );
            $sanitized_input['api_key'] = SocialPilot_Encrypt::encrypt( $api_key );
        }

        if ( isset( $input['enabled_post_types'] ) && is_array( $input['enabled_post_types'] ) ) {
            $sanitized_input['enabled_post_types'] = array_map( 
                'sanitize_text_field', 
                $input['enabled_post_types'] 
            );
        }

        return $sanitized_input;
    }

    /**
     * Render settings page
     *
     * @since 1.0.0
     * @return void
     */
    public function render_settings_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }
        ?>
        <div class="wrap">
            <!-- Header Banner -->
            <h1 class="socialpilot-wp-plugin-sp-label">
            </h1>
            <div class="socialpilot-wp-plugin-main-div">
                <div class="socialpilot-wp-plugin-sp-logo">
                    <img src="https://www.socialpilot.co/wp-content/uploads/2022/12/socialpilot.svg" 
                        alt="SocialPilot Logo">
                    <h1 class="socialpilot-wp-plugin-sp-label">
                        <?php echo esc_html__('Settings', 'socialpilot-wp'); ?>
                        <span class="socialpilot-version">v<?php echo SOCIALPILOT_VERSION; ?></span>
                    </h1>
                </div>
            </div>

            <!-- Main Content Grid -->
            <div class="socialpilot-settings-wrapper">
                <!-- Left Column: Settings -->
                <div class="socialpilot-main-settings">
                    <form method="post" action="options.php" class="socialpilot-settings-form">
                        <?php
                        settings_fields($this->option_group);
                        do_settings_sections($this->page_slug);
                        submit_button();
                        ?>
                    </form>
                </div>

                <!-- Right Column: Sidebar -->
                <div class="socialpilot-sidebar">
                    <!-- Ratings & Reviews Box -->
                    <div class="socialpilot-sidebar-box">
                        <h3><?php echo esc_html__('Manage Accounts', 'socialpilot-wp'); ?></h3>
                        <p>
                            <?php 
                            echo sprintf(
                                /* translators: %s: Plugin name */
                                esc_html__('Connect your SocialMedia Account to SocialPilot and start scheduling/publishing posts seamlessly.', 'socialpilot-wp'),
                            );
                            ?>
                        </p>
                        <p><?php echo esc_html__('Click the “Connect Account” button below to get started.', 'socialpilot-wp'); ?></p>
                        <a href="https://app.socialpilot.co/accounts" 
                        target="_blank" 
                        class="socialpilot-btn">
                            <?php echo esc_html__('Connect Account', 'socialpilot-wp'); ?>
                        </a>
                    </div>

                    <!-- Ratings & Reviews Box -->
                    <div class="socialpilot-sidebar-box">
                        <h3><?php echo esc_html__('Ratings & Reviews', 'socialpilot-wp'); ?></h3>
                        <p>
                            <?php 
                            echo sprintf(
                                /* translators: %s: Plugin name */
                                esc_html__('If you like %s please consider leaving a %s rating.', 'socialpilot-wp'),
                                '<strong>SocialPilot</strong>',
                                '<span class="socialpilot-rating-stars">★★★★★</span>'
                            );
                            ?>
                        </p>
                        <p><?php echo esc_html__('A huge thanks in advance!', 'socialpilot-wp'); ?></p>
                        <a href="https://wordpress.org/support/plugin/socialpilot/reviews/#new-post" 
                        target="_blank" 
                        class="socialpilot-btn">
                            <?php echo esc_html__('Leave a Rating', 'socialpilot-wp'); ?>
                        </a>
                    </div>

                    <!-- Support Box -->
                    <div class="socialpilot-sidebar-box">
                        <h3><?php echo esc_html__('Need Help?', 'socialpilot-wp'); ?></h3>
                        <p><?php echo esc_html__('Having trouble? Get help from our support team.', 'socialpilot-wp'); ?></p>
                        <a href="https://www.socialpilot.co/support" 
                        target="_blank" 
                        class="socialpilot-btn">
                            <?php echo esc_html__('Get Support', 'socialpilot-wp'); ?>
                        </a>
                    </div>

                    <!-- Documentation Box -->
                    <div class="socialpilot-sidebar-box">
                        <h3><?php echo esc_html__('Documentation', 'socialpilot-wp'); ?></h3>
                        <p><?php echo esc_html__('Learn how to use all features of SocialPilot WordPress plugin.', 'socialpilot-wp'); ?></p>
                        <a href="https://www.socialpilot.co/docs/wordpress" 
                        target="_blank" 
                        class="socialpilot-btn">
                            <?php echo esc_html__('View Documentation', 'socialpilot-wp'); ?>
                        </a>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render section information
     *
     * @since 1.0.0
     * @return void
     */
    public function render_section_info() {
        ?>
        <p>
            <?php
            esc_html_e( 
                'Configure your SocialPilot API settings below. You can find your API key in your SocialPilot account settings.',
                'socialpilot-wp'
            );
            ?>
        </p>
        <?php
    }

    /**
     * Render API key field
     *
     * @since 1.0.0
     * @return void
     */
    public function render_api_key_field() {
        $options = get_option( 'socialpilot_options', array() );
        $api_key = isset( $options['api_key'] ) ? 
            SocialPilot_Encrypt::decrypt( $options['api_key'] ) : '';
        ?>
        <input type="text" 
               id="socialpilot_api_key" 
               name="socialpilot_options[api_key]" 
               value="<?php echo esc_attr( $api_key ); ?>" 
               class="regular-text"
        />
        <p class="description">
            <?php
            esc_html_e( 
                'Enter your SocialPilot API key. Keep this key secure.',
                'socialpilot-wp'
            );
            ?>
        </p>
        <?php
    }

    /**
     * Render post types field
     *
     * @since 1.0.0
     * @return void
     */
    public function render_post_types_field() {
        $options = get_option( 'socialpilot_options', array() );
        $enabled_types = isset( $options['enabled_post_types'] ) ? 
            $options['enabled_post_types'] : array( 'post' );
        
        $post_types = get_post_types( array( 'public' => true ), 'objects' );
        
        foreach ( $post_types as $post_type ) {
            ?>
            <label style="display: block; margin-bottom: 8px;">
                <input type="checkbox" 
                       name="socialpilot_options[enabled_post_types][]" 
                       value="<?php echo esc_attr( $post_type->name ); ?>"
                       <?php checked( in_array( $post_type->name, $enabled_types, true ) ); ?>>
                <?php echo esc_html( $post_type->label ); ?>
            </label>
            <?php
        }
        ?>
        <p class="description">
            <?php 
            esc_html_e( 
                'Select which post types should have SocialPilot integration.',
                'socialpilot-wp'
            ); 
            ?>
        </p>
        <?php
    }

    /**
     * Display admin notices
     *
     * @since 1.0.0
     * @return void
     */
    public function display_admin_notices() {
        // Show welcome notice after activation
        /*
        if ( get_option( 'socialpilot_do_activation_redirect', false ) ) {
            delete_option( 'socialpilot_do_activation_redirect' );
            ?>
            <div class="notice notice-info is-dismissible">
                <p>
                    <?php 
                    echo wp_kses(
                        sprintf(
                            // translators: %s: Settings page URL
                            __( 'Welcome to SocialPilot! Please <a href="%s">configure your API settings</a> to get started.', 'socialpilot-wp' ),
                            esc_url( admin_url( 'options-general.php?page=' . $this->page_slug ) )
                        ),
                        array(
                            'a' => array(
                                'href' => array()
                            )
                        )
                    );
                    ?>
                </p>
            </div>
            <?php
        } */

        // Show warning if API key is not configured
        $options = get_option( 'socialpilot_options', array() );
        // Only show the tooltip if NOT on the settings page
        $current_screen = isset($_GET['page']) ? sanitize_text_field($_GET['page']) : '';
        if ( empty( $options['api_key'] ) && $current_screen !== $this->page_slug ) {
            ?>
            <div class="notice notice-info is-dismissible">
                <div class="socialpilot-welcome-banner">
                    <div class="socialpilot-welcome-header">
                        <img src="https://www.socialpilot.co/wp-content/uploads/2022/12/socialpilot.svg" alt="SocialPilot Logo" class="socialpilot-welcome-logo">
                        <h2><?php echo esc_html__('Share your WordPress posts on all major social networks in just a few clicks.', 'socialpilot-wp'); ?></h2>
                    </div>
                    <div class="socialpilot-welcome-options">
                        <!-- Create Account Option -->
                        <div class="socialpilot-option">
                            <div class="socialpilot-option-icon">
                                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M12 12C14.7614 12 17 9.76142 17 7C17 4.23858 14.7614 2 12 2C9.23858 2 7 4.23858 7 7C7 9.76142 9.23858 12 12 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                    <path d="M20.5899 22C20.5899 18.13 16.7399 15 11.9999 15C7.25991 15 3.40991 18.13 3.40991 22" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                </svg>
                            </div>
                            <h3><?php echo esc_html__('Let’s Get Started', 'socialpilot-wp'); ?></h3>
                            <p><?php echo esc_html__("New to SocialPilot? Create your account to start scheduling posts.", 'socialpilot-wp'); ?></p>
                            <a href="#" id="socialpilot-signup-btn" class="socialpilot-welcome-btn socialpilot-btn-primary">
                                <?php echo esc_html__("Create Account", 'socialpilot-wp'); ?>
                            </a>
                        </div>

                        <!-- Add API Key Option -->
                        <div class="socialpilot-option">
                            <div class="socialpilot-option-icon">
                                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <rect x="3" y="11" width="18" height="11" rx="2" ry="2" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                    <circle cx="12" cy="16" r="1" fill="currentColor"/>
                                    <path d="M7 11V7a5 5 0 0 1 10 0v4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                </svg>
                            </div>
                            <h3><?php echo esc_html__('Add Your API Key', 'socialpilot-wp'); ?></h3>
                            <p>
                                <?php 
                                echo sprintf(
                                    /* translators: %s: settings page link */
                                    esc_html__('Already have an account? Add your API key to connect SocialPilot.', 'socialpilot-wp'),
                                );
                                ?>
                            </p>
                            <a href="#" id="socialpilot-apikey-btn" class="socialpilot-welcome-btn socialpilot-btn-secondary">
                                <?php echo esc_html__('Link Your Account', 'socialpilot-wp'); ?>
                            </a>
                        </div>

                        <!-- Go to Settings Option -->
                        <div class="socialpilot-option">
                            <div class="socialpilot-option-icon">
                                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <circle cx="12" cy="12" r="3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                    <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1 1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                </svg>
                            </div>
                            <h3><?php echo esc_html__('Configure Settings', 'socialpilot-wp'); ?></h3>
                            <p><?php echo esc_html__("You’re almost done. Finish setup to start posting.", 'socialpilot-wp'); ?></p>
                            <a href="<?php echo esc_url( admin_url( 'options-general.php?page=' . $this->page_slug ) ); ?>" class="socialpilot-welcome-btn socialpilot-btn-primary">
                                <?php echo esc_html__('Open Settings', 'socialpilot-wp'); ?>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Email Modal -->
            <div id="socialpilot-signup-modal" style="display:none;position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(0,0,0,0.5);z-index:9999;">
                <div style="background:#fff;padding:30px;max-width:400px;margin:100px auto;position:relative;border-radius:8px;">
                    <button id="socialpilot-signup-close" class="btn" style="position: absolute;top: 4px;right: 4px; cursor: pointer; z-index:9999">
                        <svg width="24px" height="24px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path fill-rule="evenodd" clip-rule="evenodd" d="M5.29289 5.29289C5.68342 4.90237 6.31658 4.90237 6.70711 5.29289L12 10.5858L17.2929 5.29289C17.6834 4.90237 18.3166 4.90237 18.7071 5.29289C19.0976 5.68342 19.0976 6.31658 18.7071 6.70711L13.4142 12L18.7071 17.2929C19.0976 17.6834 19.0976 18.3166 18.7071 18.7071C18.3166 19.0976 17.6834 19.0976 17.2929 18.7071L12 13.4142L6.70711 18.7071C6.31658 19.0976 5.68342 19.0976 5.29289 18.7071C4.90237 18.3166 4.90237 17.6834 5.29289 17.2929L10.5858 12L5.29289 6.70711C4.90237 6.31658 4.90237 5.68342 5.29289 5.29289Z" fill="#0F1729"/>
                        </svg>
                            </button>
                    <div id="static-root"></div>
                    <div id="static-portal-root"></div>
                    <script>
                            var existingScript = document.getElementById('react-js-static');
                            if (!existingScript) {
                                var script = document.createElement('script');
                                script.src = 'https://sp-react-static-form.s3.amazonaws.com/main.js?v2.5';
                                script.id = 'react-js-static';
                                document.body.appendChild(script);
                                script.onload = () => {
                                window.postMessage({"command":"wpPluginSignup"});
                                };
                            }
                            window.addEventListener('message', function(event) {
                                if (event.data && event.data.command === 'signup-success') {
                                    // Send the API key to the server
                                    fetch(ajaxurl, {
                                        method: 'POST',
                                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                                        body: new URLSearchParams({
                                            action: 'socialpilot_save_api_key',
                                            api_key: event.data.data.apiKey
                                        })
                                    })
                                    .then(response => response.json())
                                    .then(data => {
                                        if (data.success) {
                                            jQuery('#socialpilot-signup-close').click();
                                            // redirect to settings page
                                            window.location.href = '<?php echo esc_url( admin_url( 'options-general.php?page=' . $this->page_slug ) ); ?>';
                                        } else {
                                            alert('Failed to save API Key.');
                                        }
                                    })
                                    .catch(err => console.error('Error:', err));
                                }
                            });
                    </script> 

                    <!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> -->
                </div>
            </div>
            <!-- API Key Modal -->
            <div id="socialpilot-apikey-modal" style="display:none;position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(0,0,0,0.5);z-index:9999;">
                <div style="background:#fff;padding:30px;max-width:400px;margin:100px auto;position:relative;border-radius:8px;">
                    <a id="socialpilot-apikey-close" class="btn" style="position: absolute;top: 10px;right: 10px; cursor: pointer;">
                        <svg width="24px" height="24px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path fill-rule="evenodd" clip-rule="evenodd" d="M5.29289 5.29289C5.68342 4.90237 6.31658 4.90237 6.70711 5.29289L12 10.5858L17.2929 5.29289C17.6834 4.90237 18.3166 4.90237 18.7071 5.29289C19.0976 5.68342 19.0976 6.31658 18.7071 6.70711L13.4142 12L18.7071 17.2929C19.0976 17.6834 19.0976 18.3166 18.7071 18.7071C18.3166 19.0976 17.6834 19.0976 17.2929 18.7071L12 13.4142L6.70711 18.7071C6.31658 19.0976 5.68342 19.0976 5.29289 18.7071C4.90237 18.3166 4.90237 17.6834 5.29289 17.2929L10.5858 12L5.29289 6.70711C4.90237 6.31658 4.90237 5.68342 5.29289 5.29289Z" fill="#0F1729"/>
                        </svg>
                            </a>
                    <?php
                    if ( isset($_POST['submit_socialpilot_api']) && check_admin_referer('save_socialpilot_api', 'socialpilot_api_nonce') ) {
                        $options = get_option('socialpilot_options', []);
                        $options['api_key'] = sanitize_text_field($_POST['api_key']);
                        update_option('socialpilot_options', $options);
                        echo '<div class="updated"><p>API Key saved!</p></div>';
                        //  redirect to settings page
                        echo '<script>setTimeout(function(){ window.location.href = "' . esc_url( admin_url( 'options-general.php?page=' . $this->page_slug ) ) . '"; }, 0);</script>';

                    }
                    $options = get_option('socialpilot_options', []);
                    $api_key = isset($options['api_key']) ? esc_attr($options['api_key']) : '';
                    ?>
                    <form method="post" action="">
                        <?php wp_nonce_field('save_socialpilot_api', 'socialpilot_api_nonce'); ?>
                        <h2><?php echo esc_html__('Enter Your API Key', 'socialpilot-wp'); ?></h2>
                        <input type="text" name="api_key" id="api_key" value="<?php echo $api_key; ?>"  placeholder="Paste your API key here" style="width:100%;padding:8px;"/>
                        <?php submit_button('Connect', 'primary', 'submit_socialpilot_api'); ?>
                    </form>

                </div>
            </div>
            <?php
        }
    }
}