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

class Dual_mode_controller extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->load_global();
        $this->load->helper('security');
        // Optional: your helper that actually reads/saves state
        $this->load->helper('dual_mode_helper');
    }

    public function index() {
        // Defaults
        $current_mode      = 'offline';
        $installation_mode = 'single'; // 'single' | 'multi'
        $is_dual_mode      = false;
        $stats             = [
            'switch_count'   => 0,
            'last_switch'    => null,
            'sync_enabled'   => false,
            'last_sync_time' => null,
            'sync_frequency' => 300 // seconds
        ];

        try {
            if (class_exists('Dual_mode_helper')) {
                $helper            = new Dual_mode_helper();
                
                // Check if we need to initialize dual mode settings
                $this->initialize_dual_mode_settings();
                
                $current_mode      = $helper->get_current_mode();
                $installation_mode = $helper->get_installation_mode();
                $is_dual_mode      = $helper->is_dual_mode();
                $stats             = array_merge($stats, $helper->get_mode_stats());
            }
        } catch (Exception $e) {
            // Keep defaults
        }

        $data                      = $this->data; // from MY_Controller
        $data['page_title']        = 'Dual Mode Management';
        $data['current_mode']      = $current_mode;
        $data['installation_mode'] = $installation_mode;
        $data['is_dual_mode']      = $is_dual_mode;
        $data['stats']             = (object)$stats;
        
        // Ensure footer variables are available
        $data['SITE_TITLE']        = isset($this->data['SITE_TITLE']) ? $this->data['SITE_TITLE'] : 'NCS Billing System';
        $data['VERSION']           = isset($this->data['VERSION']) ? $this->data['VERSION'] : '3.4';

        // Render with the same wrapper structure as your other pages
        $this->load->view('dual_mode_exact', $data);
    }

    public function get_status() {
        $current_mode = 'offline';
        $stats = [
            'sync_enabled'   => false,
            'last_sync_time' => null,
            'sync_frequency' => 300,
            'switch_count'   => 0,
            'last_switch'    => null
        ];

        try {
            if (class_exists('Dual_mode_helper')) {
                $helper        = new Dual_mode_helper();
                $current_mode  = $helper->get_current_mode();
                $stats         = array_merge($stats, $helper->get_mode_stats());
            }
        } catch (Exception $e) {}

        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'success'      => true,
                'current_mode' => $current_mode,
                'stats'        => $stats,
                // Expose navigator.onLine hint so UI can reconcile differences
                'browser_online' => isset($_SERVER['HTTP_CONNECTION']) ? true : null
            ]));
    }

    public function switch_mode() {
        $mode = $this->input->post('mode', true);
        if (!in_array($mode, ['online', 'offline'], true)) {
            return $this->_json(false, 'Invalid mode.');
        }

        try {
            if (class_exists('Dual_mode_helper')) {
                $helper = new Dual_mode_helper();
                $ok     = $helper->set_current_mode($mode); // implement in helper
                if ($ok) {
                    $helper->bump_switch_stats(); // increment counter + set last_switch
                    return $this->_json(true, 'Mode switched successfully', [
                        'current_mode' => $mode
                    ]);
                }
            }
        } catch (Exception $e) {}

        return $this->_json(false, 'Failed to switch mode. Please try again.');
    }

    public function sync_data() {
        try {
            if (class_exists('Dual_mode_helper')) {
                $helper = new Dual_mode_helper();
                $ok     = $helper->perform_sync(); // implement real sync
                if ($ok) {
                    $helper->mark_last_sync(); // save last_sync_time
                    return $this->_json(true, 'Data synchronized successfully', [
                        'last_sync_time' => date('Y-m-d H:i:s')
                    ]);
                }
            }
        } catch (Exception $e) {}

        return $this->_json(false, 'Sync failed. Check connection or try again.');
    }

    public function toggle_auto_sync() {
        $enable = $this->input->post('enable', true);
        $enable = in_array((string)$enable, ['1','true','on'], true);

        try {
            if (class_exists('Dual_mode_helper')) {
                $helper = new Dual_mode_helper();
                $helper->set_auto_sync($enable);
                return $this->_json(true, $enable ? 'Auto-sync enabled' : 'Auto-sync disabled', [
                    'sync_enabled' => $enable
                ]);
            }
        } catch (Exception $e) {}

        return $this->_json(false, 'Could not update auto-sync setting.');
    }
    
    /**
     * Debug method to check dual mode status
     */
    public function debug() {
        $debug_info = [
            'db_system_settings_exists' => $this->db->table_exists('db_system_settings'),
            'database_config_exists' => file_exists(APPPATH . 'config/database.php'),
            'has_offline_config' => false,
            'has_online_config' => false,
            'settings' => []
        ];
        
        if ($debug_info['database_config_exists']) {
            $db_config_content = file_get_contents(APPPATH . 'config/database.php');
            $debug_info['has_offline_config'] = strpos($db_config_content, '$db[\'offline\']') !== false;
            $debug_info['has_online_config'] = strpos($db_config_content, '$db[\'online\']') !== false;
        }
        
        if ($debug_info['db_system_settings_exists']) {
            $settings = $this->db->get('db_system_settings')->result();
            foreach ($settings as $setting) {
                $debug_info['settings'][$setting->setting_key] = $setting->setting_value;
            }
        }
        
        echo '<pre>';
        print_r($debug_info);
        echo '</pre>';
    }
    
    /**
     * Manually enable dual mode
     */
    public function enable_dual_mode() {
        try {
            if (!$this->db->table_exists('db_system_settings')) {
                return $this->_json(false, 'db_system_settings table does not exist. Please run installation first.');
            }
            
            // Force update installation_mode to 'dual'
            $this->db->where('setting_key', 'installation_mode')
                     ->update('db_system_settings', ['setting_value' => 'dual']);
            $this->initialize_setting('database_mode', 'offline');
            $this->initialize_setting('mode_switch_count', '0');
            $this->initialize_setting('last_mode_switch', null);
            $this->initialize_setting('sync_enabled', '0');
            $this->initialize_setting('last_sync_time', null);
            $this->initialize_setting('sync_frequency', '300');
            
            return $this->_json(true, 'Dual mode enabled successfully! You can now switch between online and offline modes.');
            
        } catch (Exception $e) {
            return $this->_json(false, 'Failed to enable dual mode: ' . $e->getMessage());
        }
    }

    private function _json($success, $message, $extra = []) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(array_merge([
                'success' => (bool)$success,
                'message' => $message
            ], $extra)));
    }
    
    /**
     * Initialize dual mode settings if they don't exist
     */
    private function initialize_dual_mode_settings() {
        try {
            // Check if db_system_settings table exists
            if (!$this->db->table_exists('db_system_settings')) {
                return false;
            }
            
            // Check if we have dual mode configuration in database.php
            $db_config_path = APPPATH . 'config/database.php';
            if (file_exists($db_config_path)) {
                $db_config_content = file_get_contents($db_config_path);
                
                // If we have both offline and online configurations, enable dual mode
                if (strpos($db_config_content, '$db[\'offline\']') !== false && 
                    strpos($db_config_content, '$db[\'online\']') !== false) {
                    
                    // Force update installation_mode to 'dual' if it's currently 'single'
                    $this->db->where('setting_key', 'installation_mode')
                             ->update('db_system_settings', ['setting_value' => 'dual']);
                    
                    // Initialize other dual mode settings
                    $this->initialize_setting('database_mode', 'offline');
                    $this->initialize_setting('mode_switch_count', '0');
                    $this->initialize_setting('last_mode_switch', null);
                    $this->initialize_setting('sync_enabled', '0');
                    $this->initialize_setting('last_sync_time', null);
                    $this->initialize_setting('sync_frequency', '300');
                    
                    return true;
                }
            }
        } catch (Exception $e) {
            // Log error but don't break the page
            log_message('error', 'Failed to initialize dual mode settings: ' . $e->getMessage());
        }
        
        return false;
    }
    
    /**
     * Initialize a setting if it doesn't exist
     */
    private function initialize_setting($key, $value) {
        $existing = $this->db->where('setting_key', $key)->get('db_system_settings')->row();
        
        if (!$existing) {
            $this->db->insert('db_system_settings', [
                'setting_key' => $key,
                'setting_value' => $value,
                'setting_type' => is_array($value) ? 'json' : 'string'
            ]);
        }
    }
}
