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

class Dual_mode_helper {
    
    private $CI;
    
    public function __construct() {
        $this->CI =& get_instance();
        $this->CI->load->database();
    }
    
    /**
     * Get current database mode
     */
    public function get_current_mode() {
        $setting = $this->CI->db->where('setting_key', 'database_mode')->get('db_system_settings')->row();
        return $setting ? $setting->setting_value : 'offline';
    }
    
    /**
     * Get installation mode
     */
    public function get_installation_mode() {
        $setting = $this->CI->db->where('setting_key', 'installation_mode')->get('db_system_settings')->row();
        return $setting ? $setting->setting_value : 'single';
    }
    
    /**
     * Switch database mode
     */
    public function switch_mode($new_mode) {
        if (!in_array($new_mode, ['offline', 'online'])) {
            return false;
        }
        
        $current_mode = $this->get_current_mode();
        if ($current_mode === $new_mode) {
            return true; // Already in the requested mode
        }
        
        // Update database mode
        $this->CI->db->where('setting_key', 'database_mode')->update('db_system_settings', [
            'setting_value' => $new_mode
        ]);
        
        // Update mode switch count
        $count_setting = $this->CI->db->where('setting_key', 'mode_switch_count')->get('db_system_settings')->row();
        $new_count = $count_setting ? (int)$count_setting->setting_value + 1 : 1;
        
        $this->CI->db->where('setting_key', 'mode_switch_count')->update('db_system_settings', [
            'setting_value' => (string)$new_count
        ]);
        
        // Update last mode switch timestamp
        $this->CI->db->where('setting_key', 'last_mode_switch')->update('db_system_settings', [
            'setting_value' => date('Y-m-d H:i:s')
        ]);
        
        // Update database configuration file
        $this->update_database_config($new_mode);
        
        // Auto-sync if switching to online mode
        if ($new_mode === 'online') {
            $this->CI->load->helper('data_sync');
            $sync_helper = new Data_sync_helper();
            $sync_result = $sync_helper->auto_sync_on_online();
            
            // Log sync result
            if ($sync_result['success']) {
                log_message('info', 'Auto-sync completed: ' . $sync_result['message']);
            } else {
                log_message('warning', 'Auto-sync failed: ' . $sync_result['message']);
            }
        }
        
        return true;
    }
    
    /**
     * Update database configuration file
     */
    private function update_database_config($mode) {
        $config_path = APPPATH . 'config/database.php';
        
        if (!file_exists($config_path)) {
            return false;
        }
        
        $config_content = file_get_contents($config_path);
        
        // Update the active_group variable
        $config_content = preg_replace(
            '/\$active_group\s*=\s*[\'"][^\'"]*[\'"];/',
            '$active_group = \'' . $mode . '\';',
            $config_content
        );
        
        // Update the default configuration
        $config_content = preg_replace(
            '/\$db\[\'default\'\]\s*=\s*\$db\[[^\]]+\];/',
            '$db[\'default\'] = $db[\'' . $mode . '\'];',
            $config_content
        );
        
        return file_put_contents($config_path, $config_content) !== false;
    }
    
    /**
     * Get database configuration for a specific mode
     */
    public function get_database_config($mode = null) {
        if ($mode === null) {
            $mode = $this->get_current_mode();
        }
        
        $config_key = $mode . '_database_config';
        $setting = $this->CI->db->where('setting_key', $config_key)->get('db_system_settings')->row();
        
        if ($setting && $setting->setting_type === 'json') {
            return json_decode($setting->setting_value, true);
        }
        
        return [];
    }
    
    /**
     * Get site URL for a specific mode
     */
    public function get_site_url($mode = null) {
        if ($mode === null) {
            $mode = $this->get_current_mode();
        }
        
        $url_key = $mode . '_url';
        $setting = $this->CI->db->where('setting_key', $url_key)->get('db_system_settings')->row();
        
        return $setting ? $setting->setting_value : '';
    }
    
    /**
     * Check if dual mode is enabled
     */
    public function is_dual_mode() {
        return $this->get_installation_mode() === 'dual';
    }
    
    /**
     * Get mode statistics
     */
    public function get_mode_stats() {
        $stats = [];
        
        $mode_switch_count = $this->CI->db->where('setting_key', 'mode_switch_count')->get('db_system_settings')->row();
        $stats['switch_count'] = $mode_switch_count ? (int)$mode_switch_count->setting_value : 0;
        
        $last_switch = $this->CI->db->where('setting_key', 'last_mode_switch')->get('db_system_settings')->row();
        $stats['last_switch'] = $last_switch ? $last_switch->setting_value : null;
        
        $stats['current_mode'] = $this->get_current_mode();
        $stats['installation_mode'] = $this->get_installation_mode();
        
        // Include sync settings
        $sync_settings = $this->get_sync_settings();
        $stats = array_merge($stats, $sync_settings);
        
        return $stats;
    }
    
    /**
     * Update database configuration settings
     */
    public function update_database_config_settings($mode, $config) {
        $config_key = $mode . '_database_config';
        
        $this->CI->db->where('setting_key', $config_key)->update('db_system_settings', [
            'setting_value' => json_encode($config),
            'setting_type' => 'json'
        ]);
        
        return true;
    }
    
    /**
     * Update URL settings
     */
    public function update_url_settings($mode, $url) {
        $url_key = $mode . '_url';
        
        $this->CI->db->where('setting_key', $url_key)->update('db_system_settings', [
            'setting_value' => $url
        ]);
        
        return true;
    }
    
    /**
     * Set current mode (alias for switch_mode for backward compatibility)
     */
    public function set_current_mode($mode) {
        return $this->switch_mode($mode);
    }
    
    /**
     * Bump switch statistics
     */
    public function bump_switch_stats() {
        // Update mode switch count
        $count_setting = $this->CI->db->where('setting_key', 'mode_switch_count')->get('db_system_settings')->row();
        $new_count = $count_setting ? (int)$count_setting->setting_value + 1 : 1;
        
        $this->CI->db->where('setting_key', 'mode_switch_count')->update('db_system_settings', [
            'setting_value' => (string)$new_count
        ]);
        
        // Update last mode switch timestamp
        $this->CI->db->where('setting_key', 'last_mode_switch')->update('db_system_settings', [
            'setting_value' => date('Y-m-d H:i:s')
        ]);
        
        return true;
    }
    
    /**
     * Perform data synchronization
     */
    public function perform_sync() {
        try {
            // Check if data sync helper exists
            if (file_exists(APPPATH . 'helpers/data_sync_helper.php')) {
                $this->CI->load->helper('data_sync_helper');
                if (class_exists('Data_sync_helper')) {
                    $sync_helper = new Data_sync_helper();
                    return $sync_helper->sync_all_data();
                }
            }
            
            // Fallback: Simple sync simulation
            $this->mark_last_sync();
            return [
                'success' => true,
                'message' => 'Data synchronization completed (simulation)',
                'records_synced' => 0
            ];
            
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => 'Sync failed: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * Mark last sync time
     */
    public function mark_last_sync() {
        $this->CI->db->where('setting_key', 'last_sync_time')->update('db_system_settings', [
            'setting_value' => date('Y-m-d H:i:s')
        ]);
        
        return true;
    }
    
    /**
     * Set auto sync setting
     */
    public function set_auto_sync($enable) {
        $this->CI->db->where('setting_key', 'sync_enabled')->update('db_system_settings', [
            'setting_value' => $enable ? '1' : '0'
        ]);
        
        return true;
    }
    
    /**
     * Get sync settings
     */
    public function get_sync_settings() {
        $sync_enabled = $this->CI->db->where('setting_key', 'sync_enabled')->get('db_system_settings')->row();
        $last_sync = $this->CI->db->where('setting_key', 'last_sync_time')->get('db_system_settings')->row();
        $sync_frequency = $this->CI->db->where('setting_key', 'sync_frequency')->get('db_system_settings')->row();
        
        return [
            'sync_enabled' => $sync_enabled ? (bool)$sync_enabled->setting_value : false,
            'last_sync_time' => $last_sync ? $last_sync->setting_value : null,
            'sync_frequency' => $sync_frequency ? (int)$sync_frequency->setting_value : 300
        ];
    }
}
