<?php

namespace App\System\Task;
use App\System\Model\SettingModel;
use App\System\Vendor\beUpdate;
use \Exception;

class LisanceCheckTask {
    public function run_task($task){
        global $be;
        $settings = $be->settings;
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,"https://mp.diyocp.com/diyocp-api-user/get-info");
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query([
            "cid" => $settings["system_id"],
            "ctoken" => $settings["system_token"],
            "secret" => $settings["system_secret"]
        ]));
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $response = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($response,true);
        if(!$data["status"]){
            throw new Exception("Veri çözümlenirken bir hata oluştu: ".$data["message"]);
        }
        $userproduct = $data["userproduct"];
        $be->settings["system_data"]["product"] = [
            "upid" => (int)$userproduct["upid"],
            "updata" => $userproduct["updata"],
            "upprice" => $userproduct["upprice"],
            "upetime" => (int)$userproduct["upetime"],
            "cicon" => $data["currency"]["cicon"]
        ];
        $mainfile = BE_APPPATH."resources/cache/version.json";
        if(file_exists($mainfile)){
            $system = file_get_contents($mainfile);
            $system = json_decode($system,true);
            $build = $system["build"] ?? 0;
            $update = beUpdate::beCheckUpdate();
            if(!$update["status"]){
                SettingModel::beUpdate(["svalue" => json_encode($be->settings["system_data"],JSON_UNESCAPED_UNICODE)])->beWhere("scode","system_data")->beExecute();
                throw new Exception("Güncelleme sistemine ulaşılamıyor!");
            }
            if($update["process"]){
                if($update["update"]["ustatus"] == 2 && $build != $update["update"]["ubuild"]){
                    $be->settings["system_data"]["update"] = [
                        "build" => (int)$update["update"]["ubuild"],
                        "name" => $update["update"]["uname"]
                    ];
                }
            }
            else{
                $be->settings["system_data"]["update"] = [];
            }
        }
        SettingModel::beUpdate(["svalue" => json_encode($be->settings["system_data"],JSON_UNESCAPED_UNICODE)])->beWhere("scode","system_data")->beExecute();
    }
}

?>