<?php

/**
 * Preset Manager
 *
 * Manages predefined settings configurations for common site types.
 *
 * @package ProRank\SEO\Core
 * @since   0.1.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Core;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}


/**
 * Preset Manager class
 */


class PresetManager {
    
    /**
     * Settings Manager instance
     *
     * @var SettingsManager
     */
    private SettingsManager $settings_manager;
    
    /**
     * Available presets
     *
     * @var array
     */
    private array $presets = [];
    
    /**
     * Constructor
     *
     * @param SettingsManager $settings_manager Settings manager instance
     */
    public function __construct(SettingsManager $settings_manager) {
        $this->settings_manager = $settings_manager;
        $this->load_presets();
    }
    
    /**
     * Load available presets
     *
     * @return void
     */
    private function load_presets(): void {
        $this->presets = $this->get_default_presets();

        $preset_dir = $this->get_presets_dir();

        if (!is_dir($preset_dir)) {
            wp_mkdir_p($preset_dir);
        }
        
        // Load preset files from uploads (custom presets).
        $preset_files = glob($preset_dir . '*.json');
        
        foreach ($preset_files as $file) {
            $preset_name = basename($file, '.json');
            $preset_data = $this->load_preset_file($file);
            
            if ($preset_data) {
                $this->presets[$preset_name] = $preset_data;
            }
        }
    }

    /**
     * Get presets directory in uploads.
     *
     * @return string
     */
    private function get_presets_dir(): string {
        $upload_dir = wp_upload_dir();
        return trailingslashit($upload_dir['basedir']) . 'prorank-seo/presets/';
    }
    
    /**
     * Load preset from file
     *
     * @param string $file_path Preset file path
     * @return array|null Preset data or null on error
     */
    private function load_preset_file(string $file_path): ?array {
        if (!is_readable($file_path)) {
            return null;
        }
        
        $json_content = $this->read_file($file_path);
        if ($json_content === '') {
            return null;
        }
        
        $data = json_decode($json_content, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return null;
        }
        
        // Validate preset structure
        if (!isset($data['name'], $data['description'], $data['settings'])) {
            return null;
        }
        
        return $data;
    }
    
    /**
     * Get default presets
     *
     * @return array
     */
    private function get_default_presets(): array {
        $blog_preset = [
            'name' => __('Blog', 'prorank-seo'),
            'description' => __('Optimized settings for blog and content websites', 'prorank-seo'),
            'icon' => 'edit',
            'settings' => [
                // Technical SEO
                'enable_xml_sitemap' => true,
                'posts_per_sitemap' => 1000,
                'include_post_types' => ['post', 'page'],
                'include_taxonomies' => ['category', 'post_tag'],
                'include_images' => true,
                'ping_search_engines' => true,
                
                // On-Page SEO
                'enable_meta_box' => true,
                'enable_schema_markup' => true,
                'default_schema_type' => 'Article',
                'enable_breadcrumbs' => true,
                'enable_readability' => true,
                'enable_internal_linking' => true,
                'internal_links_per_post' => 3,
                
                // Performance
                'enable_lazy_loading' => true,
                'lazy_load_images' => true,
                'lazy_load_iframes' => true,
                'enable_browser_caching' => true,
                'browser_cache_duration' => 7,
            ],
        ];
        
        $local_preset = [
            'name' => __('Local Business', 'prorank-seo'),
            'description' => __('Optimized settings for local businesses and service providers', 'prorank-seo'),
            'icon' => 'location',
            'settings' => [
                // Technical SEO
                'enable_xml_sitemap' => true,
                'posts_per_sitemap' => 500,
                'include_post_types' => ['page', 'service', 'location'],
                'include_images' => true,
                'ping_search_engines' => true,
                
                // Local SEO specific
                'enable_local_schema' => true,
                'default_schema_type' => 'LocalBusiness',
                'enable_google_my_business' => true,
                'enable_location_pages' => true,
                'enable_review_schema' => true,
                
                // On-Page SEO
                'enable_meta_box' => true,
                'enable_schema_markup' => true,
                'enable_breadcrumbs' => true,
                'breadcrumb_home_text' => 'Home',
                
                // Performance
                'enable_lazy_loading' => true,
                'enable_minification' => true,
            ],
        ];
        
        $woocommerce_preset = [
            'name' => __('E-commerce', 'prorank-seo'),
            'description' => __('Optimized settings for WooCommerce and online stores', 'prorank-seo'),
            'icon' => 'cart',
            'settings' => [
                // Technical SEO
                'enable_xml_sitemap' => true,
                'posts_per_sitemap' => 2000,
                'include_post_types' => ['product', 'page'],
                'include_taxonomies' => ['product_cat', 'product_tag'],
                'include_images' => true,
                'ping_search_engines' => true,
                
                // E-commerce specific
                'enable_product_schema' => true,
                'enable_price_monitoring' => true,
                'enable_cart_abandonment_schema' => true,
                'default_schema_type' => 'Product',
                'enable_review_schema' => true,
                'enable_availability_schema' => true,
                
                // On-Page SEO
                'enable_meta_box' => true,
                'enable_schema_markup' => true,
                'enable_breadcrumbs' => true,
                'woocommerce_breadcrumbs' => true,
                
                // Performance (critical for e-commerce)
                'enable_lazy_loading' => true,
                'lazy_load_product_images' => false, // Don't lazy load main product images
                'enable_cdn_optimization' => true,
                'enable_database_optimization' => true,
                'optimize_cart_fragments' => true,
            ],
        ];

        return [
            'blog' => $blog_preset,
            'local' => $local_preset,
            'woocommerce' => $woocommerce_preset,
        ];
    }

    /**
     * Read a local file safely using WP_Filesystem.
     *
     * @param string $file_path File path to read.
     * @return string
     */
    private function read_file(string $file_path): string {
        if (!is_readable($file_path)) {
            return '';
        }

        if (!function_exists('WP_Filesystem')) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }

        WP_Filesystem();
        global $wp_filesystem;
        if (!$wp_filesystem) {
            return '';
        }

        $contents = $wp_filesystem->get_contents($file_path);
        return $contents === false ? '' : (string) $contents;
    }
    
    /**
     * Get available presets
     *
     * @return array List of available presets
     */
    public function get_presets(): array {
        $preset_list = [];
        
        foreach ($this->presets as $key => $preset) {
            $preset_list[] = [
                'id' => $key,
                'name' => $preset['name'],
                'description' => $preset['description'],
                'icon' => $preset['icon'] ?? 'admin-generic',
                'settings_count' => count($preset['settings']),
            ];
        }
        
        return $preset_list;
    }
    
    /**
     * Get specific preset
     *
     * @param string $preset_name Preset name
     * @return array|null Preset data or null if not found
     */
    public function get_preset(string $preset_name): ?array {
        return $this->presets[$preset_name] ?? null;
    }
    
    /**
     * Apply preset settings
     *
     * @param string $preset_name Preset to apply
     * @return bool True on success, false on failure
     */
    public function apply_preset(string $preset_name): bool {
        $preset = $this->get_preset($preset_name);
        
        if (!$preset || !isset($preset['settings'])) {
            return false;
        }
        
        // Check capability
        if (!current_user_can('manage_options')) {
            return false;
        }
        
        // Group settings by module/group
        $grouped_settings = $this->group_settings($preset['settings']);
        
        // Apply settings group by group
        foreach ($grouped_settings as $group => $settings) {
            // Validate settings against registered settings
            $validated_settings = $this->validate_settings($group, $settings);
            
            if (!empty($validated_settings)) {
                $this->settings_manager->update_settings_group($group, $validated_settings);
            }
        }
        
        // Log preset application
        do_action('prorank_seo_preset_applied', $preset_name, $preset);
        
        return true;
    }
    
    /**
     * Group settings by module
     *
     * @param array $settings Flat settings array
     * @return array Grouped settings
     */
    private function group_settings(array $settings): array {
        $grouped = [];
        
        // Map setting keys to groups
        $setting_groups = [
            // Technical SEO
            'enable_xml_sitemap' => 'sitemaps',
            'posts_per_sitemap' => 'sitemaps',
            'include_post_types' => 'sitemaps',
            'include_taxonomies' => 'sitemaps',
            'include_images' => 'sitemaps',
            'ping_search_engines' => 'sitemaps',
            
            // On-Page SEO
            'enable_meta_box' => 'meta',
            'enable_schema_markup' => 'schema',
            'default_schema_type' => 'schema',
            'enable_breadcrumbs' => 'breadcrumbs',
            'enable_readability' => 'readability',
            'enable_internal_linking' => 'internal_linking',
            'internal_links_per_post' => 'internal_linking',
            
            // Local SEO
            'enable_local_schema' => 'local_schema',
            'enable_google_my_business' => 'google_my_business',
            'enable_location_pages' => 'location_pages',
            'enable_review_schema' => 'reviews',
            
            // E-commerce
            'enable_product_schema' => 'product_schema',
            'enable_price_monitoring' => 'price_monitoring',
            'enable_cart_abandonment_schema' => 'cart_optimization',
            'enable_availability_schema' => 'product_schema',
            'woocommerce_breadcrumbs' => 'breadcrumbs',
            'optimize_cart_fragments' => 'cart_optimization',
            
            // Performance
            'enable_lazy_loading' => 'lazy_loading',
            'lazy_load_images' => 'lazy_loading',
            'lazy_load_iframes' => 'lazy_loading',
            'lazy_load_product_images' => 'lazy_loading',
            'enable_browser_caching' => 'browser_caching',
            'browser_cache_duration' => 'browser_caching',
            'enable_minification' => 'minification',
            'enable_cdn_optimization' => 'cdn',
            'enable_database_optimization' => 'database',
        ];
        
        foreach ($settings as $key => $value) {
            $group = $setting_groups[$key] ?? 'general';
            
            if (!isset($grouped[$group])) {
                $grouped[$group] = [];
            }
            
            $grouped[$group][$key] = $value;
        }
        
        return $grouped;
    }
    
    /**
     * Validate settings against registered settings
     *
     * @param string $group    Settings group
     * @param array  $settings Settings to validate
     * @return array Validated settings
     */
    private function validate_settings(string $group, array $settings): array {
        $registered = $this->settings_manager->get_registered_settings($group);
        
        if (empty($registered)) {
            return [];
        }
        
        $validated = [];
        
        foreach ($settings as $key => $value) {
            // Check if setting is registered
            if (isset($registered[$key])) {
                // Apply any sanitization callback
                if (isset($registered[$key]['sanitize_callback']) && is_callable($registered[$key]['sanitize_callback'])) {
                    $value = call_user_func($registered[$key]['sanitize_callback'], $value);
                }
                
                $validated[$key] = $value;
            }
        }
        
        return $validated;
    }
}
