<?php
/**
 * Cache Controller
 * 
 * phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
 * Reason: Custom cache table (wp_varihu_variation_cache) - WordPress wp_cache_* not applicable
 */

namespace VariationHub\API;

use VariationHub\Core\Cache_Table;
use VariationHub\Core\Cache_Sync;
use WP_REST_Controller;
use WP_REST_Server;
use WP_Error;

defined('ABSPATH') || exit;

class Cache_Controller extends WP_REST_Controller {
    
    protected $namespace = 'variation-hub/v1';
    protected $rest_base = 'cache';
    
    public function register_routes() {
        register_rest_route($this->namespace, '/' . $this->rest_base . '/stats', [
            [
                'methods' => WP_REST_Server::READABLE,
                'callback' => [$this, 'get_stats'],
                'permission_callback' => [$this, 'check_permission'],
            ],
        ]);
        
        register_rest_route($this->namespace, '/' . $this->rest_base . '/check-and-start', [
            [
                'methods' => WP_REST_Server::CREATABLE,
                'callback' => [$this, 'check_and_start_sync'],
                'permission_callback' => [$this, 'check_permission'],
            ],
        ]);
        
        register_rest_route($this->namespace, '/' . $this->rest_base . '/resync', [
            [
                'methods' => WP_REST_Server::CREATABLE,
                'callback' => [$this, 'resync'],
                'permission_callback' => [$this, 'check_permission'],
            ],
        ]);
        
        register_rest_route($this->namespace, '/' . $this->rest_base . '/test', [
            [
                'methods' => WP_REST_Server::READABLE,
                'callback' => [$this, 'performance_test'],
                'permission_callback' => [$this, 'check_permission'],
            ],
        ]);
    }
    
    public function check_permission() {
        return current_user_can('manage_woocommerce');
    }
    
    /**
     * Get cache statistics
     */
    public function get_stats($request) {
        $stats = Cache_Table::get_stats();
        $health = Cache_Table::get_health();
        
        // Get WordPress info
        global $wpdb;
        
        return [
            'success' => true,
            'data' => [
                'cache' => [
                    'table_exists' => !empty($stats['exists']),
                    'row_count' => (int) ($stats['total_rows'] ?? 0),
                    'table_size_mb' => $this->get_table_size_mb(),
                    'index_count' => $this->count_indexes(),
                    'last_sync' => $this->get_last_sync_time(),
                ],
                'health' => [
                    'status' => strtoupper($health['status'] ?? 'UNKNOWN'),
                    'cache_count' => (int) ($health['cached'] ?? 0),
                    'actual_count' => (int) ($health['actual'] ?? 0),
                    'missing_count' => (int) (($health['actual'] ?? 0) - ($health['cached'] ?? 0)),
                    'orphaned_count' => 0, // TODO: implement orphaned detection
                ],
                'sync' => [
                    'is_running' => $this->is_sync_running(),
                    'processed' => get_option('varihu_sync_processed', 0),
                    'total' => get_option('varihu_sync_total', 0),
                    'last_error' => get_option('varihu_sync_last_error', null),
                ],
                'performance' => [
                    'avg_query_time_ms' => $this->get_avg_query_time(),
                    'cache_hit_rate' => 98.5, // Mock for now
                    'variations_per_second' => $this->calculate_throughput((int) ($stats['total_rows'] ?? 0)),
                ],
                'system' => [
                    'wordpress_version' => get_bloginfo('version'),
                    'woocommerce_version' => defined('WC_VERSION') ? WC_VERSION : 'N/A',
                    'php_version' => PHP_VERSION,
                    'php_memory_limit' => ini_get('memory_limit'),
                    'mysql_version' => $wpdb->db_version(),
                    'table_engine' => $this->get_table_engine(),
                ],
            ],
        ];
    }
    
    /**
     * Check cache and auto-start sync if needed
     */
    public function check_and_start_sync($request) {
        $health = Cache_Table::get_health();
        $cache_count = (int) ($health['cached'] ?? 0);
        $actual_count = (int) ($health['actual'] ?? 0);
        $missing_count = $actual_count - $cache_count;
        
        // Ha hiányzik akár 1 tétel is, auto-start
        $should_start = false;
        $reason = '';
        
        if ($cache_count === 0 && $actual_count > 0) {
            $should_start = true;
            $reason = 'Üres cache tábla';
        } elseif ($missing_count >= 1) {
            $should_start = true;
            $reason = 'Hiányzó cache bejegyzések (' . $missing_count . ' / ' . $actual_count . ')';
        }
        
        if ($should_start && !$this->is_sync_running()) {
            // Indítsuk el a sync-et
            Cache_Sync::schedule_full_sync();
            
            return [
                'success' => true,
                'started' => true,
                'message' => 'Cache szinkronizálás automatikusan elindítva',
                'data' => [
                    'reason' => $reason,
                    'cache_count' => $cache_count,
                    'actual_count' => $actual_count,
                    'missing_count' => $missing_count,
                    'batch_size' => 2000,
                    'estimated_time_seconds' => ceil($actual_count / 2000) * 2,
                ],
            ];
        }
        
        return [
            'success' => true,
            'started' => false,
            'message' => 'Cache rendben, nem szükséges szinkronizálás',
            'data' => [
                'cache_count' => $cache_count,
                'actual_count' => $actual_count,
                'missing_count' => $missing_count,
                'is_running' => $this->is_sync_running(),
            ],
        ];
    }
    
    /**
     * Trigger cache resync
     */
    public function resync($request) {
        try {
            // Truncate cache table
            Cache_Table::truncate();
            
            // Schedule full sync
            Cache_Sync::schedule_full_sync();
            
            return [
                'success' => true,
                'message' => 'Cache újraszinkronizálás elindítva a háttérben',
                'data' => [
                    'total_variations' => wp_count_posts('product_variation')->publish,
                    'batch_size' => 2000,
                    'estimated_time_seconds' => ceil(wp_count_posts('product_variation')->publish / 2000) * 2,
                ],
            ];
        } catch (\Exception $e) {
            return new WP_Error(
                'resync_failed',
                $e->getMessage(),
                ['status' => 500]
            );
        }
    }
    
    /**
     * Performance test
     */
    public function performance_test($request) {
        $start = microtime(true);
        
        global $wpdb;
        $table = esc_sql($wpdb->prefix . 'varihu_variation_cache');
        
        // Test query
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        // $table is safe (generated by $wpdb->prefix + hardcoded table name)
        $results = $wpdb->get_results(
            "SELECT COUNT(*) as total FROM {$table} WHERE stock_status = 'instock'",
            ARRAY_A
        );
        // phpcs:enable
        
        $query_time = (microtime(true) - $start) * 1000;
        
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $table is safe
        $total_variations = $wpdb->get_var("SELECT COUNT(*) FROM {$table}");
        
        return [
            'success' => true,
            'data' => [
                'query_time_ms' => round($query_time, 2),
                'total_variations' => $total_variations,
                'test_query' => 'SELECT COUNT(*) WHERE stock_status = instock',
                'result_count' => $results[0]['total'] ?? 0,
                'variations_per_second' => $this->calculate_throughput(
                    $total_variations,
                    $query_time
                ),
            ],
        ];
    }
    
    // Helper methods
    
    private function get_table_size_mb() {
        global $wpdb;
        $table = esc_sql($wpdb->prefix . 'varihu_variation_cache');
        
        $result = $wpdb->get_row($wpdb->prepare(
            "SELECT 
                ROUND((data_length + index_length) / 1024 / 1024, 2) as size_mb
            FROM information_schema.TABLES 
            WHERE table_schema = %s 
            AND table_name = %s",
            DB_NAME,
            $table
        ));
        
        return $result ? (float) $result->size_mb : 0.0;
    }
    
    private function count_indexes() {
        global $wpdb;
        $table = esc_sql($wpdb->prefix . 'varihu_variation_cache');
        
        $indexes = $wpdb->get_results($wpdb->prepare(
            "SELECT DISTINCT index_name 
            FROM information_schema.STATISTICS 
            WHERE table_schema = %s 
            AND table_name = %s
            AND index_name != 'PRIMARY'",
            DB_NAME,
            $table
        ));
        
        return count($indexes);
    }
    
    private function get_last_sync_time() {
        $last_sync = get_option('varihu_cache_last_sync', null);
        if (!$last_sync) {
            return null;
        }
        
        // Parse MySQL datetime
        $timestamp = strtotime($last_sync);
        if (!$timestamp) {
            return null;
        }
        
        $diff = time() - $timestamp;
        
        if ($diff < 60) {
            return sprintf('%d másodperce', $diff);
        } elseif ($diff < 3600) {
            return sprintf('%d perce', floor($diff / 60));
        } elseif ($diff < 86400) {
            return sprintf('%d órája', floor($diff / 3600));
        } else {
            return sprintf('%d napja', floor($diff / 86400));
        }
    }
    
    private function is_sync_running() {
        return (bool) get_option('varihu_sync_running', false);
    }
    
    private function get_avg_query_time() {
        global $wpdb;
        $table = esc_sql($wpdb->prefix . 'varihu_variation_cache');
        
        // Quick test query
        $start = microtime(true);
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $table is safe
        $wpdb->get_var("SELECT COUNT(*) FROM {$table}");
        $time = (microtime(true) - $start) * 1000;
        
        return round($time, 2);
    }
    
    private function calculate_throughput($row_count, $query_time_ms = null) {
        if ($query_time_ms === null) {
            $query_time_ms = $this->get_avg_query_time();
        }
        
        if ($query_time_ms <= 0) {
            return 0;
        }
        
        return round(($row_count / $query_time_ms) * 1000);
    }
    
    private function get_table_engine() {
        global $wpdb;
        $table = esc_sql($wpdb->prefix . 'varihu_variation_cache');
        
        $result = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s",
                DB_NAME,
                $table
            )
        );
        
        return $result ? $result->ENGINE : 'Unknown';
    }
}
