<?php

namespace App\Controllers;

use App\Models\KeysModel;

class Connect extends BaseController
{
    protected $model, $game, $uKey, $sDev;

    public function __construct()
    {
        include('conn.php');
//=================================================
        $sql1 ="select * from onoff where id=1";
        $result1 = mysqli_query($conn, $sql1);
        $userDetails1 = mysqli_fetch_assoc($result1);
//=================================================
        $this->model = new KeysModel();
//=================================================
        if($userDetails1['status'] == 'on')
        {
            $this->maintenance = true;
        } else {
            $this->maintenance = false;
        }
//=================================================
       $this->staticWords = "DIAMONDYT";
    }

    public function index()
    {
        if ($this->request->getPost()) {
            return $this->index_post();
        } else {
            $nata = [
                "web_info" => [
                    "_client" => BASE_NAME,
                    "license" => "Qp5KSGTquetnUkjX6UVBAURH8hTkZuLM",
                    "version" => "1.0.0",
                ],
                "web__dev" => [
                    "author" => "@",
                    "telegram" => "https://t.me/"
                           ],
            ];
            
            return "<h1><strong><center><font size='10' color='red' face='arial'><marquee direction='right' scrollamount='15'>WANT OWN KURO PANEL?<br> DM HERE - </marquee></font></center></strong></h1>";
            // $this->response->setJSON($nata);
        }
    }

    public function index_post()
    {
        $isMT = $this->maintenance;
        $game = $this->request->getPost('game');
        $uKey = $this->request->getPost('user_key');
        $sDev = $this->request->getPost('serial');

        $form_rules = [
            'game' => 'required|alpha_dash',
            'user_key' => 'required|min_length[1]|max_length[36]',
            'serial' => 'required|alpha_dash'
        ];

        if (!$this->validate($form_rules)) {
            $data = [
                'status' => false,
                'reason' => "Bad Parameter",
            ];
            return $this->response->setJSON($data);
        }

        if ($isMT) {
            include('conn.php');
            $sql1 ="select * from onoff where id=1";
            $result1 = mysqli_query($conn, $sql1);
            $userDetails1 = mysqli_fetch_assoc($result1);
            
            $data = [
                'status' => false,
                'reason' => $userDetails1['myinput']
            ];
            return $this->response->setJSON($data);
        }

        if (!$game or !$uKey or !$sDev) {
            $data = [
                'status' => false,
                'reason' => 'INVALID PARAMETER'
            ];
            return $this->response->setJSON($data);
        }

        $time = new \CodeIgniter\I18n\Time;
        $model = $this->model;
        $findKey = $model->getKeysGame(['user_key' => $uKey, 'game' => $game]);

        if (!$findKey) {
            $data = [
                'status' => false,
                'reason' => 'USER OR GAME NOT REGISTERED'
            ];
            return $this->response->setJSON($data);
        }

        if ($findKey->status != 1) {
            $data = [
                'status' => false,
                'reason' => 'USER BLOCKED'
            ];
            return $this->response->setJSON($data);
        }

        $id_keys = $findKey->id_keys;
        $duration = $findKey->duration;
        $expired = $findKey->expired_date;
        $max_dev = $findKey->max_devices;
        $devices = $findKey->devices;

        function checkDevicesAdd($serial, $devices, $max_dev)
        {
            $lsDevice = explode(",", $devices);
            $cDevices = isset($devices) ? count($lsDevice) : 0;
            $serialOn = in_array($serial, $lsDevice);

            if ($serialOn) {
                return true;
            } else {
                if ($cDevices < $max_dev) {
                    array_push($lsDevice, $serial);
                    $setDevice = reduce_multiples(implode(",", $lsDevice), ",", true);
                    return ['devices' => $setDevice];
                } else {
                    return false;
                }
            }
        }

        // Xử lý thời gian hết hạn
        $current_time = $time->now();
        
        if (!$expired) {
            $setExpired = $time::now()->addHours($duration);
            $model->update($id_keys, ['expired_date' => $setExpired->toDateTimeString()]);
            $expired = $setExpired->toDateTimeString();
        }

        // Chuyển đổi expired string thành đối tượng Time để so sánh
        $expired_time = new \CodeIgniter\I18n\Time($expired);
        
        if ($current_time->isAfter($expired_time)) {
            $data = [
                'status' => false,
                'reason' => 'EXPIRED KEY'
            ];
            return $this->response->setJSON($data);
        }

        include('conn.php');
        $sql2 = "select * from modname where id=1";
        $result2 = mysqli_query($conn, $sql2);
        $userDetails2 = mysqli_fetch_assoc($result2);
        
        $sql3 = "select * from _ftext where id=1";
        $result3 = mysqli_query($conn, $sql3);
        $userDetails3 = mysqli_fetch_assoc($result3);
        
        $sql4 = "SELECT expired_date FROM keys_code WHERE user_key='$uKey'";
        $result4 = mysqli_query($conn, $sql4);
        $userDetails4 = mysqli_fetch_assoc($result4);

        $sql = "SELECT * FROM Feature WHERE id=1";
        $result = mysqli_query($conn, $sql);
        $ModFeatureStatus = mysqli_fetch_assoc($result);

        $rngcnt = $time->getTimestamp();

        $devicesAdd = checkDevicesAdd($sDev, $devices, $max_dev);
        if (!$devicesAdd) {
            $data = [
                'status' => false,
                'reason' => 'MAX DEVICE REACHED'
            ];
            return $this->response->setJSON($data);
        }

        if (is_array($devicesAdd)) {
            $model->update($id_keys, $devicesAdd);
        }

        $real = "$game-$uKey-$sDev-$this->staticWords";
        
        // Xử lý thời gian hết hạn - chuyển đổi sang timestamp
        $expiry_timestamp = $expired_time->getTimestamp();
        
        // Chuẩn bị dữ liệu trả về
        $responseData = [
            'status' => true,
            'data' => [
                'real' => $real,
                'token' => md5($real),
                'modname' => $userDetails2['modname'] ?? '',
                'mod_status' => $userDetails3['_status'] ?? '',
                'credit' => $userDetails3['_ftext'] ?? '',
                'ESP' => $ModFeatureStatus['ESP'] ?? 'off',
                'Item' => $ModFeatureStatus['Item'] ?? 'off',
                'AIM' => $ModFeatureStatus['AIM'] ?? 'off',
                'SilentAim' => $ModFeatureStatus['SilentAim'] ?? 'off',
                'BulletTrack' => $ModFeatureStatus['BulletTrack'] ?? 'off',
                'Floating' => $ModFeatureStatus['Floating'] ?? 'off',
                'Memory' => $ModFeatureStatus['Memory'] ?? 'off',
                'Setting' => $ModFeatureStatus['Setting'] ?? 'off',
                'expired_date' => $userDetails4['expired_date'] ?? $expired,
                'EXP' => $expired,
                'ts' => $expired,
                'exdate' => $expired,
                'device' => $max_dev,
                'rng' => $rngcnt
            ],
        ];

        return $this->response->setJSON($responseData);
    }
}