<?php
/**
 * Load plugin text domain for translations.
 */

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

// Check if Pro version is active
if ( ! function_exists( 'is_plugin_active' ) ) {
    require_once ABSPATH . 'wp-admin/includes/plugin.php';
}

$pro_plugin = 'postology-pro/postology-plugin.php';
if ( is_plugin_active( $pro_plugin ) ) {
    return; // Do nothing if Pro plugin is active
}

// Include all component files.
require_once plugin_dir_path(__FILE__) . 'components/dashboard.php';
require_once plugin_dir_path(__FILE__) . 'components/general.php';
require_once plugin_dir_path(__FILE__) . 'components/content-config.php';
require_once plugin_dir_path(__FILE__) . 'components/customization.php';
require_once plugin_dir_path(__FILE__) . 'components/license.php';

class PostologySettings {
    private $tabs;

    /**
     * Constructor to initialize settings hooks
     */
    public function __construct() {
        // Add menu page
        add_action('admin_menu', array($this, 'add_menu_page'));

        // Register settings
        add_action('admin_init', array($this, 'register_settings'));

        // Enqueue admin scripts
        add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'));

        // Handle reset styles action
        add_action('admin_init', array($this, 'handle_reset_styles'));

        // Updated tabs array with dashboard included.
        $this->tabs = array(
            'dashboard'     => __('Dashboard', 'postology'),
            'general'       => __('General Settings', 'postology'),
            'api'           => __('API Configuration', 'postology'),
            'content'       => __('Content Configuration', 'postology'),
            'customization' => __('Customization', 'postology'),
            'analytics'     => __('Analytics', 'postology'),
            'license'       => __('License', 'postology'),
        );
    }

    /**
     * Add menu page
     */
    public function add_menu_page() {
        add_menu_page(
            __('Postology Settings', 'postology'),
            __('Postology', 'postology'),
            'manage_options',
            'postology-settings',
            array($this, 'render_settings_page'),
            'dashicons-sticky',
            20
        );

         // Remove the automatically added submenu item.
         remove_submenu_page('postology-settings', 'postology-settings');

         // Add a submenu page for each tab.
         foreach ($this->tabs as $tab_key => $tab_label) {
             add_submenu_page(
                 'postology-settings',                     // Parent slug.
                 $tab_label,                               // Page title.
                 $tab_label,                               // Menu title.
                 'manage_options',                         // Capability.
                 'postology-' . $tab_key,                   // Menu slug.
                 function() use ($tab_key) {                // Callback.
                     // Set the tab to display.
                     $_GET['tab'] = $tab_key;
                     $this->render_settings_page();
                 }
             );
         }
    }

    /**
     * Get user details.
     */
    public static function get_user_from_website() {
        $website = site_url();
        $user_info = array(
            'email' => '',
            'credits' => 0,
            'website' => '',
        );
        $cache_buster = time();

        $url = add_query_arg(
            array(
                'website'   => $website,
                'cache_buster'  => $cache_buster,
            ),
            'https://postology-pro.com/wp-json/credit-manager/get-user'
            // 'http://localhost/postology/wp-json/credit-manager/get-user'
        );
        $args = array(
            'timeout' => 15,
            'headers' => array(
                'Cache-Control' => 'no-cache, no-store, must-revalidate',
                'Pragma' => 'no-cache',
                'Expires' => '0',
            ),
        );
        $response = wp_remote_get($url, $args);

        if (!is_wp_error($response)) {
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
            if (isset($data)) {
                if (json_last_error() === JSON_ERROR_NONE && isset($data['email'])) {
                    $user_info['email'] = $data['email'];
                    $user_info['credits'] = isset($data['credits']) ? intval($data['credits']) : 0;
                    $user_info['website'] = $website;
                }
            }
        }

        return $user_info;
    }

    /**
     * Render settings page
     */
    public function render_settings_page() {
        // Sanitize and unslash the tab parameter safely
        $tab = isset($_GET['tab']) ? sanitize_text_field(wp_unslash($_GET['tab'])) : 'dashboard';
    
        // Get user information
        $user_info = $this->get_user_from_website();
        $allowed_tabs = ['dashboard', 'general', 'content', 'customization', 'license'];
        ?>
        <div class="pgy-stgs-wrap">
            <div class="pgy-top-bar">
                <section style="display:flex;align-items:center;">
                    <h1 style="font-size:2rem;">
                        <?php esc_html_e('Postology Settings', 'postology'); ?>
                    </h1>
                </section>
            </div>
            <p style="font-size: 16px; margin-bottom: 20px;">
                <?php esc_html_e('New to Postology?', 'postology'); ?>
                <a href="https://postology-pro.tawk.help/category/getting-started" target="_blank">
                    <?php esc_html_e('Get Started Here', 'postology'); ?>
                </a>
            </p>
            <div class="nav-tab-wrapper">
                <?php
                foreach ($this->tabs as $tab_key => $tab_label) {
                     // Enable dashboard along with license, content, and general tabs.
                    if (in_array($tab_key, $allowed_tabs)) {
                        echo '<a href="?page=postology-settings&tab=' . esc_attr($tab_key) . '" class="nav-tab ' . ($tab == $tab_key ? 'nav-tab-active' : '') . '">' . esc_html($tab_label) . '</a>';
                    } else {
                        echo '<a href="#" class="nav-tab nav-tab-disabled" style="display:flex;gap:6px;">
                        <svg style="width:21px;" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path fill-rule="evenodd" clip-rule="evenodd" d="M5.25 10.0546V8C5.25 4.27208 8.27208 1.25 12 1.25C15.7279 1.25 18.75 4.27208 18.75 8V10.0546C19.8648 10.1379 20.5907 10.348 21.1213 10.8787C22 11.7574 22 13.1716 22 16C22 18.8284 22 20.2426 21.1213 21.1213C20.2426 22 18.8284 22 16 22H8C5.17157 22 3.75736 22 2.87868 21.1213C2 20.2426 2 18.8284 2 16C2 13.1716 2 11.7574 2.87868 10.8787C3.40931 10.348 4.13525 10.1379 5.25 10.0546ZM6.75 8C6.75 5.10051 9.10051 2.75 12 2.75C14.8995 2.75 17.25 5.10051 17.25 8V10.0036C16.867 10 16.4515 10 16 10H8C7.54849 10 7.13301 10 6.75 10.0036V8ZM14 16C14 17.1046 13.1046 18 12 18C10.8954 18 10 17.1046 10 16C10 14.8954 10.8954 14 12 14C13.1046 14 14 14.8954 14 16Z" fill="#1C274C"></path> </g></svg>' . " " . esc_html($tab_label) . '</a>';
                    }
                }
                ?>
                <a href="https://postology-pro.tawk.help/" target="_blank" class="nav-tab" style="display:flex;gap:6px;">
                    <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="width:15px;">
                        <g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <g id="Interface / External_Link"> <path id="Vector" d="M10.0002 5H8.2002C7.08009 5 6.51962 5 6.0918 5.21799C5.71547 5.40973 5.40973 5.71547 5.21799 6.0918C5 6.51962 5 7.08009 5 8.2002V15.8002C5 16.9203 5 17.4801 5.21799 17.9079C5.40973 18.2842 5.71547 18.5905 6.0918 18.7822C6.5192 19 7.07899 19 8.19691 19H15.8031C16.921 19 17.48 19 17.9074 18.7822C18.2837 18.5905 18.5905 18.2839 18.7822 17.9076C19 17.4802 19 16.921 19 15.8031V14M20 9V4M20 4H15M20 4L13 11" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path> </g> </g>
                    </svg>
                    <?php esc_html_e('Help and Support', 'postology'); ?>
                </a>
                <a href="https://postology-pro.com" target="_blank" class="nav-tab" style="display:flex;gap:6px;">
                    <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="width:24px;">
                        <g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M10.5766 8.70419C11.2099 7.56806 11.5266 7 12 7C12.4734 7 12.7901 7.56806 13.4234 8.70419L13.5873 8.99812C13.7672 9.32097 13.8572 9.48239 13.9975 9.5889C14.1378 9.69541 14.3126 9.73495 14.6621 9.81402L14.9802 9.88601C16.2101 10.1643 16.825 10.3034 16.9713 10.7739C17.1176 11.2443 16.6984 11.7345 15.86 12.715L15.643 12.9686C15.4048 13.2472 15.2857 13.3865 15.2321 13.5589C15.1785 13.7312 15.1965 13.9171 15.2325 14.2888L15.2653 14.6272C15.3921 15.9353 15.4554 16.5894 15.0724 16.8801C14.6894 17.1709 14.1137 16.9058 12.9622 16.3756L12.6643 16.2384C12.337 16.0878 12.1734 16.0124 12 16.0124C11.8266 16.0124 11.663 16.0878 11.3357 16.2384L11.0378 16.3756C9.88634 16.9058 9.31059 17.1709 8.92757 16.8801C8.54456 16.5894 8.60794 15.9353 8.7347 14.6272L8.76749 14.2888C8.80351 13.9171 8.82152 13.7312 8.76793 13.5589C8.71434 13.3865 8.59521 13.2472 8.35696 12.9686L8.14005 12.715C7.30162 11.7345 6.88241 11.2443 7.02871 10.7739C7.17501 10.3034 7.78993 10.1643 9.01977 9.88601L9.33794 9.81402C9.68743 9.73495 9.86217 9.69541 10.0025 9.5889C10.1428 9.48239 10.2328 9.32097 10.4127 8.99812L10.5766 8.70419Z" fill="#1C274C"></path> <path opacity="0.8" fill-rule="evenodd" clip-rule="evenodd" d="M12 1.25C12.4142 1.25 12.75 1.58579 12.75 2V4C12.75 4.41421 12.4142 4.75 12 4.75C11.5858 4.75 11.25 4.41421 11.25 4V2C11.25 1.58579 11.5858 1.25 12 1.25ZM1.25 12C1.25 11.5858 1.58579 11.25 2 11.25H4C4.41421 11.25 4.75 11.5858 4.75 12C4.75 12.4142 4.41421 12.75 4 12.75H2C1.58579 12.75 1.25 12.4142 1.25 12ZM19.25 12C19.25 11.5858 19.5858 11.25 20 11.25H22C22.4142 11.25 22.75 11.5858 22.75 12C22.75 12.4142 22.4142 12.75 22 12.75H20C19.5858 12.75 19.25 12.4142 19.25 12ZM12 19.25C12.4142 19.25 12.75 19.5858 12.75 20V22C12.75 22.4142 12.4142 22.75 12 22.75C11.5858 22.75 11.25 22.4142 11.25 22V20C11.25 19.5858 11.5858 19.25 12 19.25Z" fill="#1C274C"></path> <g opacity="0.5"> <path d="M18.5304 5.46967C18.8233 5.76256 18.8233 6.23744 18.5304 6.53033L18.1872 6.87359C17.8943 7.16648 17.4194 7.16648 17.1265 6.87359C16.8336 6.5807 16.8336 6.10583 17.1265 5.81293L17.4698 5.46967C17.7627 5.17678 18.2376 5.17678 18.5304 5.46967Z" fill="#1C274C"></path> <path d="M5.46967 5.46979C5.76256 5.17689 6.23744 5.17689 6.53033 5.46979L6.87359 5.81305C7.16648 6.10594 7.16648 6.58081 6.87359 6.87371C6.5807 7.1666 6.10583 7.1666 5.81293 6.87371L5.46967 6.53045C5.17678 6.23755 5.17678 5.76268 5.46967 5.46979Z" fill="#1C274C"></path> <path d="M6.87348 17.1266C7.16637 17.4195 7.16637 17.8944 6.87348 18.1873L6.53043 18.5303C6.23754 18.8232 5.76266 18.8232 5.46977 18.5303C5.17688 18.2375 5.17688 17.7626 5.46977 17.4697L5.81282 17.1266C6.10571 16.8337 6.58058 16.8337 6.87348 17.1266Z" fill="#1C274C"></path> <path d="M17.1265 17.1269C17.4194 16.834 17.8943 16.834 18.1872 17.1269L18.5302 17.4699C18.8231 17.7628 18.8231 18.2377 18.5302 18.5306C18.2373 18.8235 17.7624 18.8235 17.4695 18.5306L17.1265 18.1875C16.8336 17.8946 16.8336 17.4198 17.1265 17.1269Z" fill="#1C274C"></path> </g> </g>
                    </svg>
                    <?php esc_html_e('Go Pro', 'postology') ?>
                </a>
            </div>
    
            <?php
            // Render the content based on the selected tab.
            if (in_array($tab, ['dashboard', 'general', 'content', 'customization', 'license'])) {
            ?>
                <form method="post" action="options.php">
                    <?php
                    settings_fields("postology_{$tab}_options_group");
                    if ($tab === 'dashboard') {
                        render_dashboard_component();
                    } else if ($tab == 'content') {
                        render_content_configuration_component();
                        submit_button();
                    } else if ($tab == 'general') {
                        render_general_settings_component();
                        submit_button();
                    } else if ($tab == 'customization') {
                        $active_subtab = isset($_GET['subtab']) ? sanitize_text_field($_GET['subtab']) : 'basic';
                        ?>
                        <section class="nav-tab-wrapper">
                            <a href="?page=postology-settings&tab=customization&subtab=basic" class="nav-tab <?php echo ($active_subtab == 'basic' ? 'nav-tab-active' : ''); ?>">Basic</a>
                            <a href="?page=postology-settings&tab=customization&subtab=advance" class="nav-tab <?php echo ($active_subtab == 'advance' ? 'nav-tab-active' : ''); ?>">Advance</a>
                        </section>
                        <?php
                        if ($active_subtab == "advance") {
                            settings_fields('postology_customization_options_group');
                            render_advanced_customization_component();
                            submit_button(__('Reset Styles', 'postology-pro'), 'secondary', 'postology_reset_styles', false);
                        } elseif ($active_subtab == "basic") {
                            settings_fields('postology_basic_customization_options_group');
                            render_basic_customization_component();
                        }
                        wp_nonce_field('postology_reset_styles_nonce', 'postology_reset_styles_nonce_field');
                        submit_button();
                    } else if ($tab == 'license') {
                        render_license_key_component();
                    } else {
                        do_settings_sections("postology-settings-{$tab}");
                    }
                    wp_nonce_field('postology_save_settings', 'postology_nonce');                    
                    ?>
                </form>
            <?php
            } else {
                echo '<p>' . esc_html__('Please enter a valid license key to access this section.', 'postology') . '</p>';
            }
            ?>
        </div>
        <?php
    }  

    /**
     * Get customization settings.
     */
    private function get_customization_settings() {
        return array(
            // Header Text
            'postology_header_font_size',
            'postology_header_font_family',
            'postology_header_font_weight',
            'postology_header_font_color',
            'postology_header_line_height',
            // Summary Heading Text
            'postology_summary_heading_font_size',
            'postology_summary_heading_font_family',
            'postology_summary_heading_font_weight',
            'postology_summary_heading_font_color',
            'postology_summary_heading_line_height',
            // Summary background
            'postology_summary_background_color',
            // Button Text
            'postology_button_font_size',
            'postology_button_font_family',
            'postology_button_font_weight',
            'postology_button_font_color',
            'postology_button_line_height',
            // Bullet Points Text
            'postology_bullet_points_font_size',
            'postology_bullet_points_font_family',
            'postology_bullet_points_font_weight',
            'postology_bullet_points_font_color',
            'postology_bullet_points_line_height',
            // Main Container
            'postology_main_container_background_color',
            'postology_main_container_border_radius',
            'postology_main_container_border_color',
            'postology_main_container_border_shadow',
            // Inner Container
            'postology_inner_container_background_color',
            'postology_inner_container_border_radius',
            'postology_inner_container_border_color',
            'postology_inner_container_border_shadow',
            // Button Container
            'postology_button_background_color',
            'postology_button_border_radius',
            'postology_button_border_color',
            // Icon Style
            'postology_box_icon_color'
        );
    }

    /**
     * Register settings
     */
    public function register_settings() {  
        /**
         * dashboard Settings
         */
        register_setting('postology_dashboard_options_group', 'postology_heading_text', 'sanitize_text_field');
        register_setting('postology_dashboard_options_group', 'postology_button_text', 'sanitize_text_field');

        add_settings_section(
            'postology_dashboard_settings_section',
            __('Dashboard Settings', 'postology'),
            null,
            'postology-settings-dashboard'
        );
        

        /**
         * General Settings
         */
        register_setting('postology_general_options_group', 'postology_heading_text', 'sanitize_text_field');
        register_setting('postology_general_options_group', 'postology_summary_heading_text', 'sanitize_text_field');
        register_setting('postology_general_options_group', 'postology_summary_language', 'sanitize_text_field');
        register_setting('postology_general_options_group', 'postology_button_text', 'sanitize_text_field');
        register_setting('postology_general_options_group', 'postology_bullet_point_length', 'sanitize_text_field');
        register_setting('postology_general_options_group', 'postology_summary_tone', 'sanitize_text_field');
        register_setting('postology_general_options_group', 'postology_display_powered_by');

        add_settings_section(
            'postology_general_settings_section',
            __('General Settings', 'postology'),
            null,
            'postology-settings-general'
        );

        /**
         * Content Configuration
         */
        register_setting('postology_content_options_group', 'postology_selectors', 'sanitize_text_field');
        register_setting('postology_content_options_group', 'postology_find_elements', 'sanitize_text_field');
        register_setting('postology_content_options_group', 'postology_excluded_classes', 'sanitize_text_field');

        add_settings_section(
            'postology_content_settings_section',
            __('Content Configuration', 'postology'),
            null,
            'postology-settings-content'
        );

        // Customization Settings.
        $basic_customizations = array(
            'postology_box_icon_color',
            'postology_main_container_background_color',
            'postology_inner_container_background_color',
            'postology_button_background_color',
            'postology_summary_background_color',
            'postology_header_font_color',
            'postology_summary_heading_font_color',
            'postology_button_font_color',
            'postology_button_border_color',
            'postology_bullet_points_font_color'
        );
        foreach ($basic_customizations as $setting) {
            register_setting('postology_basic_customization_options_group', $setting);
        }
        add_settings_section(
            'postology_basic_customization_settings_section',
            __('Basic Theme Settings', 'postology-pro'),
            null,
            'postology-settings-basic-customization'
        );
        $customization_settings = $this->get_customization_settings();
        foreach ($customization_settings as $setting) {
            register_setting('postology_customization_options_group', $setting);
        }
        add_settings_section(
            'postology_customization_settings_section',
            __('Theme Settings', 'postology-pro'),
            null,
            'postology-settings-customization'
        );

        /**
         * License Settings
         */
        register_setting('postology_license_options_group', 'postology_license_key', 'sanitize_text_field');

        add_settings_section(
            'postology_license_settings_section',
            __('License Key', 'postology'),
            null,
            'postology-settings-license'
        );
    }

    /**
     * Handle Reset Styles action
     */
    public function handle_reset_styles() {
        if (isset($_POST['postology_reset_styles'])) {
            check_admin_referer('postology_reset_styles_nonce', 'postology_reset_styles_nonce_field');

            // Define all customization settings
            $customization_settings = $this->get_customization_settings();

            // Remove each customization setting
            foreach ($customization_settings as $setting) {
                delete_option($setting);
            }

            // Redirect back to the settings page
            wp_redirect(add_query_arg(array('page' => 'postology-settings', 'tab' => 'customization', 'reset' => 'success'), admin_url('admin.php')));
            exit;
        }
    }

    /**
     * Enqueue admin scripts
     */
    public function admin_enqueue_scripts($hook) {
        // if ($hook != 'toplevel_page_postology-settings') {
        //     return;
        // }
        if (isset($_GET['page'])) {
            wp_enqueue_style(
                'postology-settings-style',
                plugin_dir_url(__FILE__) . '../assets/css/settings.css',
                array(),
                '0.0.1'
            );
        }
        wp_enqueue_style('postology-settings-style', plugin_dir_url(__FILE__) . '../assets/css/settings.css', array(), '0.0.1');

        $version = defined( 'POSTOLOGY_VERSION' ) ? POSTOLOGY_VERSION : '1.0.0';
        wp_enqueue_script('postology-admin-script', plugin_dir_url(__FILE__) . '../assets/js/postology-admin.js', array(
            'wp-color-picker',   // For the color picker
            'jquery'
        ), $version, true);
    }
}
// Instantiate the PostologySettings class
$postology_settings = new PostologySettings();

