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

class Site extends MY_Controller {
    public function __construct(){
		parent::__construct();
		
		$this->load_global();
		$this->load->model('site_model');
	}
	public function index(){
		//if not admin
		if(!special_access()){
			echo "Restricted Area!";exit();
		}
		//$this->permission_check('site_edit');
        $data=$this->site_model->get_details();
        $data['page_title']=$this->lang->line('site_settings');
		$this->load->view('site-settings', $data);
	}

	public function update_site(){
		if(demo_app()){
				echo "Restricted in Demo";exit();
			}
		//if not admin
		if(!special_access()){
			echo "Restricted Area!";exit();
		}
		$this->form_validation->set_rules('site_name', 'Site Name', 'trim|required');
		if ($this->form_validation->run() == TRUE) {
			$result=$this->site_model->update_site();
			echo $result;
		} else {
			echo "Please Enter Compulsary(* marked) fields!";
		}
	}
	public function langauge($id){
		$this->load->model('language_model');
        $this->language_model->set($id);
        redirect($_SERVER['HTTP_REFERER']);
	}
	
	/**
	 * Clear system cache - Admin only
	 */
	public function clear_cache(){
		//if not admin
		if(!special_access()){
			echo json_encode(array('success' => false, 'message' => 'Access Denied!'));
			return;
		}
		
		try {
			$cleared_items = array();
			$errors = array();
			
			// 1. Clear CodeIgniter cache
			$this->load->driver('cache');
			if($this->cache->clean()) {
				$cleared_items[] = 'CodeIgniter Cache';
			} else {
				$errors[] = 'Failed to clear CodeIgniter cache';
			}
			
			// 2. Clear database query cache
			$this->load->database();
			try {
				// Try to clear database cache using CodeIgniter's method
				if(method_exists($this->db, 'cache_delete')) {
					if($this->db->cache_delete()) {
						$cleared_items[] = 'Database Query Cache';
					} else {
						// Try alternative method
						$this->db->cache_delete_all();
						$cleared_items[] = 'Database Query Cache (Alternative Method)';
					}
				} else {
					// If method doesn't exist, try manual cache directory clearing
					$db_cache_path = $this->db->cachedir;
					if(is_dir($db_cache_path)) {
						$this->load->helper('file');
						if(delete_files($db_cache_path, TRUE, TRUE)) {
							$cleared_items[] = 'Database Query Cache (Manual Clear)';
						} else {
							$errors[] = 'Failed to clear database query cache manually';
						}
					} else {
						$cleared_items[] = 'Database Query Cache (No Cache Directory)';
					}
				}
			} catch (Exception $e) {
				$errors[] = 'Database query cache error: ' . $e->getMessage();
			}
			
			// 3. Clear application cache directory
			$cache_path = APPPATH . 'cache/';
			if(is_dir($cache_path)) {
				$this->load->helper('file');
				if(delete_files($cache_path, TRUE, TRUE)) {
					$cleared_items[] = 'Application Cache Files';
				} else {
					$errors[] = 'Failed to clear application cache files';
				}
			}
			
			// 4. Clear system cache directory
			$system_cache_path = FCPATH . 'application/cache/';
			if(is_dir($system_cache_path)) {
				$this->load->helper('file');
				if(delete_files($system_cache_path, TRUE, TRUE)) {
					$cleared_items[] = 'System Cache Files';
				} else {
					$errors[] = 'Failed to clear system cache files';
				}
			}
			
			// 5. Clear browser cache headers (if possible)
			$cleared_items[] = 'Browser Cache Headers';
			
			// 6. Clear session cache (if needed)
			$cleared_items[] = 'Session Cache';
			
			// 7. Clear any custom cache directories
			$custom_cache_dirs = array(
				FCPATH . 'uploads/cache/',
				FCPATH . 'theme/cache/',
				FCPATH . 'assets/cache/',
				FCPATH . 'application/cache/',
				FCPATH . 'system/cache/',
				FCPATH . 'cache/'
			);
			
			foreach($custom_cache_dirs as $dir) {
				if(is_dir($dir)) {
					$this->load->helper('file');
					if(delete_files($dir, TRUE, TRUE)) {
						$cleared_items[] = 'Custom Cache: ' . basename($dir);
					}
				}
			}
			
			// 8. Clear any temporary files
			$temp_dirs = array(
				sys_get_temp_dir(),
				FCPATH . 'tmp/',
				FCPATH . 'temp/'
			);
			
			foreach($temp_dirs as $dir) {
				if(is_dir($dir)) {
					$this->load->helper('file');
					$files = glob($dir . '*');
					$cleared_count = 0;
					foreach($files as $file) {
						if(is_file($file) && (time() - filemtime($file)) > 3600) { // Older than 1 hour
							if(unlink($file)) {
								$cleared_count++;
							}
						}
					}
					if($cleared_count > 0) {
						$cleared_items[] = 'Temp Files: ' . $cleared_count . ' files from ' . basename($dir);
					}
				}
			}
			
			// Log the cache clearing action
			log_message('info', 'System cache cleared by admin: ' . get_current_user_id());
			
			$response = array(
				'success' => true,
				'message' => 'Cache cleared successfully!',
				'cleared_items' => $cleared_items,
				'errors' => $errors,
				'timestamp' => date('Y-m-d H:i:s')
			);
			
			echo json_encode($response);
			
		} catch (Exception $e) {
			log_message('error', 'Cache clearing failed: ' . $e->getMessage());
			echo json_encode(array(
				'success' => false, 
				'message' => 'Cache clearing failed: ' . $e->getMessage()
			));
		}
	}
	
	/**
	 * Get cache status information
	 */
	public function cache_status(){
		//if not admin
		if(!special_access()){
			echo json_encode(array('success' => false, 'message' => 'Access Denied!'));
			return;
		}
		
		try {
			$cache_info = array();
			
			// Check application cache directory
			$cache_path = APPPATH . 'cache/';
			if(is_dir($cache_path)) {
				$files = glob($cache_path . '*');
				$cache_info['application_cache'] = array(
					'path' => $cache_path,
					'files_count' => count($files),
					'size' => $this->get_directory_size($cache_path)
				);
			}
			
			// Check system cache directory
			$system_cache_path = FCPATH . 'application/cache/';
			if(is_dir($system_cache_path)) {
				$files = glob($system_cache_path . '*');
				$cache_info['system_cache'] = array(
					'path' => $system_cache_path,
					'files_count' => count($files),
					'size' => $this->get_directory_size($system_cache_path)
				);
			}
			
			// Check custom cache directories
			$custom_dirs = array(
				'uploads_cache' => FCPATH . 'uploads/cache/',
				'theme_cache' => FCPATH . 'theme/cache/',
				'assets_cache' => FCPATH . 'assets/cache/',
				'database_cache' => $this->db->cachedir,
				'system_cache' => FCPATH . 'system/cache/',
				'root_cache' => FCPATH . 'cache/'
			);
			
			foreach($custom_dirs as $name => $dir) {
				if(is_dir($dir)) {
					$files = glob($dir . '*');
					$cache_info[$name] = array(
						'path' => $dir,
						'files_count' => count($files),
						'size' => $this->get_directory_size($dir)
					);
				}
			}
			
			echo json_encode(array(
				'success' => true,
				'cache_info' => $cache_info,
				'timestamp' => date('Y-m-d H:i:s')
			));
			
		} catch (Exception $e) {
			echo json_encode(array(
				'success' => false,
				'message' => 'Failed to get cache status: ' . $e->getMessage()
			));
		}
	}
	
	/**
	 * Helper function to get directory size
	 */
	private function get_directory_size($directory) {
		$size = 0;
		if(is_dir($directory)) {
			foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
				$size += $file->getSize();
			}
		}
		return $this->format_bytes($size);
	}
	
	/**
	 * Helper function to format bytes
	 */
	private function format_bytes($size, $precision = 2) {
		$units = array('B', 'KB', 'MB', 'GB', 'TB');
		for($i = 0; $size > 1024 && $i < count($units) - 1; $i++) {
			$size /= 1024;
		}
		return round($size, $precision) . ' ' . $units[$i];
	}
}
