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

class Admin extends Admin_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Account_model');
        $this->load->model('Transaction_model');
        $this->load->model('Card_model');
        $this->load->model('Wallet_model');
        $this->load->model('Crypto_wallet_model');
    }

    /**
     * Admin Dashboard
     */
    public function dashboard() {
        // Get statistics
        $total_users = $this->User_model->count_all(['user_type' => 'user']);
        $total_accounts = $this->Account_model->count_all();
        $total_transactions = $this->Transaction_model->count_all(['status' => 'completed']);
        $total_cards = $this->Card_model->count_all();
        
        // Get transaction stats for current month
        $month_start = date('Y-m-01');
        $month_end = date('Y-m-t 23:59:59');
        $transaction_stats = $this->Transaction_model->get_statistics($month_start, $month_end);
        
        // Get recent transactions
        $recent_transactions = $this->Transaction_model->get_recent(10);
        
        // Get recent users with KYC status
        $this->db->select('users.*, kyc.verification_status as kyc_status');
        $this->db->from('users');
        $this->db->join('kyc', 'kyc.user_id = users.id', 'left');
        $this->db->where('users.user_type', 'user');
        $this->db->order_by('users.created_at', 'DESC');
        $this->db->limit(5);
        $recent_users = $this->db->get()->result();
        
        // User stats by status
        $active_users = $this->User_model->count_all(['status' => 'active', 'user_type' => 'user']);
        
        // Count users with pending KYC verification
        $this->db->select('COUNT(*) as count');
        $this->db->from('users');
        $this->db->join('kyc', 'kyc.user_id = users.id', 'left');
        $this->db->where('users.user_type', 'user');
        $this->db->where('users.status', 'active');
        $this->db->where('kyc.verification_status', 'pending');
        $pending_users = $this->db->get()->row()->count;
        
        $suspended_users = $this->User_model->count_all(['status' => 'suspended', 'user_type' => 'user']);
        
        $this->data['title'] = 'Admin Dashboard';
        $this->data['total_users'] = $total_users;
        $this->data['total_accounts'] = $total_accounts;
        $this->data['total_transactions'] = $total_transactions;
        $this->data['total_cards'] = $total_cards;
        $this->data['transaction_stats'] = $transaction_stats;
        $this->data['recent_transactions'] = $recent_transactions;
        $this->data['recent_users'] = $recent_users;
        $this->data['active_users'] = $active_users;
        $this->data['pending_users'] = $pending_users;
        $this->data['suspended_users'] = $suspended_users;
        
        $this->render('admin/dashboard', $this->data);
    }

    /**
     * List all users
     */
    public function users() {
        $page = $this->input->get('page') ?: 1;
        $limit = 20;
        $offset = ($page - 1) * $limit;
        
        $filters = [
            'status' => $this->input->get('status'),
            'search' => $this->input->get('search'),
            'user_type' => 'user' // Only regular users
        ];
        
        // Fetch users with KYC status
        $this->db->select('users.*, kyc.verification_status as kyc_status');
        $this->db->from('users');
        $this->db->join('kyc', 'kyc.user_id = users.id', 'left');
        $this->db->where('users.user_type', 'user');
        
        // Apply filters
        if (!empty($filters['status'])) {
            if ($filters['status'] === 'pending_kyc') {
                // Filter for users with pending KYC
                $this->db->where('users.status', 'active');
                $this->db->where('kyc.verification_status', 'pending');
            } else {
                $this->db->where('users.status', $filters['status']);
            }
        }
        if (!empty($filters['search'])) {
            $this->db->group_start();
            $this->db->like('users.first_name', $filters['search']);
            $this->db->or_like('users.last_name', $filters['search']);
            $this->db->or_like('users.email', $filters['search']);
            $this->db->group_end();
        }
        
        $this->db->order_by('users.created_at', 'DESC');
        $this->db->limit($limit, $offset);
        $users = $this->db->get()->result();
        
        // Count total with filters
        if (!empty($filters['status']) && $filters['status'] === 'pending_kyc') {
            // Custom count for pending KYC
            $this->db->select('COUNT(*) as count');
            $this->db->from('users');
            $this->db->join('kyc', 'kyc.user_id = users.id', 'left');
            $this->db->where('users.user_type', 'user');
            $this->db->where('users.status', 'active');
            $this->db->where('kyc.verification_status', 'pending');
            if (!empty($filters['search'])) {
                $this->db->group_start();
                $this->db->like('users.first_name', $filters['search']);
                $this->db->or_like('users.last_name', $filters['search']);
                $this->db->or_like('users.email', $filters['search']);
                $this->db->group_end();
            }
            $total = $this->db->get()->row()->count;
        } else {
            $total = $this->User_model->count_all($filters);
        }
        
        $this->data['title'] = 'Manage Users';
        $this->data['users'] = $users;
        $this->data['total'] = $total;
        $this->data['page'] = $page;
        $this->data['pages'] = ceil($total / $limit);
        $this->data['filters'] = $filters;
        
        $this->render('admin/users', $this->data);
    }

    /**
     * View/Edit user
     */
    public function user($id) {
        $user = $this->User_model->get_with_kyc($id);
        
        if (!$user) {
            show_404();
            return;
        }
        
        // Get user accounts
        $accounts = $this->Account_model->get_by_user($id);
        
        // Get user transactions
        $transactions = $this->Transaction_model->get_by_user($id, [], 10);
        
        // Get user cards
        $cards = $this->Card_model->get_by_user($id);
        
        // Get KYC record
        $kyc = $this->db->get_where('kyc', ['user_id' => $id])->row();
        
        $this->data['title'] = 'User Details';
        $this->data['user_data'] = $user;
        $this->data['accounts'] = $accounts;
        $this->data['transactions'] = $transactions;
        $this->data['cards'] = $cards;
        $this->data['kyc'] = $kyc;
        $this->data['tiers'] = $this->Account_model->get_all_tiers();
        
        $this->render('admin/user_detail', $this->data);
    }

    /**
     * Create new user (by admin)
     */
    public function create_user() {
        if ($this->input->method() === 'get') {
            $this->data['title'] = 'Create User';
            $this->render('admin/create_user', $this->data);
            return;
        }
        
        $this->form_validation->set_rules('first_name', 'First Name', 'required|min_length[2]');
        $this->form_validation->set_rules('last_name', 'Last Name', 'required|min_length[2]');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
        $this->form_validation->set_rules('phone', 'Phone', 'required|is_unique[users.phone]');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[8]');
        $this->form_validation->set_rules('user_type', 'User Type', 'required|in_list[user,business,admin]');
        
        if (!$this->form_validation->run()) {
            if ($this->input->is_ajax_request()) {
                $this->error('Validation failed', validation_errors());
                return;
            }
            $this->data['title'] = 'Create User';
            $this->render('admin/create_user', $this->data);
            return;
        }
        
        // Create user
        $user_id = $this->User_model->create([
            'first_name' => $this->input->post('first_name', TRUE),
            'last_name' => $this->input->post('last_name', TRUE),
            'email' => $this->input->post('email', TRUE),
            'phone' => $this->input->post('phone', TRUE),
            'password' => $this->input->post('password'),
            'user_type' => $this->input->post('user_type', TRUE),
            'status' => 'active'
        ]);
        
        if (!$user_id) {
            $message = 'Failed to create user';
            if ($this->input->is_ajax_request()) {
                $this->error($message);
                return;
            }
            $this->session->set_flashdata('error', $message);
            redirect('admin/create_user');
            return;
        }
        
        // Create KYC record
        $tier = $this->input->post('user_type') === 'business' ? 2 : 1;
        $this->db->insert('kyc', [
            'user_id' => $user_id,
            'tier' => $tier,
            'verification_status' => 'verified',
            'verified_by' => $this->user->id,
            'verified_at' => date('Y-m-d H:i:s'),
            'created_at' => date('Y-m-d H:i:s')
        ]);
        
        // Create default account
        $user = $this->User_model->get($user_id);
        $this->Account_model->create([
            'user_id' => $user_id,
            'account_type' => $this->input->post('account_type', TRUE) ?: 'savings',
            'account_name' => $user->first_name . ' ' . $user->last_name,
            'currency' => 'USD',
            'tier_id' => $tier,
            'status' => 'active',
            'is_primary' => 1
        ]);
        
        // Set initial balance if provided
        $initial_balance = floatval($this->input->post('initial_balance'));
        if ($initial_balance > 0) {
            $account = $this->Account_model->get_primary($user_id);
            $wallet = $this->Wallet_model->get_by_account($account->id, 'USD');
            $this->Wallet_model->credit($wallet->id, $initial_balance);
        }
        
        $this->log_audit('create_user', 'user', $user_id);
        
        $message = 'User created successfully';
        if ($this->input->is_ajax_request()) {
            $this->success($message, ['user_id' => $user_id]);
            return;
        }
        
        $this->session->set_flashdata('success', $message);
        redirect('admin/user/' . $user_id);
    }

    /**
     * Update user status
     */
    public function update_user_status($id) {
        $user = $this->User_model->get($id);
        
        if (!$user) {
            $this->error('User not found');
            return;
        }
        
        $status = $this->input->post('status', TRUE);
        
        if (!in_array($status, ['active', 'inactive', 'suspended', 'pending'])) {
            $this->error('Invalid status');
            return;
        }
        
        $this->User_model->update_status($id, $status);
        $this->log_audit('update_user_status', 'user', $id, ['status' => $user->status], ['status' => $status]);
        
        $this->success('User status updated');
    }

    /**
     * Approve or reject KYC
     */
    public function update_kyc_status($user_id) {
        $user = $this->User_model->get($user_id);
        
        if (!$user) {
            $this->error('User not found');
            return;
        }
        
        $kyc = $this->db->get_where('kyc', ['user_id' => $user_id])->row();
        
        if (!$kyc) {
            $this->error('KYC record not found');
            return;
        }
        
        $status = $this->input->post('status', TRUE);
        $rejection_reason = $this->input->post('rejection_reason', TRUE);
        
        if (!in_array($status, ['approved', 'rejected', 'pending'])) {
            $this->error('Invalid KYC status');
            return;
        }
        
        $update_data = [
            'verification_status' => $status,
            'updated_at' => date('Y-m-d H:i:s')
        ];
        
        if ($status === 'approved') {
            $update_data['verified_at'] = date('Y-m-d H:i:s');
        } elseif ($status === 'rejected' && $rejection_reason) {
            $update_data['rejection_reason'] = $rejection_reason;
        }
        
        $this->db->update('kyc', $update_data, ['user_id' => $user_id]);
        
        // Send notification to user
        $message = $status === 'approved' 
            ? 'Your account has been verified! You can now access all features.' 
            : ($status === 'rejected' 
                ? 'Your account verification was rejected. ' . ($rejection_reason ?: 'Please contact support for more information.')
                : 'Your account verification is under review.');
        
        $this->Notification_model->send($user_id, 'KYC Status Update', $message);
        
        // Send email notification
        $this->load->library('mailer');
        $email_subject = $status === 'approved' ? 'Account Verified' : 'Account Verification Update';
        $email_body = "Hello {$user->first_name},<br><br>{$message}<br><br>Thank you,<br>" . get_app_name();
        $this->mailer->send($user->email, $email_subject, $email_body);
        
        $this->log_audit('update_kyc_status', 'kyc', $kyc->id, ['status' => $kyc->verification_status], ['status' => $status]);
        
        $this->success('KYC status updated successfully');
    }

    /**
     * Create account for user
     */
    public function create_account($user_id) {
        $user = $this->User_model->get($user_id);
        
        if (!$user) {
            if ($this->input->is_ajax_request()) {
                $this->error('User not found');
                return;
            }
            show_404();
            return;
        }
        
        if ($this->input->method() === 'get') {
            $this->data['title'] = 'Create Account';
            $this->data['user_data'] = $user;
            $this->data['tiers'] = $this->Account_model->get_all_tiers();
            $this->render('admin/create_account', $this->data);
            return;
        }
        
        $this->form_validation->set_rules('account_type', 'Account Type', 'required|in_list[savings,current,virtual]');
        $this->form_validation->set_rules('account_name', 'Account Name', 'required');
        $this->form_validation->set_rules('tier_id', 'Tier', 'required|integer');
        
        if (!$this->form_validation->run()) {
            if ($this->input->is_ajax_request()) {
                $this->error('Validation failed', validation_errors());
                return;
            }
            $this->session->set_flashdata('error', validation_errors());
            redirect('admin/create_account/' . $user_id);
            return;
        }
        
        $account_id = $this->Account_model->create([
            'user_id' => $user_id,
            'account_type' => $this->input->post('account_type', TRUE),
            'account_name' => $this->input->post('account_name', TRUE),
            'currency' => $this->input->post('currency', TRUE) ?: 'USD',
            'tier_id' => $this->input->post('tier_id', TRUE),
            'status' => 'active',
            'is_primary' => 0
        ]);
        
        // Set initial balance
        $initial_balance = floatval($this->input->post('initial_balance'));
        if ($initial_balance > 0) {
            $wallet = $this->Wallet_model->get_by_account($account_id, $this->input->post('currency', TRUE) ?: 'USD');
            $this->Wallet_model->credit($wallet->id, $initial_balance);
        }
        
        $this->log_audit('create_account', 'account', $account_id);
        
        $message = 'Account created successfully';
        if ($this->input->is_ajax_request()) {
            $this->success($message, ['account_id' => $account_id]);
            return;
        }
        
        $this->session->set_flashdata('success', $message);
        redirect('admin/user/' . $user_id);
    }

    /**
     * Freeze account
     */
    public function freeze_account($id) {
        $account = $this->Account_model->get($id);
        
        if (!$account) {
            $this->error('Account not found');
            return;
        }
        
        $reason = $this->input->post('reason', TRUE);
        
        $this->Account_model->freeze($id, $reason, $this->user->id);
        $this->log_audit('freeze_account', 'account', $id, null, ['reason' => $reason]);
        
        // Notify user
        $this->Notification_model->send_security_notification($account->user_id, 'account_frozen', ['account' => $account->account_number]);
        
        $this->success('Account frozen successfully');
    }

    /**
     * Unfreeze account
     */
    public function unfreeze_account($id) {
        $account = $this->Account_model->get($id);
        
        if (!$account) {
            $this->error('Account not found');
            return;
        }
        
        $this->Account_model->unfreeze($id);
        $this->log_audit('unfreeze_account', 'account', $id);
        
        $this->success('Account unfrozen successfully');
    }

    /**
     * List all accounts
     */
    public function accounts() {
        $page = $this->input->get('page') ?: 1;
        $limit = 20;
        $offset = ($page - 1) * $limit;
        
        $filters = [
            'status' => $this->input->get('status'),
            'account_type' => $this->input->get('account_type'),
            'search' => $this->input->get('search')
        ];
        
        $accounts = $this->Account_model->get_all($filters, $limit, $offset);
        $total = $this->Account_model->count_all($filters);
        
        $this->data['title'] = 'Manage Accounts';
        $this->data['accounts'] = $accounts;
        $this->data['total'] = $total;
        $this->data['page'] = $page;
        $this->data['pages'] = ceil($total / $limit);
        $this->data['filters'] = $filters;
        
        $this->render('admin/accounts', $this->data);
    }

    /**
     * List all transactions
     */
    public function transactions() {
        $page = $this->input->get('page') ?: 1;
        $limit = 50;
        $offset = ($page - 1) * $limit;
        
        $filters = [
            'type' => $this->input->get('type'),
            'status' => $this->input->get('status'),
            'search' => $this->input->get('search')
        ];
        
        $transactions = $this->Transaction_model->get_all($filters, $limit, $offset);
        $total = $this->Transaction_model->count_all($filters);
        
        $this->data['title'] = 'All Transactions';
        $this->data['transactions'] = $transactions;
        $this->data['total'] = $total;
        $this->data['page'] = $page;
        $this->data['pages'] = ceil($total / $limit);
        $this->data['filters'] = $filters;
        
        $this->render('admin/transactions', $this->data);
    }

    /**
     * View transaction detail
     */
    public function transaction($id) {
        $transaction = $this->Transaction_model->get($id);
        
        if (!$transaction) {
            show_404();
            return;
        }
        
        // Get related accounts
        $source_account = $transaction->source_account_id ? $this->Account_model->get_with_user($transaction->source_account_id) : null;
        $dest_account = $transaction->destination_account_id ? $this->Account_model->get_with_user($transaction->destination_account_id) : null;
        
        $this->data['title'] = 'Transaction Details';
        $this->data['transaction'] = $transaction;
        $this->data['source_account'] = $source_account;
        $this->data['dest_account'] = $dest_account;
        
        $this->render('admin/transaction_detail', $this->data);
    }

    /**
     * Reverse transaction
     */
    public function reverse_transaction($id) {
        $reason = $this->input->post('reason', TRUE);
        
        if (empty($reason)) {
            $this->error('Reason is required');
            return;
        }
        
        $result = $this->Transaction_model->reverse($id, $reason, $this->user->id);
        
        if ($result['success']) {
            $this->log_audit('reverse_transaction', 'transaction', $id, null, ['reason' => $reason]);
            $this->success($result['message']);
        } else {
            $this->error($result['message']);
        }
    }

    /**
     * Credit account
     */
    public function credit_account($account_id) {
        $account = $this->Account_model->get($account_id);
        
        if (!$account) {
            $this->error('Account not found');
            return;
        }
        
        $amount = floatval($this->input->post('amount'));
        $narration = $this->input->post('narration', TRUE) ?: 'Admin credit';
        
        if ($amount <= 0) {
            $this->error('Invalid amount');
            return;
        }
        
        $wallet = $this->Wallet_model->get_by_account($account_id, $account->currency);
        
        // Create transaction
        $transaction_id = $this->Transaction_model->create([
            'type' => 'deposit',
            'category' => 'admin_credit',
            'destination_account_id' => $account_id,
            'destination_wallet_id' => $wallet->id,
            'amount' => $amount,
            'currency' => $account->currency,
            'narration' => $narration,
            'status' => 'completed',
            'metadata' => json_encode(['credited_by' => $this->user->id])
        ]);
        
        // Credit wallet
        $this->Wallet_model->credit($wallet->id, $amount);
        
        $this->log_audit('credit_account', 'account', $account_id, null, ['amount' => $amount, 'narration' => $narration]);
        
        // Get transaction details
        $transaction = $this->Transaction_model->get($transaction_id);
        
        // Notify user (in-app)
        $this->Notification_model->send_transaction_notification($account->user_id, 'credit', $amount, 
            $transaction->reference, $narration);
        
        // Send email notification
        $user = $this->User_model->get($account->user_id);
        $updated_wallet = $this->Wallet_model->get($wallet->id);
        
        $this->load->library('mailer');
        $this->mailer->send_transaction_notification(
            $user->email,
            $user->first_name . ' ' . $user->last_name,
            [
                'type' => 'credit',
                'amount' => format_money($amount, $account->currency),
                'account_number' => $account->account_number,
                'new_balance' => format_money($updated_wallet->available_balance, $account->currency),
                'narration' => $narration,
                'reference' => $transaction->reference,
                'date' => date('M d, Y h:i A', strtotime($transaction->created_at))
            ]
        );
        
        $this->success('Account credited successfully');
    }

    /**
     * Debit account
     */
    public function debit_account($account_id) {
        $account = $this->Account_model->get($account_id);
        
        if (!$account) {
            $this->error('Account not found');
            return;
        }
        
        $amount = floatval($this->input->post('amount'));
        $narration = $this->input->post('narration', TRUE) ?: 'Admin debit';
        
        if ($amount <= 0) {
            $this->error('Invalid amount');
            return;
        }
        
        $wallet = $this->Wallet_model->get_by_account($account_id, $account->currency);
        
        if (!$this->Wallet_model->has_sufficient_balance($wallet->id, $amount)) {
            $this->error('Insufficient balance');
            return;
        }
        
        // Create transaction
        $transaction_id = $this->Transaction_model->create([
            'type' => 'withdrawal',
            'category' => 'admin_debit',
            'source_account_id' => $account_id,
            'source_wallet_id' => $wallet->id,
            'amount' => $amount,
            'currency' => $account->currency,
            'narration' => $narration,
            'status' => 'completed',
            'metadata' => json_encode(['debited_by' => $this->user->id])
        ]);
        
        // Debit wallet
        $this->Wallet_model->debit($wallet->id, $amount);
        
        $this->log_audit('debit_account', 'account', $account_id, null, ['amount' => $amount, 'narration' => $narration]);
        
        // Get transaction details
        $transaction = $this->Transaction_model->get($transaction_id);
        
        // Notify user (in-app)
        $this->Notification_model->send_transaction_notification($account->user_id, 'debit', $amount,
            $transaction->reference, $narration);
        
        // Send email notification
        $user = $this->User_model->get($account->user_id);
        $updated_wallet = $this->Wallet_model->get($wallet->id);
        
        $this->load->library('mailer');
        $this->mailer->send_transaction_notification(
            $user->email,
            $user->first_name . ' ' . $user->last_name,
            [
                'type' => 'debit',
                'amount' => format_money($amount, $account->currency),
                'account_number' => $account->account_number,
                'new_balance' => format_money($updated_wallet->available_balance, $account->currency),
                'narration' => $narration,
                'reference' => $transaction->reference,
                'date' => date('M d, Y h:i A', strtotime($transaction->created_at))
            ]
        );
        
        $this->success('Account debited successfully');
    }

    /**
     * List all cards
     */
    public function cards() {
        $page = $this->input->get('page') ?: 1;
        $limit = 20;
        $offset = ($page - 1) * $limit;
        
        $filters = [
            'status' => $this->input->get('status'),
            'card_type' => $this->input->get('card_type')
        ];
        
        $cards = $this->Card_model->get_all($filters, $limit, $offset);
        $total = $this->Card_model->count_all($filters);
        
        $this->data['title'] = 'Manage Cards';
        $this->data['cards'] = $cards;
        $this->data['total'] = $total;
        $this->data['page'] = $page;
        $this->data['pages'] = ceil($total / $limit);
        $this->data['filters'] = $filters;
        
        $this->render('admin/cards', $this->data);
    }

    /**
     * View card details
     */
    public function card($id) {
        $card = $this->Card_model->get($id);
        
        if (!$card) {
            show_404();
            return;
        }
        
        // Get user and account info
        $card_user = $this->User_model->get($card->user_id);
        $card_account = $this->Account_model->get($card->account_id);
        
        // Get card transactions
        $card_transactions = $this->Card_model->get_card_transactions($id, 20);
        
        $this->data['title'] = 'Card Details';
        $this->data['card'] = $card;
        $this->data['card_user'] = $card_user;
        $this->data['card_account'] = $card_account;
        $this->data['card_transactions'] = $card_transactions;
        
        $this->render('admin/card_detail', $this->data);
    }

    /**
     * Edit card (Admin only)
     */
    public function edit_card($id) {
        $card = $this->Card_model->get($id);
        
        if (!$card) {
            if ($this->input->is_ajax_request()) {
                $this->error('Card not found');
                return;
            }
            show_404();
            return;
        }
        
        $card_user = $this->User_model->get($card->user_id);
        
        if ($this->input->method() === 'post') {
            $update_data = [];
            
            // Editable fields
            $cardholder_name = $this->input->post('cardholder_name', TRUE);
            $status = $this->input->post('status', TRUE);
            $daily_limit = $this->input->post('daily_limit');
            $monthly_limit = $this->input->post('monthly_limit');
            $single_transaction_limit = $this->input->post('single_transaction_limit');
            $balance = $this->input->post('balance');
            $expiry_month = $this->input->post('expiry_month', TRUE);
            $expiry_year = $this->input->post('expiry_year', TRUE);
            
            // Controls
            $is_online_enabled = $this->input->post('is_online_enabled') ? 1 : 0;
            $is_pos_enabled = $this->input->post('is_pos_enabled') ? 1 : 0;
            $is_atm_enabled = $this->input->post('is_atm_enabled') ? 1 : 0;
            $is_international_enabled = $this->input->post('is_international_enabled') ? 1 : 0;
            
            if (!empty($cardholder_name)) {
                $update_data['cardholder_name'] = strtoupper($cardholder_name);
            }
            if (!empty($status) && in_array($status, ['active', 'inactive', 'frozen', 'blocked'])) {
                $update_data['status'] = $status;
            }
            if (is_numeric($daily_limit)) {
                $update_data['daily_limit'] = floatval($daily_limit);
            }
            if (is_numeric($monthly_limit)) {
                $update_data['monthly_limit'] = floatval($monthly_limit);
            }
            if (is_numeric($single_transaction_limit)) {
                $update_data['single_transaction_limit'] = floatval($single_transaction_limit);
            }
            if (is_numeric($balance)) {
                $update_data['balance'] = floatval($balance);
            }
            if (!empty($expiry_month) && is_numeric($expiry_month) && $expiry_month >= 1 && $expiry_month <= 12) {
                $update_data['expiry_month'] = str_pad($expiry_month, 2, '0', STR_PAD_LEFT);
            }
            if (!empty($expiry_year) && is_numeric($expiry_year) && $expiry_year >= date('Y')) {
                $update_data['expiry_year'] = $expiry_year;
            }
            
            // Controls
            $update_data['is_online_enabled'] = $is_online_enabled;
            $update_data['is_pos_enabled'] = $is_pos_enabled;
            $update_data['is_atm_enabled'] = $is_atm_enabled;
            $update_data['is_international_enabled'] = $is_international_enabled;
            
            if (!empty($update_data)) {
                $this->Card_model->update($id, $update_data);
                $this->log_audit('edit_card', 'card', $id, (array)$card, $update_data);
                
                if ($this->input->is_ajax_request()) {
                    $this->success('Card updated successfully');
                    return;
                }
                $this->session->set_flashdata('success', 'Card updated successfully');
            }
            
            redirect('admin/card/' . $id);
            return;
        }
        
        // Show edit form
        $this->data['title'] = 'Edit Card';
        $this->data['card'] = $card;
        $this->data['card_user'] = $card_user;
        
        $this->render('admin/edit_card', $this->data);
    }

    /**
     * Settings page
     */
    public function settings() {
        $this->load->model('Setting_model');
        
        if ($this->input->method() === 'post') {
            $settings = $this->input->post();
            
            // Remove CSRF token from settings
            unset($settings[$this->security->get_csrf_token_name()]);
            
            foreach ($settings as $key => $value) {
                $this->db->replace('settings', [
                    'key' => $key,
                    'value' => $value,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
            }
            
            $this->session->set_flashdata('success', 'Settings updated');
            redirect('admin/settings');
            return;
        }
        
        $settings_rows = $this->db->get('settings')->result();
        $settings = [];
        foreach ($settings_rows as $row) {
            $settings[$row->key] = $row->value;
        }
        
        $this->data['title'] = 'System Settings';
        $this->data['settings'] = $settings;
        
        $this->render('admin/settings', $this->data);
    }
    
    /**
     * Upload branding assets (logo/favicon)
     */
    public function upload_branding() {
        $this->load->model('Setting_model');
        
        // Ensure uploads/branding directory exists
        $upload_path = FCPATH . 'uploads/branding/';
        if (!is_dir($upload_path)) {
            mkdir($upload_path, 0755, true);
        }
        
        $response = ['success' => false, 'message' => ''];
        $type = $this->input->post('type'); // logo, logo_dark, favicon
        
        if (!in_array($type, ['logo', 'logo_dark', 'favicon'])) {
            $response['message'] = 'Invalid upload type';
            $this->json_response($response);
            return;
        }
        
        $config = [
            'upload_path' => $upload_path,
            'allowed_types' => ($type === 'favicon') ? 'png|ico' : 'png|jpg|jpeg|svg',
            'max_size' => 2048, // 2MB
            'file_name' => $type . '_' . time()
        ];
        
        $this->load->library('upload', $config);
        
        if ($this->upload->do_upload('file')) {
            $upload_data = $this->upload->data();
            $filename = $upload_data['file_name'];
            
            // Delete old file if exists
            $setting_key = 'app_' . $type;
            $old_file = $this->Setting_model->get($setting_key);
            if ($old_file && file_exists($upload_path . $old_file)) {
                @unlink($upload_path . $old_file);
            }
            
            // Save new setting
            $this->Setting_model->set($setting_key, $filename, 'file', ucfirst(str_replace('_', ' ', $type)));
            
            $response['success'] = true;
            $response['message'] = ucfirst(str_replace('_', ' ', $type)) . ' uploaded successfully';
            $response['url'] = base_url('uploads/branding/' . $filename);
        } else {
            $response['message'] = strip_tags($this->upload->display_errors());
        }
        
        $this->json_response($response);
    }
    
    /**
     * Remove branding asset
     */
    public function remove_branding() {
        $this->load->model('Setting_model');
        
        $type = $this->input->post('type');
        $setting_key = 'app_' . $type;
        
        if (!in_array($type, ['logo', 'logo_dark', 'favicon'])) {
            $this->error('Invalid type');
            return;
        }
        
        // Delete file
        $filename = $this->Setting_model->get($setting_key);
        if ($filename) {
            $filepath = FCPATH . 'uploads/branding/' . $filename;
            if (file_exists($filepath)) {
                @unlink($filepath);
            }
        }
        
        // Remove setting
        $this->Setting_model->delete($setting_key);
        
        $this->success('Removed successfully');
    }

    /**
     * Create card for user
     */
    public function create_card($user_id) {
        $user = $this->User_model->get($user_id);
        
        if (!$user) {
            $this->error('User not found');
            return;
        }
        
        $account_id = $this->input->post('account_id', TRUE);
        $card_type = $this->input->post('card_type', TRUE);
        $card_brand = $this->input->post('card_brand', TRUE);
        $card_name = $this->input->post('card_name', TRUE);
        $balance = floatval($this->input->post('balance'));
        
        // Verify account belongs to user
        $account = $this->Account_model->get($account_id);
        if (!$account || $account->user_id != $user_id) {
            $this->error('Invalid account');
            return;
        }
        
        // Generate card details
        $card_number = $this->generate_card_number($card_brand);
        $cvv = str_pad(mt_rand(0, 999), 3, '0', STR_PAD_LEFT);
        $expiry_month = date('m');
        $expiry_year = date('Y', strtotime('+3 years'));
        
        // Create card
        $card_data = [
            'user_id' => $user_id,
            'account_id' => $account_id,
            'card_type' => $card_type,
            'card_brand' => $card_brand,
            'card_number' => $card_number,
            'card_number_masked' => '**** **** **** ' . substr($card_number, -4),
            'card_name' => $card_name,
            'cvv' => password_hash($cvv, PASSWORD_DEFAULT),
            'cvv_plain' => $cvv, // Store temporarily for display
            'expiry_month' => $expiry_month,
            'expiry_year' => $expiry_year,
            'balance' => $balance,
            'currency' => $account->currency,
            'status' => 'active',
            'daily_limit' => 5000,
            'monthly_limit' => 50000,
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        $this->db->insert('cards', $card_data);
        $card_id = $this->db->insert_id();
        
        if ($card_id) {
            $this->log_audit('create_card', 'card', $card_id);
            $this->success('Card created successfully');
        } else {
            $this->error('Failed to create card');
        }
    }

    /**
     * Generate card number
     */
    private function generate_card_number($brand = 'mastercard') {
        // Mastercard starts with 5, Visa starts with 4
        $prefix = $brand == 'visa' ? '4' : '5';
        
        do {
            $number = $prefix . str_pad(mt_rand(0, 999999999999999), 15, '0', STR_PAD_LEFT);
        } while ($this->db->where('card_number', $number)->count_all_results('cards') > 0);
        
        return $number;
    }

    /**
     * Edit transaction
     */
    public function edit_transaction($id) {
        $transaction = $this->Transaction_model->get($id);
        
        if (!$transaction) {
            if ($this->input->is_ajax_request()) {
                $this->error('Transaction not found');
                return;
            }
            show_404();
            return;
        }
        
        if ($this->input->method() === 'post') {
            $amount = floatval($this->input->post('amount'));
            $narration = $this->input->post('narration', TRUE);
            $status = $this->input->post('status', TRUE);
            $created_at = $this->input->post('created_at', TRUE);
            
            $update_data = [];
            
            if ($amount > 0) {
                $update_data['amount'] = $amount;
            }
            if (!empty($narration)) {
                $update_data['narration'] = $narration;
            }
            if (!empty($status) && in_array($status, ['pending', 'completed', 'failed', 'reversed'])) {
                $update_data['status'] = $status;
            }
            if (!empty($created_at)) {
                $update_data['created_at'] = date('Y-m-d H:i:s', strtotime($created_at));
            }
            
            if (!empty($update_data)) {
                $update_data['updated_at'] = date('Y-m-d H:i:s');
                $this->Transaction_model->update($id, $update_data);
                $this->log_audit('edit_transaction', 'transaction', $id, (array)$transaction, $update_data);
                
                if ($this->input->is_ajax_request()) {
                    $this->success('Transaction updated successfully');
                    return;
                }
                $this->session->set_flashdata('success', 'Transaction updated successfully');
            }
            
            redirect('admin/transaction/' . $id);
            return;
        }
        
        // Show edit form
        $source_account = $transaction->source_account_id ? $this->Account_model->get_with_user($transaction->source_account_id) : null;
        $dest_account = $transaction->destination_account_id ? $this->Account_model->get_with_user($transaction->destination_account_id) : null;
        
        $this->data['title'] = 'Edit Transaction';
        $this->data['transaction'] = $transaction;
        $this->data['source_account'] = $source_account;
        $this->data['dest_account'] = $dest_account;
        
        $this->render('admin/edit_transaction', $this->data);
    }

    // ==================== Crypto Wallets (Deposit) ====================

    /**
     * List crypto wallets
     */
    public function crypto_wallets() {
        $wallets = $this->Crypto_wallet_model->get_all_wallets(false);
        $this->data['title'] = 'Crypto Wallets';
        $this->data['wallets'] = $wallets;
        $this->render('admin/crypto_wallets', $this->data);
    }

    /**
     * Add crypto wallet
     */
    public function crypto_wallet_add() {
        if ($this->input->method() === 'post') {
            $this->form_validation->set_rules('name', 'Name', 'required|max_length[100]');
            $this->form_validation->set_rules('symbol', 'Symbol', 'required|max_length[20]');
            if ($this->form_validation->run()) {
                $id = $this->Crypto_wallet_model->create_wallet([
                    'name' => $this->input->post('name', TRUE),
                    'symbol' => strtoupper($this->input->post('symbol', TRUE)),
                    'network' => $this->input->post('network', TRUE) ?: null,
                    'instructions' => $this->input->post('instructions', TRUE) ?: null,
                    'is_active' => $this->input->post('is_active') ? 1 : 0,
                    'display_order' => (int) $this->input->post('display_order'),
                ]);
                $this->session->set_flashdata('success', 'Crypto wallet added.');
                redirect('admin/crypto_wallets');
                return;
            }
        }
        $this->data['title'] = 'Add Crypto Wallet';
        $this->data['wallet'] = null;
        $this->render('admin/crypto_wallet_form', $this->data);
    }

    /**
     * Edit crypto wallet
     */
    public function crypto_wallet_edit($id) {
        $wallet = $this->Crypto_wallet_model->get_wallet($id);
        if (!$wallet) {
            show_404();
            return;
        }
        if ($this->input->method() === 'post') {
            $this->form_validation->set_rules('name', 'Name', 'required|max_length[100]');
            $this->form_validation->set_rules('symbol', 'Symbol', 'required|max_length[20]');
            if ($this->form_validation->run()) {
                $this->Crypto_wallet_model->update_wallet($id, [
                    'name' => $this->input->post('name', TRUE),
                    'symbol' => strtoupper($this->input->post('symbol', TRUE)),
                    'network' => $this->input->post('network', TRUE) ?: null,
                    'instructions' => $this->input->post('instructions', TRUE) ?: null,
                    'is_active' => $this->input->post('is_active') ? 1 : 0,
                    'display_order' => (int) $this->input->post('display_order'),
                ]);
                $this->session->set_flashdata('success', 'Crypto wallet updated.');
                redirect('admin/crypto_wallets');
                return;
            }
        }
        $this->data['title'] = 'Edit Crypto Wallet';
        $this->data['wallet'] = $wallet;
        $this->render('admin/crypto_wallet_form', $this->data);
    }

    /**
     * Delete crypto wallet
     */
    public function crypto_wallet_delete($id) {
        $wallet = $this->Crypto_wallet_model->get_wallet($id);
        if (!$wallet) {
            show_404();
            return;
        }
        $this->Crypto_wallet_model->delete_wallet($id);
        $this->session->set_flashdata('success', 'Crypto wallet deleted.');
        redirect('admin/crypto_wallets');
    }

    /**
     * Manage addresses for a crypto wallet
     */
    public function crypto_addresses($wallet_id) {
        $wallet = $this->Crypto_wallet_model->get_wallet($wallet_id);
        if (!$wallet) {
            show_404();
            return;
        }
        $addresses = $this->Crypto_wallet_model->get_addresses_by_wallet($wallet_id, false);
        $this->data['title'] = $wallet->name . ' – Addresses';
        $this->data['wallet'] = $wallet;
        $this->data['addresses'] = $addresses;
        $this->render('admin/crypto_addresses', $this->data);
    }

    /**
     * Add crypto address (POST from form)
     */
    public function crypto_address_add($wallet_id) {
        $wallet = $this->Crypto_wallet_model->get_wallet($wallet_id);
        if (!$wallet) {
            show_404();
            return;
        }
        $this->form_validation->set_rules('address', 'Address', 'required|max_length[255]');
        if ($this->form_validation->run()) {
            $this->Crypto_wallet_model->create_address([
                'crypto_wallet_id' => $wallet_id,
                'address' => $this->input->post('address', TRUE),
                'label' => $this->input->post('label', TRUE) ?: null,
                'is_active' => $this->input->post('is_active') ? 1 : 0,
            ]);
            $this->session->set_flashdata('success', 'Address added.');
        } else {
            $this->session->set_flashdata('error', validation_errors());
        }
        redirect('admin/crypto_addresses/' . $wallet_id);
    }

    /**
     * Delete crypto address
     */
    public function crypto_address_delete($id) {
        $addr = $this->Crypto_wallet_model->get_address($id);
        if (!$addr) {
            show_404();
            return;
        }
        $wallet_id = $addr->crypto_wallet_id;
        $this->Crypto_wallet_model->delete_address($id);
        $this->session->set_flashdata('success', 'Address deleted.');
        redirect('admin/crypto_addresses/' . $wallet_id);
    }
}
