<?php

namespace App\Models;

use CodeIgniter\Model;
use \Hermawan\DataTables\DataTable;

class KeysModel extends Model
{
    protected $table      = 'keys_code'; // ✅ Bảng đang dùng
    protected $primaryKey = 'id_keys';

    // ✅ ĐÃ THÊM 'key_type' để sửa lỗi key VIP
    protected $allowedFields = [
        'game',
        'user_key',
        'duration',
        'expired_date',
        'max_devices',
        'devices',
        'status',
        'registrator',
        'key_type', // ✅ PHẢI CÓ DÒNG NÀY
        'fullname',
        'registrator_ip',
        'link_id',
        'created_at',
        'updated_at'
    ];

    protected $useTimestamps = true;

    public function getKeys($key = false, $where = 'user_key')
    {
        return $this->where($where, $key)
            ->get()
            ->getRowObject();
    }

    // ✅ Dùng để lấy thông tin thêm fullname từ users
    public function getKeysGame($where)
    {
        return $this->db->table('keys_code')
            ->select('keys_code.*, users.fullname')
            ->join('users', 'users.username = keys_code.registrator', 'left')
            ->where($where)
            ->get()
            ->getRow();
    }

    public function API_getKeys()
    {
        $connect = db_connect();
        $builder = $connect->table($this->table);

        $userModel = new UserModel();
        $user = $userModel->getUser();
        if ($user->level != 1) {
            $builder->where('registrator', $user->username);
        }

        $builder->select('CONCAT(keys_code.id_keys) as id, game, user_key, duration, CONCAT(keys_code.expired_date) as expired, max_devices, devices, status, registrator, key_type');

        return DataTable::of($builder)
            ->setSearchableColumns(['id_keys', 'game', 'user_key', 'duration', 'expired_date', 'max_devices', 'devices', 'registrator', 'key_type'])
            ->format('status', function ($value) {
                return ($value ? "Active" : "Inactive");
            })
            ->format('duration', function ($value) {
                return "$value Giờ";
            })
            ->format('devices', function ($value) {
                if ($value) {
                    $e = explode(',', reduce_multiples($value, ",", true));
                }
                return $value ? count($e) : 0;
            })
            ->format('expired', function ($value) {
                $time = new \CodeIgniter\I18n\Time;
                return $value ? $time::parse($value)->toLocalizedString('d MMM yy - H:m') : '';
            })
            ->format('key_type', function ($value) {
                return strtoupper($value); // hiển thị VIP / REGULAR
            })
            ->toJson(true);
    }
}