<?php

/**
 * Palette Manager Class file.
 *
 * @package Color_Theme_Manager_For_Divi
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
    // Exit if accessed directly.
}
/**
 * Manages creation, storage, deletion, and restoration of color palettes and theme groups.
 *
 * @since 1.0.0
 */
class CTMD_Palette_Manager {
    /**
     * The database option name for Divi settings.
     *
     * @var string
     */
    private $option_name = 'et_divi';

    /**
     * The slug of the plugin main page.
     *
     * @var string
     */
    private $page_slug = 'color-theme-manager-for-divi';

    /**
     * Instance of the Cache Manager class.
     *
     * @var CTMD_Cache_Manager
     */
    private $cache_manager;

    /**
     * Instance of the Color Manager class.
     *
     * @var CTMD_Color_Manager
     */
    private $color_manager;

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

    /**
     * Default special colors values.
     *
     * @var array
     */
    private $default_special_colors = array();

    /**
     * Constructor.
     *
     * @since 1.0.0
     *
     * @param CTMD_Cache_Manager $cache_manager The cache manager instance.
     */
    public function __construct( CTMD_Cache_Manager $cache_manager ) {
        $this->cache_manager = $cache_manager;
        $this->default_special_colors = array(
            'accent_color'           => '#2ea3f2',
            'secondary_accent_color' => '#2ea3f2',
            'header_color'           => '#666666',
            'font_color'             => '#666666',
        );
    }

    /**
     * Initializes translatable properties.
     *
     * @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' ),
        );
    }

    /**
     * Sets the Color Manager instance.
     *
     * Used to resolve circular dependency between managers.
     *
     * @since 1.0.0
     *
     * @param CTMD_Color_Manager $color_manager The color manager instance.
     * @return void
     */
    public function set_color_manager( CTMD_Color_Manager $color_manager ) {
        $this->color_manager = $color_manager;
    }

    /**
     * Retrieves all saved palettes.
     *
     * @since 1.0.0
     *
     * @return array An array of saved palettes.
     */
    public function get_palettes() {
        $settings = get_option( 'ctmd_settings', array() );
        return ( isset( $settings['palettes'] ) ? $settings['palettes'] : array() );
    }

    /**
     * Retrieves all saved theme groups (Premium only).
     *
     * @since 1.0.0
     *
     * @return array An array of saved theme groups.
     */
    public function get_themes() {
        return array();
    }

    /**
     * Deletes all palettes and theme groups.
     *
     * @since 1.0.0
     *
     * @return bool True on success.
     */
    public function delete_all_palettes() {
        $settings = get_option( 'ctmd_settings', array() );
        if ( isset( $settings['palettes'] ) ) {
            unset($settings['palettes']);
            update_option( 'ctmd_settings', $settings );
        }
        if ( isset( $settings['themes'] ) ) {
            unset($settings['themes']);
            update_option( 'ctmd_settings', $settings );
        }
        return true;
    }

    /**
     * Deletes a specific theme group.
     *
     * @since 1.0.0
     *
     * @param string $group_name The name of the theme group to delete.
     * @return bool True on success, false otherwise.
     */
    public function delete_theme_group( $group_name ) {
        return false;
    }

    /**
     * Saves a theme group containing multiple palettes.
     *
     * @since 1.0.0
     *
     * @param string $group_name     The name of the theme group.
     * @param array  $palettes_array The array of palettes (Light, Dark, Mixed).
     * @param array  $source_colors  The source colors used to generate the theme.
     * @return bool True on success, false on failure.
     */
    public function save_theme_group( $group_name, $palettes_array, $source_colors = array() ) {
        if ( empty( $group_name ) || empty( $palettes_array ) ) {
            return false;
        }
        return false;
    }

    /**
     * Saves a single palette snapshot.
     *
     * @since 1.0.0
     *
     * @param string $name      The name of the palette.
     * @param array  $color_set The color data (global and special colors).
     * @return bool True on success, false on failure.
     */
    public function save_palette( $name, $color_set ) {
        if ( empty( $name ) || empty( $color_set ) || !is_array( $color_set ) ) {
            return false;
        }
        $settings = get_option( 'ctmd_settings', array() );
        $palettes = $settings['palettes'] ?? array();
        $snapshot = array(
            'special_colors' => $color_set['special_colors'] ?? array(),
            'global_colors'  => $color_set['global_colors'] ?? array(),
        );
        $palettes[$name] = $snapshot;
        $settings['palettes'] = $palettes;
        return update_option( 'ctmd_settings', $settings );
    }

    /**
     * Handles the POST request to create a new palette snapshot.
     *
     * @since 1.0.0
     *
     * @return void
     */
    public function create_palette() {
        check_admin_referer( 'ctmd_create_palette_nonce' );
        if ( !current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Unauthorized.', 'color-theme-manager-for-divi' ) );
        }
        $palette_name = sanitize_text_field( filter_input( INPUT_POST, 'palette_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ?? '' );
        if ( !empty( $palette_name ) ) {
            $settings = get_option( 'ctmd_settings', array() );
            $palettes = $settings['palettes'] ?? array();
            if ( !isset( $palettes[$palette_name] ) ) {
                $et_divi_options = get_option( $this->option_name, array() );
                $snapshot = array(
                    'special_colors' => array(),
                    'global_colors'  => $this->color_manager->get_global_colors(),
                );
                foreach ( array_keys( $this->special_colors_map ) as $key ) {
                    $snapshot['special_colors'][$key] = $et_divi_options[$key] ?? $this->default_special_colors[$key];
                }
                $palettes[$palette_name] = $snapshot;
                $settings['palettes'] = $palettes;
                update_option( 'ctmd_settings', $settings );
            }
        }
        wp_safe_redirect( admin_url( 'admin.php?page=' . $this->page_slug . '&tab=palettes&message=palette_created' ) );
        exit;
    }

    /**
     * Handles the POST request to delete a palette.
     *
     * @since 1.0.0
     *
     * @return void
     */
    public function delete_palette() {
        check_admin_referer( 'ctmd_delete_palette_nonce' );
        if ( !current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Unauthorized.', 'color-theme-manager-for-divi' ) );
        }
        $palette_name = sanitize_text_field( filter_input( INPUT_POST, 'palette_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ?? '' );
        if ( !empty( $palette_name ) ) {
            $settings = get_option( 'ctmd_settings', array() );
            if ( isset( $settings['palettes'][$palette_name] ) ) {
                unset($settings['palettes'][$palette_name]);
                update_option( 'ctmd_settings', $settings );
            }
        }
        wp_safe_redirect( admin_url( 'admin.php?page=' . $this->page_slug . '&tab=palettes&message=palette_deleted' ) );
        exit;
    }

    /**
     * Internal helper to restore palette data to Divi options.
     *
     * Updates the global colors and special colors in the database
     * and clears the Divi cache.
     *
     * @since 1.0.0
     *
     * @param array $palette_data The palette data to restore.
     * @return bool True on success, false if data is empty.
     */
    private function _restore_palette_data( $palette_data ) {
        if ( empty( $palette_data ) ) {
            return false;
        }
        $option_data = get_option( $this->option_name, array() );
        $option_data = maybe_unserialize( $option_data );
        if ( isset( $palette_data['special_colors'] ) ) {
            foreach ( $palette_data['special_colors'] as $key => $color ) {
                $option_data[$key] = $color;
            }
        }
        $et_global_data = array();
        if ( isset( $option_data['et_global_data'] ) ) {
            $et_global_data = maybe_unserialize( $option_data['et_global_data'] );
        }
        $global_colors_to_save = $palette_data['global_colors'] ?? array();
        if ( !empty( $global_colors_to_save ) ) {
            foreach ( $global_colors_to_save as &$color_data ) {
                unset($color_data['source_name']);
            }
        }
        $et_global_data['global_colors'] = $global_colors_to_save;
        $option_data['et_global_data'] = maybe_serialize( $et_global_data );
        update_option( $this->option_name, $option_data );
        $this->cache_manager->clear_divi_cache();
        return true;
    }

    /**
     * Handles the POST request to restore a palette or theme sub-palette.
     *
     * @since 1.0.0
     *
     * @return void
     */
    public function restore_palette() {
        if ( !current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Unauthorized.', 'color-theme-manager-for-divi' ) );
        }
        check_admin_referer( 'ctmd_restore_nonce' );
        $group_name = sanitize_text_field( filter_input( INPUT_POST, 'theme_group_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ?? '' );
        $sub_palette_name = sanitize_text_field( filter_input( INPUT_POST, 'sub_palette_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ?? '' );
        $palette_name = sanitize_text_field( filter_input( INPUT_POST, 'palette_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ?? '' );
        $settings = get_option( 'ctmd_settings', array() );
        $palette_data = null;
        // Check if restoring from a theme group.
        if ( !empty( $group_name ) && !empty( $sub_palette_name ) ) {
            if ( isset( $settings['themes'][$group_name]['palettes'][$sub_palette_name] ) ) {
                $palette_data = $settings['themes'][$group_name]['palettes'][$sub_palette_name];
            }
            // Fallback to checking for a standalone palette.
        } elseif ( !empty( $palette_name ) ) {
            if ( isset( $settings['palettes'][$palette_name] ) ) {
                $palette_data = $settings['palettes'][$palette_name];
            }
        }
        if ( $palette_data ) {
            $this->_restore_palette_data( $palette_data );
        }
        wp_safe_redirect( admin_url( 'admin.php?page=' . $this->page_slug . '&tab=colors&message=palette_restored' ) );
        exit;
    }

    /**
     * Handles the POST request to activate a theme group (Premium).
     *
     * Sets the active theme and restores the Light palette as the default.
     *
     * @since 1.0.0
     *
     * @return void
     */
    public function activate_theme() {
        if ( !current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Unauthorized.', 'color-theme-manager-for-divi' ) );
        }
        wp_die( esc_html__( 'Unauthorized.', 'color-theme-manager-for-divi' ) );
    }

    /**
     * Handles the POST request to deactivate the current theme (Premium).
     *
     * @since 1.0.0
     *
     * @return void
     */
    public function deactivate_theme() {
        if ( !current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Unauthorized.', 'color-theme-manager-for-divi' ) );
        }
        wp_die( esc_html__( 'Unauthorized.', 'color-theme-manager-for-divi' ) );
    }

}
