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

class Data_reset extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->load_global();
        
        // DEBUG: Let's see what session data we have
        $user_id = $this->session->userdata('inv_userid');  // Correct session variable
        $user_role_id = $this->session->userdata('role_id');
        $user_role_name = $this->session->userdata('role_name');
        
        // Log all session data for debugging
        log_message('info', 'Data_reset access attempt - User ID: ' . $user_id . ', Role ID: ' . $user_role_id . ', Role Name: ' . $user_role_name);
        
        // Check if user is logged in
        if (!$user_id) {
            log_message('error', 'Unauthenticated access attempt to Data_reset controller');
            show_error("Access Denied - Not logged in", 403, $heading = "Unauthorized Access!!");
            exit();
        }
        
        // Method 1: Check role_id (1 = admin)
        $is_admin_by_id = ($user_role_id == 1);
        
        // Method 2: Check role_name (case-insensitive)
        $is_admin_by_name = (strtoupper($user_role_name) == strtoupper('admin'));
        
        // Method 3: Use special_access function
        $is_special_access = special_access();
        
        // Method 4: Check if role_id is 2 (store admin)
        $is_store_admin = ($user_role_id == 2);
        
        // Log each check result
        log_message('info', 'Admin checks - By ID: ' . ($is_admin_by_id ? 'YES' : 'NO') . ', By Name: ' . ($is_admin_by_name ? 'YES' : 'NO') . ', Special Access: ' . ($is_special_access ? 'YES' : 'NO') . ', Store Admin: ' . ($is_store_admin ? 'YES' : 'NO'));
        
        // User must pass at least one admin check
        if (!$is_admin_by_id && !$is_admin_by_name && !$is_special_access && !$is_store_admin) {
            log_message('error', 'Non-admin user attempted to access Data_reset controller. User ID: ' . $user_id . ', Role ID: ' . $user_role_id . ', Role Name: ' . $user_role_name);
            show_error("Access Denied - Not admin", 403, $heading = "Unauthorized Access!!");
            exit();
        }
        
        // Log successful admin access for debugging
        log_message('info', 'Admin access granted to Data_reset controller. User ID: ' . $user_id . ', Role ID: ' . $user_role_id . ', Role Name: ' . $user_role_name);
    }

    public function index() {
        $data = $this->data;
        $data['page_title'] = 'Data Reset Settings';
        $this->load->view('data_reset', $data);
    }

    public function debug() {
        // Debug method to check session data
        echo "<h2>Session Debug Information</h2>";
        echo "<p><strong>User ID (inv_userid):</strong> " . $this->session->userdata('inv_userid') . "</p>";
        echo "<p><strong>User ID (user_id):</strong> " . $this->session->userdata('user_id') . "</p>";
        echo "<p><strong>Role ID:</strong> " . $this->session->userdata('role_id') . "</p>";
        echo "<p><strong>Role Name:</strong> " . $this->session->userdata('role_name') . "</p>";
        echo "<p><strong>Username:</strong> " . $this->session->userdata('username') . "</p>";
        echo "<p><strong>Store ID:</strong> " . $this->session->userdata('store_id') . "</p>";
        echo "<p><strong>Logged In:</strong> " . $this->session->userdata('logged_in') . "</p>";
        
        echo "<h3>Admin Checks:</h3>";
        echo "<p><strong>is_admin():</strong> " . (is_admin() ? 'YES' : 'NO') . "</p>";
        echo "<p><strong>is_store_admin():</strong> " . (is_store_admin() ? 'YES' : 'NO') . "</p>";
        echo "<p><strong>special_access():</strong> " . (special_access() ? 'YES' : 'NO') . "</p>";
        
        echo "<h3>Database Test:</h3>";
        try {
            $result = $this->db->query("SELECT 1 as test");
            if($result) {
                echo "<p><strong>Database Connection:</strong> Success</p>";
            } else {
                echo "<p><strong>Database Connection:</strong> Failed</p>";
            }
        } catch (Exception $e) {
            echo "<p><strong>Database Connection:</strong> Error - " . $e->getMessage() . "</p>";
        }
        
        echo "<h3>All Session Data:</h3>";
        echo "<pre>";
        print_r($this->session->all_userdata());
        echo "</pre>";
    }
    
    public function test_reset() {
        // Test method to check if reset operations work
        echo "<h2>Reset Test</h2>";
        
        try {
            // Test foreign key operations
            $this->db->query("SET FOREIGN_KEY_CHECKS = 0");
            echo "<p>✅ Foreign key checks disabled</p>";
            
            $this->db->query("SET FOREIGN_KEY_CHECKS = 1");
            echo "<p>✅ Foreign key checks enabled</p>";
            
            // Test a simple query
            $result = $this->db->query("SELECT COUNT(*) as count FROM db_sales");
            if($result) {
                $row = $result->row();
                echo "<p>✅ Sales table accessible - " . $row->count . " records</p>";
            }
            
            echo "<p><strong>✅ All tests passed! Reset should work.</strong></p>";
            
        } catch (Exception $e) {
            echo "<p><strong>❌ Test failed:</strong> " . $e->getMessage() . "</p>";
        }
    }
    
    public function test_backup() {
        // Test method to check if backup operations work
        echo "<h2>Backup Test</h2>";
        
        try {
            // Test dbutil loading
            $this->load->dbutil();
            echo "<p>✅ Database utility loaded</p>";
            
            // Test file helper
            $this->load->helper('file');
            echo "<p>✅ File helper loaded</p>";
            
            // Test backup directory
            if(!is_dir('dbbackup/')){
                if(mkdir('dbbackup/', 0755, true)) {
                    echo "<p>✅ Backup directory created</p>";
                } else {
                    echo "<p>❌ Failed to create backup directory</p>";
                    return;
                }
            } else {
                echo "<p>✅ Backup directory exists</p>";
            }
            
            // Test if directory is writable
            if(is_writable('dbbackup/')) {
                echo "<p>✅ Backup directory is writable</p>";
            } else {
                echo "<p>❌ Backup directory is not writable</p>";
                return;
            }
            
            // Test ZipArchive
            if(class_exists('ZipArchive')) {
                echo "<p>✅ ZipArchive available</p>";
            } else {
                echo "<p>⚠️ ZipArchive not available (will use SQL format)</p>";
            }
            
            echo "<p><strong>✅ All backup tests passed!</strong></p>";
            
        } catch (Exception $e) {
            echo "<p><strong>❌ Backup test failed:</strong> " . $e->getMessage() . "</p>";
        }
    }
    
    public function test_reset_simple() {
        // Simple test for reset functionality
        echo "<h2>Reset Test</h2>";
        
        try {
            // Test database connection
            $result = $this->db->query("SELECT 1 as test");
            if($result) {
                echo "<p>✅ Database connection works</p>";
            } else {
                echo "<p>❌ Database connection failed</p>";
                return;
            }
            
            // Test foreign key operations
            $this->db->query("SET FOREIGN_KEY_CHECKS = 0");
            echo "<p>✅ Foreign key checks disabled</p>";
            
            $this->db->query("SET FOREIGN_KEY_CHECKS = 1");
            echo "<p>✅ Foreign key checks enabled</p>";
            
            // Test a simple delete (safe test)
            $result = $this->db->query("SELECT COUNT(*) as count FROM db_sales");
            if($result) {
                $row = $result->row();
                echo "<p>✅ Sales table accessible - " . $row->count . " records</p>";
            }
            
            echo "<p><strong>✅ Reset should work!</strong></p>";
            
        } catch (Exception $e) {
            echo "<p><strong>❌ Reset test failed:</strong> " . $e->getMessage() . "</p>";
        }
    }

    public function reset_all_data() {
        // Check if in demo mode
        if (demo_app()) {
            echo json_encode(['status' => 'error', 'message' => 'Data reset is disabled in demo mode.']);
            return;
        }
        
        // Simple admin check
        if (!special_access()) {
            echo json_encode(['status' => 'error', 'message' => 'Access denied. Admin required.']);
            return;
        }

        try {
            // Disable foreign key checks temporarily
            $this->db->query("SET FOREIGN_KEY_CHECKS = 0");
            
            $reset_log = [];
            $errors = [];
            
            // 1. Reset Sales Data
            try {
                $this->db->query("DELETE FROM db_salesitemsreturn");
                $this->db->query("DELETE FROM db_salespaymentsreturn");
                $this->db->query("DELETE FROM db_salesreturn");
                $this->db->query("DELETE FROM db_salespayments");
                $this->db->query("DELETE FROM db_salesitems");
                $this->db->query("DELETE FROM db_sales");
                $reset_log[] = "Sales data cleared";
            } catch (Exception $e) {
                log_message('error', 'Error clearing sales data: ' . $e->getMessage());
                $reset_log[] = "Sales data clear failed: " . $e->getMessage();
            }
            
            // 2. Reset Purchase Data
            $this->db->query("DELETE FROM db_purchaseitemsreturn");
            $this->db->query("DELETE FROM db_purchasepaymentsreturn");
            $this->db->query("DELETE FROM db_purchasereturn");
            $this->db->query("DELETE FROM db_purchasepayments");
            $this->db->query("DELETE FROM db_purchaseitems");
            $this->db->query("DELETE FROM db_purchase");
            $reset_log[] = "Purchase data cleared";
            
            // 3. Reset Quotation Data
            $this->db->query("DELETE FROM db_quotationitems");
            $this->db->query("DELETE FROM db_quotation");
            $reset_log[] = "Quotation data cleared";
            
            // 4. Reset Payment Data (except cash accounts)
            $this->db->query("DELETE FROM db_cobpayments");
            $this->db->query("DELETE FROM db_sobpayments");
            $this->db->query("DELETE FROM db_customer_payments");
            $this->db->query("DELETE FROM db_supplier_payments");
            $this->db->query("DELETE FROM db_custadvance");
            $reset_log[] = "Payment data cleared";
            
            // 5. Reset Money Transfer and Deposit Data
            $this->db->query("DELETE FROM ac_moneytransfer");
            $this->db->query("DELETE FROM ac_moneydeposits");
            $this->db->query("DELETE FROM ac_transactions");
            $reset_log[] = "Money transfer & deposit data cleared";
            
            // 6. Reset Customer Data (except walk-in customers)
            $this->db->query("DELETE FROM db_customer_coupons");
            $this->db->query("DELETE FROM db_shippingaddress WHERE customer_id NOT IN (SELECT id FROM db_customers WHERE delete_bit = 1)");
            $this->db->query("DELETE FROM db_customers WHERE delete_bit != 1");
            $reset_log[] = "Customer data cleared (walk-in customers preserved)";
            
            // 7. Reset Account Data (reset cash account balances to 0, delete others)
            $this->db->query("UPDATE ac_accounts SET balance = 0 WHERE account_name LIKE '%Cash%' OR account_name LIKE '%cash%'");
            $this->db->query("DELETE FROM ac_accounts WHERE account_name NOT LIKE '%Cash%' AND account_name NOT LIKE '%cash%'");
            $reset_log[] = "Account data cleared (cash accounts reset to 0, others deleted)";
            
            // 8. Reset Brand Data
            $this->db->query("DELETE FROM db_brands");
            $reset_log[] = "Brand data cleared";
            
            // 9. Reset Unit Data
            $this->db->query("DELETE FROM db_units");
            $reset_log[] = "Unit data cleared";
            
            // 10. Reset Tax Data
            $this->db->query("DELETE FROM db_tax");
            $reset_log[] = "Tax data cleared";
            
            // 11. Reset Item Data
            $this->db->query("DELETE FROM db_item_batches");
            $this->db->query("DELETE FROM db_warehouseitems");
            $this->db->query("DELETE FROM db_items");
            $reset_log[] = "Item data cleared";
            
            // 12. Reset Category Data
            $this->db->query("DELETE FROM db_category");
            $reset_log[] = "Category data cleared";
            
            // 13. Reset Supplier Data
            $this->db->query("DELETE FROM db_suppliers");
            $reset_log[] = "Supplier data cleared";
            
            // 14. Reset Expense Data
            $this->db->query("DELETE FROM db_expense");
            $this->db->query("DELETE FROM db_expense_category");
            $reset_log[] = "Expense data cleared";
            
            // 15. Reset Stock Data
            $this->db->query("DELETE FROM db_stockadjustmentitems");
            $this->db->query("DELETE FROM db_stockadjustment");
            $this->db->query("DELETE FROM db_stocktransferitems");
            $this->db->query("DELETE FROM db_stocktransfer");
            $this->db->query("DELETE FROM db_stockentry");
            $reset_log[] = "Stock data cleared";
            
            // 16. Reset Hold Data
            $this->db->query("DELETE FROM db_holditems");
            $this->db->query("DELETE FROM db_hold");
            $reset_log[] = "Hold data cleared";
            
            // 17. Reset Coupon Data
            $this->db->query("DELETE FROM db_coupons");
            $reset_log[] = "Coupon data cleared";
            
            // 18. Reset Variant Data
            $this->db->query("DELETE FROM db_variants");
            $reset_log[] = "Variant data cleared";
            
            // 19. Reset Exchange Rate Data
            $this->db->query("DELETE FROM db_exchange_rates");
            $this->db->query("DELETE FROM db_currency_conversion_log");
            $reset_log[] = "Exchange rate data cleared";
            
            // 20. Reset Payment Gateway Data
            $this->db->query("DELETE FROM db_instamojopayments");
            $this->db->query("DELETE FROM db_paypalpaylog");
            $this->db->query("DELETE FROM db_stripepayments");
            $reset_log[] = "Payment gateway data cleared";
            
            // 21. Reset SMS Data
            $this->db->query("DELETE FROM db_promotional_sms_log");
            $reset_log[] = "SMS data cleared";
            
            // 22. Reset Sessions Data
            $this->db->query("DELETE FROM ci_sessions");
            $reset_log[] = "All user sessions cleared from database";
            
            // Re-enable foreign key checks
            $this->db->query("SET FOREIGN_KEY_CHECKS = 1");
            
            // Reset auto-increment counters
            $tables_to_reset = [
                'db_sales', 'db_salesitems', 'db_salespayments', 'db_salesreturn', 'db_salesitemsreturn', 'db_salespaymentsreturn',
                'db_purchase', 'db_purchaseitems', 'db_purchasepayments', 'db_purchasereturn', 'db_purchaseitemsreturn', 'db_purchasepaymentsreturn',
                'db_quotation', 'db_quotationitems',
                'db_customers', 'db_suppliers', 'db_items', 'db_category', 'db_brands', 'db_units', 'db_tax',
                'db_expense', 'db_expense_category', 'db_coupons', 'db_variants',
                'db_stockadjustment', 'db_stockadjustmentitems', 'db_stocktransfer', 'db_stocktransferitems', 'db_stockentry',
                'db_hold', 'db_holditems',
                'ac_accounts', 'ac_transactions', 'ac_moneytransfer', 'ac_moneydeposits',
                'db_cobpayments', 'db_sobpayments', 'db_customer_payments', 'db_supplier_payments', 'db_custadvance',
                'db_exchange_rates', 'db_currency_conversion_log',
                'db_instamojopayments', 'db_paypalpaylog', 'db_stripepayments',
                'db_promotional_sms_log', 'ci_sessions'
            ];
            
            foreach ($tables_to_reset as $table) {
                try {
                    $this->db->query("ALTER TABLE $table AUTO_INCREMENT = 1");
                } catch (Exception $e) {
                    // Table might not exist or might not have auto-increment
                }
            }
            $reset_log[] = "Auto-increment counters reset";
            
            // Clear current session to ensure clean state
            $this->session->sess_destroy();
            $reset_log[] = "Current session destroyed";
            
            echo json_encode([
                'status' => 'success', 
                'message' => 'POS Data Reset Completed Successfully! All sessions cleared. Please login again.',
                'log' => $reset_log
            ]);
            
        } catch (Exception $e) {
            echo json_encode([
                'status' => 'error', 
                'message' => 'Error during reset: ' . $e->getMessage()
            ]);
        }
    }

    public function backup_before_reset() {
        // Check if in demo mode
        if (demo_app()) {
            echo "error|Backup is disabled in demo mode.";
            return;
        }
        
        // Simple admin check
        if (!special_access()) {
            echo "error|Access denied. Admin required.";
            return;
        }

        try {
            $backup_name = 'backup_before_reset_' . date('Y-m-d_H-i-s');
            
            $this->load->dbutil();
            
            if(class_exists('ZipArchive')) {
                $prefs = array(
                    'newline' => "\n",
                    'format' => 'zip',
                    'filename' => $backup_name . '.sql',
                    'foreign_key_checks' => FALSE,
                    'add_drop' => TRUE,
                    'add_insert' => TRUE,
                    'add_if_not_exists' => TRUE,
                    'ignore' => array(),
                    'backup_tables' => TRUE,
                    'backup_views' => FALSE,
                    'backup_routines' => FALSE,
                    'backup_events' => FALSE,
                    'backup_triggers' => FALSE,
                );
                
                $backup = $this->dbutil->backup($prefs);
                
                $this->load->helper('file');
                $filename = 'dbbackup/' . $backup_name . '.zip';
            } else {
                $prefs = array(
                    'newline' => "\n",
                    'format' => 'sql',
                    'filename' => $backup_name . '.sql',
                    'foreign_key_checks' => FALSE,
                    'add_drop' => TRUE,
                    'add_insert' => TRUE,
                    'add_if_not_exists' => TRUE,
                    'ignore' => array(),
                    'backup_tables' => TRUE,
                    'backup_views' => FALSE,
                    'backup_routines' => FALSE,
                    'backup_events' => FALSE,
                    'backup_triggers' => FALSE,
                );
                
                $backup = $this->dbutil->backup($prefs);
                
                $this->load->helper('file');
                $filename = 'dbbackup/' . $backup_name . '.sql';
            }
            
            if(write_file($filename, $backup)){
                echo "success|Backup created: " . basename($filename);
            } else {
                echo "error|Failed to create backup file.";
            }
            
        } catch (Exception $e) {
            echo "error|Backup error: " . $e->getMessage();
        }
    }
    
}
?>
