<?php

namespace App\Controllers;

use App\Models\HistoryModel;
use App\Models\KeysModel;
use App\Models\UserModel;
use Config\Services;

class Keys extends BaseController
{
    protected $userModel, $model, $user, $db;

    public function __construct()
    {
        $this->userModel = new UserModel();
        $this->user = $this->userModel->getUser();
        $this->model = new KeysModel();
        $this->time = new \CodeIgniter\I18n\Time;
        $this->db = \Config\Database::connect();

        // Lấy danh sách game theo permission
        $this->game_list = $this->getGameListByLevel();
        
        $this->duration = [
            2 => '2 Giờ ',
            5 => '5 Giờ ',
            24 => '1 Ngày ',
            72 => '3 Ngày ',
            168 => '7 Ngày ',
            336 => '14 Ngày ',
            720 => '30 Ngày ',
            1440 => '60 Ngày ',
            1920 => '80 Ngày ',
            2880 => '120 Ngày',
            8760 => '365 Ngày ',
        ];

        $this->price = [
            2 => 0,
            5 => 0,
            24 => 0,
            72 => 0,
            168 => 0,
            336 => 0,
            720 => 0,
            1440 => 0,
            1920 => 0,
            2880 => 0,
            8760 => 0,
        ];

        $this->key_types = [
            'regular' => 'Key Normal',
            'vip' => 'VIP Key'
        ];
    }
    
    /**
     * Lấy danh sách game theo level của user
     */
    private function getGameListByLevel()
    {
        $userLevel = $this->user->level ?? 0;
        
        // Level 1 thấy tất cả game
        if ($userLevel == 1) {
            // Lấy tất cả game từ database
            $builder = $this->db->table('game_permissions');
            $builder->select('game_code, game_name')
                    ->where('status', 1);
            
            $games = $builder->get()->getResultArray();
            
            $gameList = [];
            foreach ($games as $game) {
                $gameList[$game['game_code']] = $game['game_name'];
            }
            
            return $gameList;
        }
        
        // Các level khác lấy game theo permission
        $builder = $this->db->table('game_permissions');
        $builder->select('game_code, game_name')
                ->where('status', 1)
                ->where("FIND_IN_SET('$userLevel', allowed_levels) > 0");
        
        $games = $builder->get()->getResultArray();
        
        $gameList = [];
        foreach ($games as $game) {
            $gameList[$game['game_code']] = $game['game_name'];
        }
        
        return $gameList;
    }
    
    /**
     * Lấy tất cả game (dùng cho admin chỉnh sửa)
     */
    private function getAllGames()
    {
        $builder = $this->db->table('game_permissions');
        $builder->select('*')
                ->orderBy('game_name', 'ASC');
        
        return $builder->get()->getResultArray();
    }
    
    /**
     * Lấy danh sách game cho dropdown
     */
    private function getGameListForDropdown()
    {
        $userLevel = $this->user->level ?? 0;
        
        if ($userLevel == 1) {
            $games = $this->getAllGames();
        } else {
            $builder = $this->db->table('game_permissions');
            $builder->select('game_code, game_name')
                    ->where('status', 1)
                    ->where("FIND_IN_SET('$userLevel', allowed_levels) > 0");
            $games = $builder->get()->getResultArray();
        }
        
        $gameList = [];
        foreach ($games as $game) {
            $gameList[$game['game_code']] = $game['game_name'];
        }
        
        return $gameList;
    }
    
    public function api()
    {
        $request = service('request');
        $db = \Config\Database::connect();
        $builder = $db->table('keys_code');

        $columns = [
            'id_keys', 'game', 'user_key', 'key_type',
            'duration', 'expired_date', 'max_devices', 'devices', 'status'
        ];

        // Datatables server-side
        $draw = $request->getGet('draw');
        $start = $request->getGet('start');
        $length = $request->getGet('length');
        $searchValue = $request->getGet('search')['value'];

        if ($searchValue) {
            $builder->groupStart();
            foreach ($columns as $col) {
                $builder->orLike($col, $searchValue);
            }
            $builder->groupEnd();
        }

        $totalCount = $builder->countAllResults(false);

        $builder->limit($length, $start);
        $data = $builder->get()->getResultArray();

        $result = [];
        foreach ($data as $row) {
            $devices = json_decode($row['devices'], true);
            $devices_count = is_array($devices) ? count($devices) : 0;

            $result[] = [
                'id' => $row['id_keys'],
                'game' => $row['game'],
                'user_key' => $row['user_key'],
                'key_type' => strtolower(trim($row['key_type'] ?? 'regular')),
                'duration' => $row['duration'] . 'h',
                'expired' => $row['expired_date'] ? date('d/m/Y H:i', strtotime($row['expired_date'])) : null,
                'devices' => $devices_count,
                'max_devices' => $row['max_devices'],
                'status' => $row['status'] == 1 ? 'Active' : 'Inactive',
            ];
        }

        return $this->response->setJSON([
            'draw' => intval($draw),
            'recordsTotal' => $totalCount,
            'recordsFiltered' => $totalCount,
            'data' => $result
        ]);
    }

    public function index()
    {
        $model = $this->model;
        $user = $this->user;

        if ($user->level != 1) {
            $keys = $model->where('registrator', $user->username)
                ->findAll();
        } else {
            $keys = $model->findAll();
        }

        $data = [
            'title' => 'Keys',
            'user' => $user,
            'keylist' => $keys,
            'time' => $this->time,
            'game_list' => $this->game_list,
        ];
        return view('Keys/list', $data);
    }

    public function api_get_keys()
    {
        $model = $this->model;
        return $model->API_getKeys();
    }

    public function api_key_reset()
    {
        sleep(1);
        $model = $this->model;
        $keys = $this->request->getGet('userkey');
        $reset = $this->request->getGet('reset');
        $db_key = $model->getKeys($keys);

        $rules = [];
        if ($db_key) {
            $total = $db_key->devices ? explode(',', $db_key->devices) : [];
            $rules = ['devices_total' => count($total), 'devices_max' => (int) $db_key->max_devices];
            $user = $this->user;
            if ($db_key->devices && $reset) {
                if ($user->level == 1 || $db_key->registrator == $user->username) {
                    $model->set('devices', NULL)
                        ->where('user_key', $keys)
                        ->update();
                    $rules = ['reset' => true, 'devices_total' => 0, 'devices_max' => $db_key->max_devices];
                }
            }
        }

        $data = [
            'registered' => $db_key ? true : false,
            'keys' => $keys,
        ];

        return $this->response->setJSON(array_merge($data, $rules));
    }

    public function edit_key($key = false)
    {
        if ($this->request->getPost()) return $this->edit_key_action();
        
        $msgDanger = "The user key no longer exists.";
        if ($key) {
            $dKey = $this->model->getKeys($key, 'id_keys');
            $user = $this->user;
            if ($dKey) {
                if ($user->level == 1 || $dKey->registrator == $user->username) {
                    $validation = Services::validation();
                    
                    // Lấy game list phù hợp
                    $gameList = $this->getGameListForDropdown();
                    
                    $data = [
                        'title' => 'Edit Key',
                        'user' => $user,
                        'key' => $dKey,
                        'game_list' => $gameList,
                        'time' => $this->time,
                        'key_info' => getDevice($dKey->devices),
                        'key_types' => $this->key_types,
                        'messages' => setMessage('Please carefully edit information'),
                        'validation' => $validation,
                    ];
                    return view('Keys/key_edit', $data);
                } else {
                    $msgDanger = "Restricted to this user key.";
                }
            }
        }
        return redirect()->to('keys')->with('msgDanger', $msgDanger);
    }

    private function edit_key_action()
    {
        $keys = $this->request->getPost('id_keys');
        $user = $this->user;
        $dKey = $this->model->getKeys($keys, 'id_keys');
        
        // Lấy danh sách game cho validation
        $gameList = $this->getGameListForDropdown();
        $game = implode(",", array_keys($gameList));
        $key_types = implode(",", array_keys($this->key_types));

        if (!$dKey) {
            return redirect()->to('keys')->with('msgDanger', "The user key no longer exists~");
        }

        if ($user->level != 1 && $dKey->registrator != $user->username) {
            return redirect()->to('keys')->with('msgDanger', "Restricted to this user key~");
        }

        $form_reseller = [
            'status' => [
                'label' => 'status',
                'rules' => 'required|integer|in_list[0,1]',
                'errors' => [
                    'integer' => 'Invalid {field}.',
                    'in_list' => 'Choose between list.'
                ]
            ],
            'key_type' => [
                'label' => 'key type',
                'rules' => "required|in_list[$key_types]",
                'errors' => [
                    'in_list' => 'Invalid key type.'
                ]
            ]
        ];

        $form_admin = [
            'id_keys' => [
                'label' => 'keys',
                'rules' => 'required|is_not_unique[keys_code.id_keys]|numeric',
                'errors' => [
                    'is_not_unique' => 'Invalid keys.'
                ],
            ],
            'game' => [
                'label' => 'Games',
                'rules' => "required|regex_match[/^[a-zA-Z0-9_.-]+$/]|in_list[$game]",
                'errors' => [
                    'regex_match' => 'Game contains invalid characters.'
                ],
            ],
            'user_key' => [
                'label' => 'User keys',
                'rules' => "required|is_unique[keys_code.user_key,user_key,$dKey->user_key]|min_length[4]|max_length[64]",
                'errors' => [
                    'is_unique' => '{field} has been taken.',
                    'min_length' => '{field} must be at least {param} characters.',
                    'max_length' => '{field} cannot exceed {param} characters.'
                ],
            ],
            'duration' => [
                'label' => 'duration',
                'rules' => 'required|numeric|greater_than_equal_to[1]',
                'errors' => [
                    'greater_than_equal_to' => 'Minimum {field} is invalid.',
                    'numeric' => 'Invalid day {field}.'
                ]
            ],
            'max_devices' => [
                'label' => 'devices',
                'rules' => 'required|numeric|greater_than_equal_to[1]',
                'errors' => [
                    'greater_than_equal_to' => 'Minimum {field} is invalid.',
                    'numeric' => 'Invalid max of {field}.'
                ]
            ],
            'registrator' => [
                'label' => 'registrator',
                'rules' => 'permit_empty|regex_match[/^[a-zA-Z0-9_.\- ]{4,64}$/]',
                'errors' => [
                    'regex_match' => 'Invalid registrator name.'
                ]
            ],
            'expired_date' => [
                'label' => 'expired',
                'rules' => 'permit_empty|valid_date[Y-m-d H:i:s]',
                'errors' => [
                    'valid_date' => 'Invalid {field} date.',
                ]
            ],
            'devices' => [
                'label' => 'device list',
                'rules' => 'permit_empty'
            ]
        ];

        if ($user->level == 1) {
            $form_rules = array_merge($form_reseller, $form_admin);
            $devices = $this->request->getPost('devices');
            $max_devices = $this->request->getPost('max_devices');
            
            // Kiểm tra game có tồn tại không
            $selectedGame = $this->request->getPost('game');
            if (!array_key_exists($selectedGame, $gameList)) {
                return redirect()->back()->withInput()->with('msgDanger', 'Invalid game selection.');
            }

            $data_saves = [
                'game' => $selectedGame,
                'user_key' => $this->request->getPost('user_key'),
                'duration' => $this->request->getPost('duration'),
                'max_devices' => $max_devices,
                'status' => $this->request->getPost('status'),
                'key_type' => $this->request->getPost('key_type'),
                'registrator' => $this->request->getPost('registrator'),
                'expired_date' => $this->request->getPost('expired_date') ?: NULL,
                'devices' => setDevice($devices, $max_devices),
            ];
        } else {
            $form_rules = $form_reseller;
            $data_saves = [
                'status' => $this->request->getPost('status'),
                'key_type' => $this->request->getPost('key_type')
            ];
        }

        if (!$this->validate($form_rules)) {
            return redirect()->back()->withInput()->with('msgDanger', 'Failed! Please check the error');
        }

        $this->model->update($dKey->id_keys, $data_saves);
        return redirect()->back()->with('msgSuccess', 'User key successfully updated!');
    }

    public function generate()
    {
        if ($this->request->getPost()) {
            return $this->generate_action();
        }

        $user = $this->user;
        $validation = Services::validation();

        $message = setMessage("<i class='bi bi-wallet'></i> Total Saldo $$user->saldo");
        if ($user->saldo <= 0) {
            $message = setMessage("Please top up to your beloved admin.", 'warning');
        }

        // Lấy danh sách game theo level
        $gameList = $this->getGameListForDropdown();
        
        // Kiểm tra nếu không có game nào
        if (empty($gameList)) {
            $message = setMessage("No games available for your level.", 'warning');
        }

        $data = [
            'title' => 'Generate Keys',
            'user' => $user,
            'time' => $this->time,
            'game' => $gameList,
            'duration' => $this->duration,
            'price' => json_encode($this->price),
            'key_types' => $this->key_types,
            'messages' => $message,
            'validation' => $validation,
        ];
        return view('Keys/generate', $data);
    }

    private function generate_action()
    {
        $user = $this->user;
        $game = $this->request->getPost('game');
        $maxd = $this->request->getPost('max_devices');
        $drtn = $this->request->getPost('duration');
        $key_type = strtolower(trim($this->request->getPost('key_type')));
        $key_gen_type = $this->request->getPost('key_gen_type');
        $custom_key = trim($this->request->getPost('custom_key'));
        $loopcount = (int)$this->request->getPost('loopcount');

        // Kiểm tra game có trong danh sách được phép không
        $gameList = $this->getGameListForDropdown();
        if (!array_key_exists($game, $gameList)) {
            return redirect()->back()->withInput()->with('msgDanger', 'Invalid game selection.');
        }

        $game_list = implode(",", array_keys($gameList));
        $key_types = implode(",", array_keys($this->key_types));

        $form_rules = [
            'game' => [
                'label' => 'Games',
                'rules' => "required|alpha_numeric_space|in_list[$game_list]",
            ],
            'duration' => [
                'label' => 'duration',
                'rules' => 'required|numeric|greater_than_equal_to[1]',
            ],
            'max_devices' => [
                'label' => 'devices',
                'rules' => 'required|numeric|greater_than_equal_to[1]',
            ],
            'key_type' => [
                'label' => 'key type',
                'rules' => "required|in_list[$key_types]",
            ],
            'key_gen_type' => [
                'label' => 'key generation type',
                'rules' => 'required|in_list[random,custom]',
            ],
            'loopcount' => [
                'label' => 'loop count',
                'rules' => 'required|numeric|greater_than_equal_to[1]',
            ]
        ];
        
        // Thêm rule cho custom_key nếu chọn custom
        if ($key_gen_type == 'custom') {
            $form_rules['custom_key'] = [
                'label' => 'custom key',
                'rules' => 'required|min_length[4]|max_length[64]',
                'errors' => [
                    'min_length' => 'Key must be at least {param} characters.',
                    'max_length' => 'Key cannot exceed {param} characters.'
                ]
            ];
        }

        if (!$this->validate($form_rules)) {
            return redirect()->back()->withInput()->with('msgDanger', 'Failed! Please check the error');
        }

        $getPrice = getPrice($this->price, $drtn, $maxd) * $loopcount;
        $reduceCheck = $user->saldo - $getPrice;

        if ($reduceCheck < 0) {
            return redirect()->back()->withInput()->with('msgWarning', 'Insufficient balance. Please top up.');
        }

        $generated_keys = [];
        $history = new HistoryModel();

        for ($i = 0; $i < $loopcount; $i++) {
            // Tạo key tùy theo loại
            if ($key_gen_type == 'custom') {
                if ($loopcount == 1) {
                    $license = $custom_key;
                } else {
                    $license = $custom_key . '_' . ($i + 1);
                }
            } else {
                // Random key
                $license = strtolower(random_string('alnum', 10));
            }
            
            // Kiểm tra key có tồn tại chưa
            $existingKey = $this->model->where('user_key', $license)->first();
            if ($existingKey) {
                return redirect()->back()->withInput()->with('msgDanger', "Key '$license' already exists. Please use a different base key.");
            }

            $data_response = [
                'game' => $game,
                'user_key' => $license,
                'duration' => $drtn,
                'max_devices' => $maxd,
                'registrator' => $user->username,
                'key_type' => $key_type
            ];

            $idKeys = $this->model->insert($data_response);
            $generated_keys[] = $license;

            $history->insert([
                'keys_id' => $idKeys,
                'user_do' => $user->username,
                'info' => "$game|" . substr($license, 0, 5) . "|$drtn|$maxd|$key_type"
            ]);
        }

        // Cập nhật số dư
        $this->userModel->update(session('userid'), ['saldo' => $reduceCheck]);

        $msg = "Successfully Generated " . count($generated_keys) . " keys (" . ucfirst($key_type) . ")";

        session()->setFlashdata([
            'game' => $game,
            'duration' => $drtn,
            'max_devices' => $maxd,
            'user_key' => $license,
            'key_type' => $key_type,
            'fees' => $getPrice,
            'generated_keys' => $generated_keys,
            'saldo_after' => $reduceCheck,
            'generated_at' => date('d/m/Y H:i')
        ]);

        return redirect()->back()->with('msgSuccess', $msg);
    }

    public function delete_bulk()
    {
        $keys = $this->request->getPost('keys');

        if (!is_array($keys) || empty($keys)) {
            return $this->response->setJSON([
                'status' => false,
                'message' => 'Không có key nào được chọn'
            ]);
        }

        $user = $this->user;
        $db = \Config\Database::connect();
        $builder = $db->table('keys_code');
        $deleted = 0;

        foreach ($keys as $key) {
            $row = $builder->where('user_key', $key)->get()->getRow();
            if ($row && ($user->level == 1 || $row->registrator === $user->username)) {
                $builder->where('user_key', $key)->delete();
                $deleted++;
            }
        }

        return $this->response->setJSON([
            'status' => true,
            'message' => "Đã xoá {$deleted} key thành công."
        ]);
    }

    /**
     * Trang quản lý game - Danh sách game
     */
    public function manage_games()
    {
        $user = $this->user;
        
        if ($user->level != 1) {
            return redirect()->to('keys')->with('msgDanger', 'Access denied.');
        }
        
        $games = $this->getAllGames();
        
        $data = [
            'title' => 'Game Management',
            'user' => $user,
            'games' => $games,
            'time' => $this->time,
        ];
        
        return view('Keys/manage_games', $data);
    }
    
    /**
     * Trang thêm game mới
     */
    public function add_game()
    {
        $user = $this->user;
        
        if ($user->level != 1) {
            return redirect()->to('keys')->with('msgDanger', 'Access denied.');
        }
        
        $data = [
            'title' => 'Add New Game',
            'user' => $user,
            'time' => $this->time,
            'validation' => Services::validation(),
        ];
        
        return view('Keys/game_form', $data);
    }
    
    /**
     * Trang sửa game
     */
    public function edit_game($id = null)
    {
        $user = $this->user;
        
        if ($user->level != 1) {
            return redirect()->to('keys')->with('msgDanger', 'Access denied.');
        }
        
        if (!$id) {
            return redirect()->to('keys/manage-games')->with('msgDanger', 'Game ID is required.');
        }
        
        $builder = $this->db->table('game_permissions');
        $game = $builder->where('id', $id)->get()->getRow();
        
        if (!$game) {
            return redirect()->to('keys/manage-games')->with('msgDanger', 'Game not found.');
        }
        
        $data = [
            'title' => 'Edit Game',
            'user' => $user,
            'game' => $game,
            'time' => $this->time,
            'validation' => Services::validation(),
        ];
        
        return view('Keys/game_form', $data);
    }
    
    /**
     * Xử lý lưu game (thêm/sửa) - FIXED VERSION
     */
    public function save_game()
    {
        $user = $this->user;
        
        if ($user->level != 1) {
            return redirect()->to('keys')->with('msgDanger', 'Access denied.');
        }
        
        $id = $this->request->getPost('id');
        $isEdit = !empty($id);
        
        // Debug dữ liệu POST nếu cần
        // print_r($this->request->getPost()); exit;
        
        // Đơn giản hóa validation để test
        $gameCode = strtoupper(trim($this->request->getPost('game_code')));
        $gameName = trim($this->request->getPost('game_name'));
        $allowedLevels = trim($this->request->getPost('allowed_levels'));
        $status = $this->request->getPost('status');
        
        // Kiểm tra dữ liệu cơ bản
        if (empty($gameCode) || empty($gameName) || empty($allowedLevels)) {
            return redirect()->back()->withInput()->with('msgDanger', 'Please fill all required fields.');
        }
        
        // Kiểm tra định dạng allowed_levels
        if (!preg_match('/^[0-9,]+$/', $allowedLevels)) {
            return redirect()->back()->withInput()->with('msgDanger', 'Invalid level format. Use comma separated numbers only.');
        }
        
        // Chuẩn hóa allowed_levels
        $levels = explode(',', $allowedLevels);
        $levels = array_map('trim', $levels);
        $levels = array_filter($levels);
        $levels = array_unique($levels);
        sort($levels);
        $cleanLevels = implode(',', $levels);
        
        // Kiểm tra game_code unique (chỉ khi thêm mới)
        if (!$isEdit) {
            $builder = $this->db->table('game_permissions');
            $existing = $builder->where('game_code', $gameCode)->get()->getRow();
            if ($existing) {
                return redirect()->back()->withInput()->with('msgDanger', 'Game code already exists.');
            }
        }
        
        // Dữ liệu để lưu
        $data = [
            'game_code' => $gameCode,
            'game_name' => $gameName,
            'allowed_levels' => $cleanLevels,
            'status' => $status ? 1 : 0,
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        
        try {
            $builder = $this->db->table('game_permissions');
            
            if ($isEdit) {
                // Kiểm tra game tồn tại trước khi update
                $existingGame = $builder->where('id', $id)->get()->getRow();
                if (!$existingGame) {
                    return redirect()->back()->withInput()->with('msgDanger', 'Game not found.');
                }
                
                $builder->where('id', $id)->update($data);
                $message = 'Game updated successfully!';
            } else {
                $data['created_at'] = date('Y-m-d H:i:s');
                $builder->insert($data);
                $message = 'Game added successfully!';
            }
            
            return redirect()->to('keys/manage-games')->with('msgSuccess', $message);
            
        } catch (\Exception $e) {
            // Log lỗi
            log_message('error', 'Save game error: ' . $e->getMessage());
            return redirect()->back()->withInput()->with('msgDanger', 'Error: ' . $e->getMessage());
        }
    }
    
    /**
     * Xóa game
     */
    public function delete_game($id = null)
    {
        $user = $this->user;
        
        if ($user->level != 1) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Access denied.'
            ]);
        }
        
        if (!$id) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Game ID is required.'
            ]);
        }
        
        // Kiểm tra xem game có đang được sử dụng không
        $gameBuilder = $this->db->table('game_permissions');
        $game = $gameBuilder->where('id', $id)->get()->getRow();
        
        if (!$game) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Game not found.'
            ]);
        }
        
        $keysBuilder = $this->db->table('keys_code');
        $keysCount = $keysBuilder->where('game', $game->game_code)->countAllResults();
        
        if ($keysCount > 0) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Cannot delete game. There are ' . $keysCount . ' keys using this game.'
            ]);
        }
        
        $builder = $this->db->table('game_permissions');
        
        try {
            $deleted = $builder->where('id', $id)->delete();
            
            if ($deleted) {
                return $this->response->setJSON([
                    'success' => true,
                    'message' => 'Game deleted successfully!'
                ]);
            } else {
                return $this->response->setJSON([
                    'success' => false,
                    'message' => 'Failed to delete game.'
                ]);
            }
        } catch (\Exception $e) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Database error: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * Toggle game status (Active/Inactive)
     */
    public function toggle_game_status($id = null)
    {
        $user = $this->user;
        
        if ($user->level != 1) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Access denied.'
            ]);
        }
        
        if (!$id) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Game ID is required.'
            ]);
        }
        
        $builder = $this->db->table('game_permissions');
        $game = $builder->where('id', $id)->get()->getRow();
        
        if (!$game) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Game not found.'
            ]);
        }
        
        $newStatus = $game->status == 1 ? 0 : 1;
        
        try {
            $builder->where('id', $id)->update(['status' => $newStatus]);
            
            return $this->response->setJSON([
                'success' => true,
                'message' => 'Game status updated.',
                'newStatus' => $newStatus,
                'statusText' => $newStatus == 1 ? 'Active' : 'Inactive'
            ]);
        } catch (\Exception $e) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Database error: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * API để lưu thay đổi level nhanh - SIMPLE VERSION
     */
    public function api_save_levels()
    {
        $user = $this->user;
        
        if ($user->level != 1) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Access denied.'
            ]);
        }
        
        $id = $this->request->getPost('id');
        $allowedLevels = $this->request->getPost('allowed_levels');
        
        if (!$id || !$allowedLevels) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Missing required data.'
            ]);
        }
        
        // Kiểm tra định dạng
        if (!preg_match('/^[0-9,]+$/', $allowedLevels)) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Invalid level format. Use comma separated numbers only.'
            ]);
        }
        
        // Chuẩn hóa allowed_levels
        $levels = explode(',', $allowedLevels);
        $levels = array_map('trim', $levels);
        $levels = array_filter($levels);
        $levels = array_unique($levels);
        sort($levels);
        $cleanLevels = implode(',', $levels);
        
        $builder = $this->db->table('game_permissions');
        $existing = $builder->where('id', $id)->get()->getRow();
        
        if (!$existing) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Game not found.'
            ]);
        }
        
        try {
            $builder->where('id', $id)->update([
                'allowed_levels' => $cleanLevels,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            
            return $this->response->setJSON([
                'success' => true,
                'message' => 'Levels updated successfully!',
                'data' => [
                    'id' => $id,
                    'allowed_levels' => $cleanLevels
                ]
            ]);
            
        } catch (\Exception $e) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Database error: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * Lấy thông tin game qua API
     */
    public function api_get_game($id = null)
    {
        $user = $this->user;
        
        if ($user->level != 1) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Access denied.'
            ]);
        }
        
        if (!$id) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Game ID is required.'
            ]);
        }
        
        $builder = $this->db->table('game_permissions');
        $game = $builder->where('id', $id)->get()->getRow();
        
        if (!$game) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Game not found.'
            ]);
        }
        
        return $this->response->setJSON([
            'success' => true,
            'data' => $game
        ]);
    }
    
    /**
     * Tìm kiếm game
     */
    public function search_games()
    {
        $user = $this->user;
        
        if ($user->level != 1) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Access denied.'
            ]);
        }
        
        $search = $this->request->getGet('search');
        $builder = $this->db->table('game_permissions');
        
        if (!empty($search)) {
            $builder->groupStart()
                    ->like('game_code', $search)
                    ->orLike('game_name', $search)
                    ->orLike('allowed_levels', $search)
                    ->groupEnd();
        }
        
        $games = $builder->orderBy('game_name', 'ASC')->get()->getResultArray();
        
        return $this->response->setJSON([
            'success' => true,
            'data' => $games
        ]);
    }
    
    /**
     * API cho DataTables (game management)
     */
    public function api_games()
    {
        $user = $this->user;
        
        if ($user->level != 1) {
            return $this->response->setJSON([
                'error' => 'Access denied'
            ]);
        }
        
        $request = service('request');
        $builder = $this->db->table('game_permissions');
        
        // Datatables server-side
        $draw = $request->getGet('draw');
        $start = $request->getGet('start');
        $length = $request->getGet('length');
        $searchValue = $request->getGet('search')['value'];
        
        // Tìm kiếm
        if ($searchValue) {
            $builder->groupStart()
                    ->like('game_code', $searchValue)
                    ->orLike('game_name', $searchValue)
                    ->orLike('allowed_levels', $searchValue)
                    ->groupEnd();
        }
        
        $totalCount = $builder->countAllResults(false);
        
        // Sắp xếp và phân trang
        $builder->orderBy('game_name', 'ASC')
                ->limit($length, $start);
        
        $data = $builder->get()->getResultArray();
        
        // Format data
        $result = [];
        foreach ($data as $row) {
            $result[] = [
                'id' => $row['id'],
                'game_code' => $row['game_code'],
                'game_name' => $row['game_name'],
                'allowed_levels' => $row['allowed_levels'],
                'status' => $row['status'] == 1 ? 
                    '<span class="badge badge-success">Active</span>' : 
                    '<span class="badge badge-danger">Inactive</span>',
                'created_at' => date('d/m/Y', strtotime($row['created_at'])),
                'actions' => '
                    <div class="btn-group">
                        <a href="' . site_url('keys/edit-game/' . $row['id']) . '" class="btn btn-sm btn-warning">
                            <i class="fas fa-edit"></i>
                        </a>
                        <button onclick="toggleGameStatus(' . $row['id'] . ')" class="btn btn-sm btn-' . ($row['status'] == 1 ? 'warning' : 'success') . '">
                            <i class="fas fa-' . ($row['status'] == 1 ? 'times' : 'check') . '"></i>
                        </button>
                        <button onclick="confirmDelete(' . $row['id'] . ')" class="btn btn-sm btn-danger">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                '
            ];
        }
        
        return $this->response->setJSON([
            'draw' => intval($draw),
            'recordsTotal' => $totalCount,
            'recordsFiltered' => $totalCount,
            'data' => $result
        ]);
    }
}