<?php

class Mapi extends Model
{
    function __construct()
    {
        parent::__construct();
    }

    function createNonprofit($name, $email, $expire, $ctrID)
    {
        $response = new stdClass();

        $checkCallback = $this->db->query("SELECT COUNT(id) AS count FROM cl_hlusers.api_callbacks c WHERE c.function = 'generateNonProfit' AND ctrID = {$ctrID}")->row();
        if ($checkCallback->count >= 50) {
            $response->message = 'Limit reached.';
            return $response;
        }

        if ($name == '') {
            $response->message = 'Missing argument: name.';
            return $response;
        }

        if ($email == '') {
            $response->message = 'Missing argument: email.';
            return $response;
        }

        $expireDate = '';

        if ($expire == '') {
            $expireDate = date('Y-m-d', strtotime(date('Y-m-d') . ' + 90 days'));
        } else {
            $customDate = date_create($expire);
            $expireDate = date_format($customDate, "Y-m-d");

            if ($expireDate > date('Y-m-d', strtotime(date('Y-m-d') . ' + 90 days')))
                $expireDate = date('Y-m-d', strtotime(date('Y-m-d') . ' + 90 days'));
        }

        $emptyKey = $this->db->query("SELECT * FROM cl_hlusers.hardlock WHERE hlNum LIKE '99%' AND hlStat = 0 ORDER BY hlNum")->row();

        if (!empty($emptyKey))
            $hlNum = $emptyKey->hlNum;
        else
            $hlNum = $this->tryToAlloc();

        $version = $this->getVersions();
        $serial = $this->createPassword($hlNum, $version->verCode, 0, 8);

        $this->createLicense(8, $version->verID, 0, $serial, $expireDate, 5, $ctrID);

        $retrievedUser = $this->db->query("SELECT nUserID FROM cl_hlusers.u_emails WHERE email = '{$email}'")->row();

        if (empty($retrievedUser)) {
            $userID = $this->insertUser($ctrID, 4, 2, $name, $email);
        } else {
            $userID = (int)$retrievedUser->nUserID;
        }

        $this->updateHardlock($hlNum, $userID, $ctrID);

        $response = new stdClass();
        $response->message = 'Success.';
        $response->serial = $serial;

        return $response;
    }

    private function getVersions()
    {
        return $this->db->query("SELECT * FROM cl_hlusers.p_versions WHERE verID = 22")->row();
    }

    private function createPassword($key, $verCode, $lan, $type)
    {
        $command    = PATH_CODEGEN . " -Password " . $key . $verCode . $lan . $type;
        $ph         = popen($command, "r") or die("A 'codegen' paranccsal nem veheto fel kapcsolat");
        $serial     = fgets($ph, 1024);
        pclose($ph);

        return $serial;
    }

    private function updateHardlock($key, $userID, $ctrID)
    {
        $hlDateIssue  = date('Y-m-d');
        $hlTime       = date("Y-m-d H:i:s");

        $updateQuery = "UPDATE cl_hlusers.hardlock
            SET hlLan = 0, hlStat = 1, hlDateIssue = '{$hlDateIssue}', hlUser = {$userID}, hlManID = 36, hlCtrID = '{$ctrID}',
            old_db = 'clusers_eng', hlTime = '{$hlTime}', product_id = 1, isFloating = 0
            WHERE hlNum = '{$key}'";
        $this->db->query($updateQuery);
    }

    private function createLicense($type, $version, $prLan, $serial, $expire, $contact, $ctrID)
    {
        $license                        = new stdClass();
        $license->prTypeID              = $type;
        $license->prVerID               = $version;
        $license->prLan                 = $prLan;
        $license->prPass                = $serial;
        $license->prSellDate            = date("Y-m-d H:i:s");
        $license->prActDate             = date("Y-m-d H:i:s");
        $license->prFizetve             = $expire;
        $license->prTime                = date("Y-m-d H:i:s");
        $license->prLastMod             = date("Y-m-d H:i:s");
        $license->prContact             = $contact;
        $license->prHlNum               = substr($serial, 0, 6);
        $license->prManID               = 36;
        $license->prCtrID               = $ctrID;
        $license->prStat                = 0;
        $license->prActCode             = '';
        $license->old_db                = 'clusers_eng';
        $license->old_prID              = 0;

        $this->db->insert("cl_hlusers.h_programs", $license);
    }

    private function tryToAlloc($min = 990001, $max = 999999)
    {
        $ret = 0;
        if ((int)$min == 0 || (int)$max == 0) return $ret;

        $query = "SELECT LEFT(hlNum, 6) AS hlNum FROM cl_hlusers.hardlock WHERE hlNum >= " . (int)$min . " AND hlNum < " . (int)$max . " ORDER BY hlNum;";
        $res = $this->db->query($query)->result();

        if (count($res)) {
            $keszlet = range($min, $max);
            foreach ($res as $r) $kulcsok[] = $r->hlNum;

            $diff = array_diff($keszlet, $kulcsok);
            reset($diff);
            $ret = current($diff);
        }
        return $ret;
    }

    private function getDistributor($ctrID)
    {
        $distID = 0;

        $distributor = $this->db->query("SELECT id FROM cl_hlusers.distributors WHERE ctrID = '{$ctrID}'")->row();

        if (!empty($distributor))
            $distID = $distributor->id;

        return $distID;
    }

    private function insertUser($ctrID, $status, $userType, $name, $email)
    {
        $distID = $this->getDistributor($ctrID);

        $user               = new stdClass();
        $user->strName      = $name;
        $user->nManagerID   = 36;
        $user->nSchoolID    = 0;
        $user->deleted      = 0;
        $user->old_db       = 'clusers_eng';
        $user->bNewsletter  = 'N';
        $user->strEMail     = $email;
        $user->strCurrency  = substr($ctrID, 0, 2) == '11' ? 'USD' : 'EUR';
        $user->nCtrID       = substr($ctrID, 0, 2);
        $user->nUserStatus  = $status;
        $user->nDistID      = $distID;
        $user->nUserType    = $userType;

        $this->db->insert("cl_hlusers.users", $user);
        $nUserID = $this->db->insert_id();

        $history                = new stdClass();
        $history->nUserID       = $nUserID;
        $history->nTopicID      = 382;
        $history->dateEvent     = date('Y-m-d');
        $history->strPlace      = 'Weborder';
        $history->strInfo       = 'Weborderen regisztrált';
        $history->nManagerID    = 36;
        $history->insertDate    = date('Y-m-d H:i:s');

        $this->db->insert("cl_hlusers.u_history", $history);

        $u_email                = new stdClass();
        $u_email->email         = $email;
        $u_email->nUserID       = $nUserID;
        $u_email->default       = 1;
        $u_email->active        = 1;
        $u_email->deleted       = 0;
        $u_email->newsletter    = 1;

        $this->db->insert("cl_hlusers.u_emails", $u_email);

        return $nUserID;
    }

    function checkToken($auth)
    {
        $authorization  = "Authorization: " . $auth;

        $headers = [
            'Accept: application/json',
            $authorization,
        ];

        $ch = curl_init('https://partners.staging.cadline.hu/api/checkToken');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

        $response = curl_exec($ch);

        curl_close($ch);

        $result = json_decode($response);

        $this->insertApiCallback('checkToken', $response, $result->ctrID);

        return $result;
    }

    function insertApiCallback($function, $response, $ctrID)
    {
        $apiCallback            = new stdClass();
        $apiCallback->function  = $function;
        $apiCallback->date      = date('Y-m-d H:i:s');
        $apiCallback->response  = $response;
        $apiCallback->ip        = $_SERVER['REMOTE_ADDR'];
        $apiCallback->ctrID     = $ctrID;


        $this->db->insert("cl_hlusers.api_callbacks", $apiCallback);
    }
}
