<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Performance Monitoring Controller
 * 
 * Provides performance monitoring and optimization tools
 */
class Performance extends MY_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load_global();
        
        // Admin only access
        if (!special_access()) {
            show_error("Access Denied - Admin Required", 403);
        }
    }
    
    /**
     * Performance dashboard
     */
    public function index() {
        $data = $this->data;
        $data['page_title'] = 'Performance Dashboard';
        
        // Get performance stats
        $data['memory_usage'] = get_memory_usage();
        $data['cache_stats'] = $this->get_cache_stats();
        $data['database_stats'] = $this->get_database_stats();
        $data['asset_stats'] = $this->get_asset_stats();
        
        $this->load->view('performance/dashboard', $data);
    }
    
    /**
     * Clear all caches
     */
    public function clear_cache() {
        try {
            // Clear database cache
            $this->db->cache_delete_all();
            
            // Clear file cache
            $this->load->driver('cache', array('adapter' => 'file'));
            $this->cache->clean();
            
            // Clear asset cache
            $this->load->library('asset_optimizer');
            $this->asset_optimizer->clear_cache();
            
            echo json_encode(array(
                'status' => 'success',
                'message' => 'All caches cleared successfully!'
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'status' => 'error',
                'message' => 'Error clearing cache: ' . $e->getMessage()
            ));
        }
    }
    
    /**
     * Optimize database
     */
    public function optimize_database() {
        try {
            $tables = $this->db->list_tables();
            $optimized = 0;
            
            foreach ($tables as $table) {
                $this->db->query("OPTIMIZE TABLE `$table`");
                $optimized++;
            }
            
            echo json_encode(array(
                'status' => 'success',
                'message' => "Optimized $optimized tables successfully!",
                'optimized_count' => $optimized
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'status' => 'error',
                'message' => 'Error optimizing database: ' . $e->getMessage()
            ));
        }
    }
    
    /**
     * Get cache statistics
     */
    private function get_cache_stats() {
        $stats = array();
        
        // Database cache stats
        $db_cache_dir = APPPATH . 'cache/db/';
        if (is_dir($db_cache_dir)) {
            $db_files = glob($db_cache_dir . '*');
            $stats['database'] = array(
                'file_count' => count($db_files),
                'total_size' => array_sum(array_map('filesize', $db_files))
            );
        }
        
        // File cache stats
        $file_cache_dir = APPPATH . 'cache/';
        if (is_dir($file_cache_dir)) {
            $file_files = glob($file_cache_dir . '*');
            $stats['file'] = array(
                'file_count' => count($file_files),
                'total_size' => array_sum(array_map('filesize', $file_files))
            );
        }
        
        return $stats;
    }
    
    /**
     * Get database statistics
     */
    private function get_database_stats() {
        $stats = array();
        
        try {
            // Get table sizes
            $query = $this->db->query("
                SELECT 
                    table_name,
                    ROUND(((data_length + index_length) / 1024 / 1024), 2) AS size_mb
                FROM information_schema.tables 
                WHERE table_schema = DATABASE()
                ORDER BY (data_length + index_length) DESC
                LIMIT 10
            ");
            
            $stats['table_sizes'] = $query->result();
            
            // Get total database size
            $query = $this->db->query("
                SELECT 
                    ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS total_size_mb
                FROM information_schema.tables 
                WHERE table_schema = DATABASE()
            ");
            
            $stats['total_size'] = $query->row()->total_size_mb;
            
        } catch (Exception $e) {
            $stats['error'] = $e->getMessage();
        }
        
        return $stats;
    }
    
    /**
     * Get asset statistics
     */
    private function get_asset_stats() {
        $this->load->library('asset_optimizer');
        return $this->asset_optimizer->get_cache_stats();
    }
    
    /**
     * Get query performance stats
     */
    public function query_stats() {
        try {
            $query = $this->db->query("
                SELECT 
                    COUNT(*) as total_queries,
                    AVG(query_time) as avg_query_time,
                    MAX(query_time) as max_query_time
                FROM information_schema.processlist 
                WHERE command != 'Sleep'
            ");
            
            echo json_encode($query->row());
        } catch (Exception $e) {
            echo json_encode(array('error' => $e->getMessage()));
        }
    }
    
    /**
     * Test page load performance
     */
    public function test_performance() {
        $start_time = microtime(TRUE);
        $start_memory = memory_get_usage();
        
        // Simulate some operations
        $this->db->query("SELECT 1");
        $this->load->view('performance/test');
        
        $end_time = microtime(TRUE);
        $end_memory = memory_get_usage();
        
        $performance = array(
            'load_time' => round(($end_time - $start_time) * 1000, 2) . 'ms',
            'memory_used' => format_bytes($end_memory - $start_memory),
            'peak_memory' => format_bytes(memory_get_peak_usage())
        );
        
        echo json_encode($performance);
    }
}
