<?php

/**
 * Admin Class file handling UI and requests.
 *
 * @package Color_Theme_Manager_For_Divi
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
    // Exit if accessed directly.
}
/**
 * Handles the admin menu, script enqueueing, and AJAX requests.
 *
 * @since 1.0.0
 */
class CTMD_Admin {
    /**
     * The slug of the plugin main page.
     *
     * @var string
     */
    private $page_slug = 'color-theme-manager-for-divi';

    /**
     * The Color Manager instance.
     *
     * @var CTMD_Color_Manager
     */
    public $color_manager;

    /**
     * The Palette Manager instance.
     *
     * @var CTMD_Palette_Manager
     */
    public $palette_manager;

    /**
     * Maps special Divi color IDs to readable labels.
     *
     * @var array
     */
    public $special_colors_map = array();

    /**
     * Maps default Divi color IDs to readable labels.
     *
     * @var array
     */
    public $default_special_colors = array();

    /**
     * Maps special Divi color display IDs to readable labels.
     *
     * @var array
     */
    public $special_color_display_ids = array();

    /**
     * Constructor.
     *
     * @since 1.0.0
     *
     * @param CTMD_Color_Manager   $color_manager   The color manager instance.
     * @param CTMD_Palette_Manager $palette_manager The palette manager instance.
     */
    public function __construct( CTMD_Color_Manager $color_manager, CTMD_Palette_Manager $palette_manager ) {
        $this->color_manager = $color_manager;
        $this->palette_manager = $palette_manager;
        $this->default_special_colors = array(
            'accent_color'           => '#2ea3f2',
            'secondary_accent_color' => '#2ea3f2',
            'header_color'           => '#666666',
            'font_color'             => '#666666',
        );
        $this->special_color_display_ids = array(
            'accent_color'           => 'gcid-primary-color',
            'secondary_accent_color' => 'gcid-secondary-color',
            'header_color'           => 'gcid-heading-color',
            'font_color'             => 'gcid-body-color',
        );
        add_action( 'wp_ajax_ctmd_fix_contrast', array($this, 'ajax_fix_contrast') );
        add_action( 'wp_ajax_ctmd_run_manual_contrast_check', array($this, 'ajax_run_manual_contrast_check') );
    }

    /**
     * Initializes translatable properties.
     *
     * Sets up the special colors map with localized strings.
     *
     * @since 1.0.0
     *
     * @return void
     */
    public function setup_properties() {
        $this->special_colors_map = array(
            'accent_color'           => __( 'Primary Color', 'color-theme-manager-for-divi' ),
            'secondary_accent_color' => __( 'Secondary Color', 'color-theme-manager-for-divi' ),
            'header_color'           => __( 'Heading Color', 'color-theme-manager-for-divi' ),
            'font_color'             => __( 'Text Color', 'color-theme-manager-for-divi' ),
        );
    }

    /**
     * Registers the admin menu pages.
     *
     * @since 1.0.0
     *
     * @return void
     */
    public function add_admin_menu() {
        add_menu_page(
            esc_html__( 'Color Theme Manager for Divi', 'color-theme-manager-for-divi' ),
            esc_html__( 'Color Themes for Divi', 'color-theme-manager-for-divi' ),
            'manage_options',
            $this->page_slug,
            array($this, 'render_admin_page'),
            'dashicons-art',
            99
        );
        add_submenu_page(
            $this->page_slug,
            esc_html__( 'Color Manager', 'color-theme-manager-for-divi' ),
            esc_html__( 'Color Manager', 'color-theme-manager-for-divi' ),
            'manage_options',
            'admin.php?page=' . $this->page_slug . '&tab=colors'
        );
        add_submenu_page(
            $this->page_slug,
            esc_html__( 'Palette Manager', 'color-theme-manager-for-divi' ),
            esc_html__( 'Palette Manager', 'color-theme-manager-for-divi' ),
            'manage_options',
            'admin.php?page=' . $this->page_slug . '&tab=palettes'
        );
        add_submenu_page(
            $this->page_slug,
            esc_html__( 'Theme Generator', 'color-theme-manager-for-divi' ),
            esc_html__( 'Theme Generator', 'color-theme-manager-for-divi' ),
            'manage_options',
            'admin.php?page=' . $this->page_slug . '&tab=themegenerator'
        );
        add_submenu_page(
            $this->page_slug,
            esc_html__( 'Settings', 'color-theme-manager-for-divi' ),
            esc_html__( 'Settings', 'color-theme-manager-for-divi' ),
            'manage_options',
            'admin.php?page=' . $this->page_slug . '&tab=settings'
        );
        add_submenu_page(
            $this->page_slug,
            esc_html__( 'How To', 'color-theme-manager-for-divi' ),
            esc_html__( 'How To', 'color-theme-manager-for-divi' ),
            'manage_options',
            'admin.php?page=' . $this->page_slug . '&tab=howto'
        );
        add_submenu_page(
            $this->page_slug,
            esc_html__( 'About', 'color-theme-manager-for-divi' ),
            esc_html__( 'About', 'color-theme-manager-for-divi' ),
            'manage_options',
            'admin.php?page=' . $this->page_slug . '&tab=about'
        );
        remove_submenu_page( $this->page_slug, $this->page_slug );
    }

    /**
     * Ensures the correct submenu is highlighted when tabs are used.
     *
     * @since 1.0.0
     *
     * @param string $submenu_file The submenu file currently highlighted.
     * @return string The modified submenu file.
     */
    public function highlight_correct_submenu( $submenu_file ) {
        global $plugin_page;
        $tab = sanitize_key( filter_input( INPUT_GET, 'tab', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ?? '' );
        if ( $plugin_page === $this->page_slug && !empty( $tab ) ) {
            $submenu_file = 'admin.php?page=' . $this->page_slug . '&tab=' . $tab;
        }
        return $submenu_file;
    }

    /**
     * Enqueues admin styles and scripts.
     *
     * Loads specific assets based on the current active tab.
     *
     * @since 1.0.0
     *
     * @param string $hook The current admin page hook.
     * @return void
     */
    public function enqueue_admin_scripts( $hook ) {
        if ( 'toplevel_page_color-theme-manager-for-divi' !== $hook ) {
            return;
        }
        $current_tab = sanitize_key( filter_input( INPUT_GET, 'tab', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ?? 'colors' );
        if ( empty( $current_tab ) ) {
            $current_tab = 'colors';
        }
        // Enqueue view-specific stylesheets.
        $view_css_path = CTMD_PLUGIN_DIR . 'admin/css/view-' . $current_tab . '.css';
        if ( file_exists( $view_css_path ) ) {
            wp_enqueue_style(
                'ctmd-view-' . $current_tab,
                CTMD_PLUGIN_URL . 'admin/css/view-' . $current_tab . '.css',
                array(),
                CTMD_VERSION
            );
        }
        // Enqueue SimpleLightbox assets only on the 'howto' tab.
        if ( 'howto' === $current_tab ) {
            wp_enqueue_style(
                'simple-lightbox-css',
                CTMD_PLUGIN_URL . 'admin/css/vendor/simple-lightbox.css',
                array(),
                '2.14.3'
            );
            wp_enqueue_script(
                'simple-lightbox-js',
                CTMD_PLUGIN_URL . 'admin/js/vendor/simple-lightbox.js',
                array(),
                '2.14.3',
                true
            );
        }
        wp_enqueue_script(
            'sortable-js',
            CTMD_PLUGIN_URL . 'admin/js/vendor/Sortable.js',
            array(),
            CTMD_VERSION,
            true
        );
        wp_enqueue_style(
            'ctmd-admin-style',
            CTMD_PLUGIN_URL . 'admin/css/ctmd-admin.css',
            array(),
            CTMD_VERSION
        );
        wp_enqueue_style(
            'ctmd-freemius-style',
            CTMD_PLUGIN_URL . 'admin/css/ctmd-freemius.css',
            array(),
            CTMD_VERSION
        );
        wp_enqueue_style(
            'vanilla-picker-css',
            CTMD_PLUGIN_URL . 'admin/css/vendor/vanilla-picker/vanilla-picker.css',
            array(),
            '2.12.3'
        );
        wp_enqueue_script(
            'vanilla-picker-js',
            CTMD_PLUGIN_URL . 'admin/js/vendor/vanilla-picker/vanilla-picker.js',
            array(),
            '2.12.3',
            true
        );
        wp_enqueue_script(
            'ctmd-admin-script',
            CTMD_PLUGIN_URL . 'admin/js/ctmd-admin.js',
            array('sortable-js', 'jquery', 'vanilla-picker-js'),
            CTMD_VERSION,
            true
        );
    }

    /**
     * Renders the main admin page wrapper.
     *
     * Includes the view file corresponding to the active tab.
     *
     * @since 1.0.0
     *
     * @return void
     */
    public function render_admin_page() {
        if ( !current_user_can( 'manage_options' ) ) {
            return;
        }
        $active_tab = sanitize_key( filter_input( INPUT_GET, 'tab', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ?? 'colors' );
        if ( empty( $active_tab ) ) {
            $active_tab = 'colors';
        }
        ?>
		<div class="wrap">
			<h1>
				<?php 
        esc_html_e( 'Color Theme Manager for Divi', 'color-theme-manager-for-divi' );
        ?>
				<?php 
        ?>
				<span class="title-count theme-version"><?php 
        echo esc_html( CTMD_VERSION );
        ?></span>
			</h1>

			<?php 
        $this->display_notices();
        ?>

			<div id="ctmd-unsaved-warning" class="notice notice-info inline"><p><?php 
        esc_html_e( 'You have unsaved changes.', 'color-theme-manager-for-divi' );
        ?></p></div>

			<h2 class="nav-tab-wrapper">
				<a href="?page=<?php 
        echo esc_attr( $this->page_slug );
        ?>&tab=colors" class="nav-tab <?php 
        echo ( 'colors' === $active_tab ? 'nav-tab-active' : '' );
        ?>"><?php 
        esc_html_e( 'Color Manager', 'color-theme-manager-for-divi' );
        ?></a>
				<a href="?page=<?php 
        echo esc_attr( $this->page_slug );
        ?>&tab=palettes" class="nav-tab <?php 
        echo ( 'palettes' === $active_tab ? 'nav-tab-active' : '' );
        ?>"><?php 
        esc_html_e( 'Palette Manager', 'color-theme-manager-for-divi' );
        ?></a>
				<?php 
        ?>
					<a href="#" class="nav-tab nav-tab-disabled"><?php 
        esc_html_e( 'Theme Generator', 'color-theme-manager-for-divi' );
        ?> <span class="ctmd-premium-badge">Premium</span></a>
				<?php 
        ?>
				<a href="?page=<?php 
        echo esc_attr( $this->page_slug );
        ?>&tab=settings" class="nav-tab <?php 
        echo ( 'settings' === $active_tab ? 'nav-tab-active' : '' );
        ?>"><?php 
        esc_html_e( 'Settings', 'color-theme-manager-for-divi' );
        ?></a>
				<a href="?page=<?php 
        echo esc_attr( $this->page_slug );
        ?>&tab=howto" class="nav-tab <?php 
        echo ( 'howto' === $active_tab ? 'nav-tab-active' : '' );
        ?>"><?php 
        esc_html_e( 'How To', 'color-theme-manager-for-divi' );
        ?></a>
				<a href="?page=<?php 
        echo esc_attr( $this->page_slug );
        ?>&tab=about" class="nav-tab <?php 
        echo ( 'about' === $active_tab ? 'nav-tab-active' : '' );
        ?>"><?php 
        esc_html_e( 'About', 'color-theme-manager-for-divi' );
        ?></a>
			</h2>

			<?php 
        $premium_tabs = array('themegenerator', 'preview');
        if ( in_array( $active_tab, $premium_tabs ) && !ctmd_fs()->can_use_premium_code__premium_only() ) {
            ?>
				<div class="ctmd-premium-feature-notice">
					<h2><?php 
            esc_html_e( 'This is a Premium Feature', 'color-theme-manager-for-divi' );
            ?></h2>
					<p><?php 
            esc_html_e( 'Upgrade to the premium version to unlock this feature and many more!', 'color-theme-manager-for-divi' );
            ?></p>
					<a href="<?php 
            echo esc_url( ctmd_fs()->get_upgrade_url() );
            ?>" class="button button-primary"><?php 
            esc_html_e( 'Upgrade Now', 'color-theme-manager-for-divi' );
            ?></a>
				</div>
				<?php 
        } else {
            $view_path = CTMD_PLUGIN_DIR . 'admin/views/view-' . $active_tab . '.php';
            if ( file_exists( $view_path ) ) {
                include $view_path;
            }
        }
        ?>
		</div>
		<?php 
    }

    /**
     * Displays admin notices (success/errors) based on URL parameters.
     *
     * (Refactored for WPCS compliance to support Freemius build process)
     *
     * @since 1.0.0
     *
     * @return void
     */
    private function display_notices() {
        // --- 1. Εμφάνιση Transient Errors (Παραμένει ως έχει) ---
        $transient_errors = get_transient( 'ctmd_admin_errors' );
        if ( $transient_errors ) {
            foreach ( $transient_errors as $error_message ) {
                echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( $error_message ) . '</p></div>';
            }
            delete_transient( 'ctmd_admin_errors' );
        }
        // --- 2. Λήψη κλειδιών μηνυμάτων από το URL (Παραμένει ως έχει) ---
        $message_key = sanitize_key( filter_input( INPUT_GET, 'message', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ?? '' );
        $error_key = sanitize_key( filter_input( INPUT_GET, 'error', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ?? '' );
        $failed_id = sanitize_text_field( filter_input( INPUT_GET, 'failed_id', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ?? '' );
        // --- 3. Ορισμός Μεταφράσιμων Strings (Η ΑΛΛΑΓΗ ΕΙΝΑΙ ΕΔΩ) ---
        // Αυτός ο τρόπος (ορισμός σε μεταβλητές) είναι WPCS-compliant.
        // --- Messages ---
        $msg_import_success = __( 'Settings imported successfully.', 'color-theme-manager-for-divi' );
        $msg_reset_success = __( 'Colors have been successfully reset.', 'color-theme-manager-for-divi' );
        $msg_settings_saved = __( 'Settings saved.', 'color-theme-manager-for-divi' );
        $msg_palette_restored = __( 'Colors successfully restored from palette.', 'color-theme-manager-for-divi' );
        $msg_palette_created = __( 'Palette created successfully.', 'color-theme-manager-for-divi' );
        $msg_palette_deleted = __( 'Palette deleted successfully.', 'color-theme-manager-for-divi' );
        $msg_theme_group_deleted = __( 'Theme group deleted successfully.', 'color-theme-manager-for-divi' );
        $msg_color_added = __( 'Color added successfully.', 'color-theme-manager-for-divi' );
        $msg_saved = __( 'Changes saved.', 'color-theme-manager-for-divi' );
        $msg_generation_success = __( 'Theme palettes generated successfully! You can view them in the Palette Manager tab.', 'color-theme-manager-for-divi' );
        $msg_json_staged = __( 'JSON file uploaded successfully. Review the colors below and click \'Generate Theme Palettes\' to proceed.', 'color-theme-manager-for-divi' );
        $msg_staged_cleared = __( 'Preview cleared. You can now upload a new file.', 'color-theme-manager-for-divi' );
        $msg_layout_uploaded = __( 'Master layout JSON uploaded successfully.', 'color-theme-manager-for-divi' );
        $msg_layout_reset_success = __( 'Custom layout has been reset. The bundled layout will be used.', 'color-theme-manager-for-divi' );
        $msg_contrast_rechecked = __( 'Contrast check complete. The results have been updated.', 'color-theme-manager-for-divi' );
        // --- Errors ---
        /* translators: %s: The ID of the duplicate color. */
        $err_duplicate_id = __( '<strong>Error:</strong> The color ID "%s" already exists. The new color was not added.', 'color-theme-manager-for-divi' );
        $err_missing_fields = __( '<strong>Error:</strong> Both a Color ID and a color value are required to add a new color.', 'color-theme-manager-for-divi' );
        $err_import_upload = __( '<strong>Error:</strong> There was a problem uploading the settings file.', 'color-theme-manager-for-divi' );
        $err_import_invalid = __( '<strong>Error:</strong> The imported file is invalid.', 'color-theme-manager-for-divi' );
        $err_upload_error = __( '<strong>Error:</strong> Error uploading file. Please try again.', 'color-theme-manager-for-divi' );
        $err_generation_error = __( '<strong>Error:</strong> Error generating palettes. The JSON file might be invalid or missing required colors.', 'color-theme-manager-for-divi' );
        $err_json_error = __( '<strong>Error:</strong> The uploaded file was not valid JSON.', 'color-theme-manager-for-divi' );
        $err_missing_name = __( '<strong>Error:</strong> Please provide a name for the theme.', 'color-theme-manager-for-divi' );
        $err_invalid_file_type = __( '<strong>Error:</strong> Invalid file type. Please upload a .json file.', 'color-theme-manager-for-divi' );
        // --- 4. Δημιουργία Πινάκων (Arrays) από τις Μεταβλητές ---
        $messages = array(
            'import_success'       => $msg_import_success,
            'reset_success'        => $msg_reset_success,
            'settings_saved'       => $msg_settings_saved,
            'palette_restored'     => $msg_palette_restored,
            'palette_created'      => $msg_palette_created,
            'palette_deleted'      => $msg_palette_deleted,
            'theme_group_deleted'  => $msg_theme_group_deleted,
            'color_added'          => $msg_color_added,
            'saved'                => $msg_saved,
            'generation_success'   => $msg_generation_success,
            'json_staged'          => $msg_json_staged,
            'staged_cleared'       => $msg_staged_cleared,
            'layout_uploaded'      => $msg_layout_uploaded,
            'layout_reset_success' => $msg_layout_reset_success,
            'contrast_rechecked'   => $msg_contrast_rechecked,
        );
        $errors = array(
            'duplicate_id'         => $err_duplicate_id,
            'missing_fields'       => $err_missing_fields,
            'import_error_upload'  => $err_import_upload,
            'import_error_invalid' => $err_import_invalid,
            'upload_error'         => $err_upload_error,
            'generation_error'     => $err_generation_error,
            'json_error'           => $err_json_error,
            'missing_name'         => $err_missing_name,
            'invalid_file_type'    => $err_invalid_file_type,
        );
        // --- 5. Εμφάνιση Μηνυμάτων (Παραμένει ως έχει) ---
        if ( !empty( $message_key ) && isset( $messages[$message_key] ) ) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $messages[$message_key] ) . '</p></div>';
        }
        if ( !empty( $error_key ) && isset( $errors[$error_key] ) ) {
            $message = $errors[$error_key];
            if ( 'duplicate_id' === $error_key && !empty( $failed_id ) ) {
                // Η wp_kses_post χρησιμοποιείται εδώ αντί για sprintf/esc_html
                // επειδή το string περιέχει <strong> tags.
                $message = sprintf( $message, esc_html( $failed_id ) );
            }
            echo '<div class="notice notice-error is-dismissible"><p>' . wp_kses_post( $message ) . '</p></div>';
        }
    }

    /**
     * Handles the POST request to delete a theme group.
     *
     * @since 1.0.0
     *
     * @return void
     */
    public function handle_delete_theme_group_request() {
        check_admin_referer( 'ctmd_delete_theme_group_nonce' );
        if ( !current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Unauthorized.', 'color-theme-manager-for-divi' ) );
        }
        wp_safe_redirect( admin_url( 'admin.php?page=' . $this->page_slug . '&tab=palettes&message=theme_group_deleted' ) );
        exit;
    }

    /**
     * Handles the request to reset the custom layout flag.
     *
     * @since 1.0.0
     *
     * @return void
     */
    public function reset_custom_layout_flag() {
        check_admin_referer( 'ctmd_reset_custom_layout_flag_nonce' );
        if ( !current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Unauthorized.', 'color-theme-manager-for-divi' ) );
        }
        wp_safe_redirect( admin_url( 'admin.php?page=' . $this->page_slug . '&tab=settings&message=layout_reset_success' ) );
        exit;
    }

    /**
     * AJAX handler to fix color contrast issues.
     *
     * Switches the color to its "opposite" variant (e.g., Light to Dark)
     * to improve contrast.
     *
     * @since 1.0.0
     *
     * @return void
     */
    public function ajax_fix_contrast() {
        check_ajax_referer( 'ctmd_fix_contrast_nonce', 'nonce' );
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array(
                'message' => __( 'Unauthorized.', 'color-theme-manager-for-divi' ),
            ) );
        }
    }

    /**
     * AJAX handler to run a manual contrast check.
     *
     * @since 1.0.0
     *
     * @return void
     */
    public function ajax_run_manual_contrast_check() {
        check_ajax_referer( 'ctmd_manual_contrast_check_nonce', 'nonce' );
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array(
                'message' => __( 'Unauthorized.', 'color-theme-manager-for-divi' ),
            ) );
        }
    }

}
