<?php
if (!class_exists('crm_hardlock')) require_once("common_cadline_libraries/crm_hardlock.class.php");

$param          = isset($_GET['param']) ? $_GET['param'] : '';
$session        = isset($_GET['session']) ? $_GET['session'] : '';
$product        = isset($_GET['prod']) ? $_GET['prod'] : '';
$version        = isset($_GET['ver']) ? $_GET['ver'] : '';
$ctrID          = isset($_GET['cnt']) ? $_GET['cnt'] : '';
$decodedSession = base64_decode($session);
$verID          = crm_hardlock::getVerIDFrom8and9($version);

$privatekey     = Webform::GetWebformPrivateKey();
$decoded_param  = Webform::decode($privatekey, $decodedSession, $param);
$decoded_param  = "?{$decoded_param}";

if (crm_hardlock::isEmergencyServer($_GET['secondary'])) {
    $data = "<GetSerial>
        <Serials>0</Serials>
        <Error>invalid_token</Error>
    </GetSerial>";

    $result = 'result_ok';

    $message = $button = '';

    $param = Webform::encode($privatekey, $decodedSession, $data);

    Webform::SetWebformResult($decodedSession, $result, $param, $message, $button);

    $resultXml .= '<' . '?' . 'xml version="1.0"' . '?' . '><WebFormResult>';
    $resultXml .= '?session=' . $session . '&' . $result . '=' . $param . '&';
    $resultXml .= '</WebFormResult>';

    header('Content-Type: text/xml; charset=utf-8');
    header('Content-Disposition: inline; filename=response.xml');

    echo $resultXml;
    return;
}

$generatetrial  = Webform::get_valueFromStringUrl($decoded_param, "generatetrial");
$installDate    = Webform::get_valueFromStringUrl($decoded_param, "trialinstalldate");
$tokenID        = Webform::get_valueFromStringUrl($decoded_param, "tokenid");
$specEdition    = Webform::get_valueFromStringUrl($decoded_param, "se");
$npid           = Webform::get_valueFromStringUrl($decoded_param, "npid");
$seatID         = Webform::get_valueFromStringUrl($decoded_param, "seatid");
$build          = Webform::get_valueFromStringUrl($decoded_param, "build");
$currentpwd     = Webform::get_valueFromStringUrl($decoded_param, "currentpassword");
$userID         = crm_hardlock::GetUserIdFromToken($tokenID);

if ($userID) {
    $programs   = crm_hardlock::GetAllProgramsFromUser($userID, $product, $verID, $specEdition);
    $prg_count  = 0;
    $serials    = array();

    foreach ($programs as $program) {
        if (!array_key_exists($program['prPass'], $serials)) { // Ha nincs meg a listaban, akkor megnezi, hogy floating-e az adott licenc
            $hlNum = substr($program['prPass'], 0, 6);

            $query = "SELECT * FROM cl_hlusers.hardlock WHERE hlNum = ?";
            Database::getInstance()->query($query, array('s', $hlNum));
            $key = Database::getInstance()->fetchNext();

            $isFloating = $key['isFloating'] == 1 && $program['prVerID'] >= 23;

            if ($isFloating && $program['prVerID'] == 23 && $build < 255)
                $isFloating = false;

            $serials[$program['prPass']] = $isFloating;
            $prg_count++;
        } elseif (array_key_exists($program['prPass'], $serials) && !$serials[$program['prPass']]) {
            // Ha benne van a listaban es nem floating a licenc, noveljuk a kulonallo licencek szamat
            $prg_count++;
        }
    }

    if ($generatetrial == 'true') {
        $errorMsg   = '';
        $needTrial  = true;
        $password   = '';

        if ($prg_count > 1) { // Ha tobb, mint 1 licence van, nem kaphat
            $needTrial = false;
        } elseif ($prg_count == 1) { // Ha van trialja, akkor kesobb visszaadja
            if (substr($programs[0]['prPass'], 0, 2) != '96') // 1 programja van, de az is kereskedelmi, nem kaphat
                $needTrial = false;
        }

        if ($needTrial) {
            if ($prg_count == 1) {
                $password = $programs[0]['prPass'];
            } else {
                $password = crm_hardlock::GenerateTrial($userID, $product, $verID, '', $installDate, $ctrID, $specEdition, $npid, $errorMsg);

                if ($password != '') {
                    $prg_count++;

                    if ($userID < 0) { // Ha custom login van, akkor a partnernek uzenjuk meg, hogy letrejott 1 uj sorozatszam es hogy melyik userre
                        $customUser = crm_hardlock::GetCustomUser(abs($userID));

                        $query = "SELECT * FROM cl_hlusers.custom_login_urls WHERE id = ? AND urls.enabled = ? AND process = ? LIMIT 1";
                        Database::getInstance()->query($query, array('sis', $customUser['custom_login_id'], 1, 'login'));
                        $urlDB = Database::getInstance()->fetchNext();

                        if (!empty($urlDB) && $urlDB['trial_result_url'] != '') {
                            $url = $urlDB['trial_result_url'];

                            $jsonUser           = new stdClass();
                            $jsonUser->serial   = $customUser['serial'];
                            $jsonUser->email    = $customUser['email'];
                            $jsonUser->crmID    = $customUser['custom_id'];

                            $jsonString     = json_encode($jsonUser);
                            $encodedJson    = base64_encode($jsonString); // base64 encode-olt JSON

                            $postData = [
                                'data' => $encodedJson
                            ];

                            $cURLConnection = curl_init($url);
                            curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $postData);
                            $result = curl_exec($cURLConnection);

                            $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

                            $msg = "Url: {$actual_link} || Data: {$jsonString}";

                            crm_hardlock::AddToDebugTable($msg, 'custom_login_test');
                        }
                    } else {
                        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`users` WHERE nUserID = ?";
                        Database::getInstance()->query($query, array('i', $userID));
                        $user = Database::getInstance()->fetchNext();

                        if (!empty($user) && $user['distID_by_user'] > 0) {
                            $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`distributors` WHERE id = ?";
                            Database::getInstance()->query($query, array('i', $user['distID_by_user']));
                            $dealer = Database::getInstance()->fetchNext();

                            if ($dealer['email'] != '') {
                                $subject = 'ARCHLine.XP Trial download - local representative to contact';
                                $headers = "Content-Type: text/html; charset=utf-8\r\n";
                                $headers .= 'Bcc: office@cadline.hu, mate.nagy@cadline.hu' . "\r\n";

                                $message = "Dear Distributor, <br/><br/>

                                This message is automatically generated because we have received an ARCHLine.XP Trial download with the following user details: <br/><br/>
                                
                                <b>Name:</b> " . $user['strName'] . " <br/>
                                <b>Email:</b> " . $user['strEMail'] . " <br/>
                                <b>Serial number:</b> " . $password . " <br/><br/>

                                During installation, the user selected you as the local representative to contact. <br/>
                                " . $dealer['name'] . "<br/><br/>
                                
                                Best regards, <br/><br/>

                                <a href='mailto:partnering@archlinexp.com'>partnering@archlinexp.com</a> <br/>
                                <a href='https://www.archlinexp.com/'>www.archlinexp.com</a> <br/>
                                CadLine Ltd. <br/>
                                1037 Budapest, Montevideo utca 3/b <br/>

                                Hungary.";

                                mail($dealer['email'], $subject, $message, $headers);

                                $dealer_url = "<br/>";

                                if ($dealer['webpage'] != '') {
                                    $dealer_url = "<b>Webpage:</b> <a href='" . $dealer['webpage'] . "'>" . $dealer['webpage'] . "</a> <br/><br/>";
                                }

                                $subject = 'ARCHLine.XP Trial download - Your inquiry has been received';
                                $headers = "Content-Type: text/html; charset=utf-8\r\n";

                                $message = "Hello " . $user['strName'] . ", <br/><br/>

                                This message is an automatic reply to acknowledge your choice to find local representative. <br/><br/>
                                
                                Representative's details: <br/>
                                <b>Name:</b> " . $dealer['name'] . " <br/>
                                <b>Email:</b> " . $dealer['email'] . " <br/>
                                " . $dealer_url . "

                                Your name and email address is being redirected to the sales reps who will shortly get in touch with you to guide you through our product line.<br/>
                                In the meantime, please take a look at the knowledge base <a href='https://help.archlinexp.com/hc/en-us'>help.archinexp.com</a> to learn more about our desktop app.<br/>
                                We hope you'll enjoy your experience with us! <br/><br/>
                                
                                Best regards, <br/><br/>

                                <a href='mailto:partnering@archlinexp.com'>partnering@archlinexp.com</a> <br/>
                                <a href='https://www.archlinexp.com/'>www.archlinexp.com</a> <br/>
                                CadLine Ltd. <br/>
                                1037 Budapest, Montevideo utca 3/b <br/>

                                Hungary.";

                                mail($user['strEMail'], $subject, $message, $headers);
                            }
                        }

                        if (!empty($user) && ($user['distID_by_user'] <= 0 || $user['distID_by_user'] == '' || $user['distID_by_user'] == null)) {
                            $subjectOffice = 'ARCHLine.XP Trial download - Nem választott viszonteladót';
                            $headersOffice = "Content-Type: text/html; charset=utf-8\r\n";
                            $headersOffice .= 'Cc: mate.nagy@cadline.hu' . "\r\n";

                            $messageOffice = "Az alábbi felhasználó igényelt bónusz trialt, viszont nem választott viszonteladót / The following user requested a bonus trial but did not select a reseller: <br/><br/>
                                
                                <b>Name:</b> " . $user['strName'] . " <br/>
                                <b>Email:</b> " . $user['strEMail'] . " <br/>
                                <b>Serial number:</b> " . $password . " <br/><br/>";

                            mail('office@cadline.hu', $subjectOffice, $messageOffice, $headersOffice);
                        }
                    }
                }
            }
        }

        $data = Webform::GenerateSerialXML($prg_count, $password, $errorMsg);
    } else { // Nem generate trial
        if ($prg_count == 1) {
            $password = $programs[0]['prPass'];

            $data = "<GetSerial>
                <Serials>{$prg_count}</Serials>
                <Serial>{$password}</Serial>
            </GetSerial>";
        } else {
            // ha 2 programja van, akkor van-e trial-ja, ha van, akkor a normál licensz-t vissza kell adni
            if ($prg_count == 2) {
                $trialIndex = -1;
                $i = 0;

                foreach ($programs as $program) {
                    if (substr($program['prPass'], 0, 2) == '96')
                        $trialIndex = $i;

                    $i++;
                }

                if ($trialIndex == -1) {
                    $data = "<GetSerial>
                        <Serials>" . $prg_count . "</Serials>
                    </GetSerial>";
                } else {
                    if ($trialIndex == 1)
                        $trialIndex = 0;
                    else
                        $trialIndex = 1;

                    $data = "<GetSerial>
                        <Serials>1</Serials>
                        <Serial>" . $programs[$trialIndex]['prPass'] . "</Serial>
                    </GetSerial>";
                }
            } else {
                // Ha a currentpwd megvan adva, akkor a funkcio az, hogy keresse meg, hogy a hasznalt licencek kozul megvan-e az aktualis
                // ha nincs, akkor nem szabad visszaadni, hanem azt, hogy nincs licenc. Ebben az esetben az ARCHLine eltavolitja a licencet.
                if ($currentpwd != '' && !array_key_exists($currentpwd, $serials)) {
                    $data = "<GetSerial>
                        <Serials>0</Serials>
                    </GetSerial>";
                } else {
                    $data = "<GetSerial>
                        <Serials>" . $prg_count . "</Serials>
                    </GetSerial>";
                }
            }
        }
    }
} else {
    $data = "<GetSerial>
        <Error>invalid_token</Error>
    </GetSerial>";
}

$result = 'result_ok';

$param = Webform::encode($privatekey, $decodedSession, $data);

Webform::SetWebformResult($decodedSession, $result, $param, $message, $button);

$resultXml .= '<' . '?' . 'xml version="1.0"' . '?' . '><WebFormResult>';
$resultXml .= '?session=' . $session . '&' . $result . '=' . $param . '&';
$resultXml .= '</WebFormResult>';

header('Content-Type: text/xml; charset=utf-8');
header('Content-Disposition: inline; filename=response.xml');

echo $resultXml;
