<?php
error_reporting(E_ALL);

require 'hivasok.php';
require 'autoload.php';

use \SzamlaAgent\SzamlaAgentAPI;
use \SzamlaAgent\Buyer;
use \SzamlaAgent\Document\Invoice\Invoice;
use \SzamlaAgent\Item\InvoiceItem;
use \SzamlaAgent\Ledger\InvoiceItemLedger;
use \SzamlaAgent\Log;
use \SzamlaAgent\Currency;
use \SzamlaAgent\Language;
use \SzamlaAgent\Seller;
use \SzamlaAgent\TaxPayer;

use \SzamlaAgent\CreditNote\InvoiceCreditNote;
use \SzamlaAgent\Document\Document;
use \SzamlaAgent\SzamlaAgentUtil;

try {
    $agent = SzamlaAgentAPI::create('t6c8vvb8kuiae4xjuhtkf3zahv5qcpdknz4hzcxn7v');

    $invoice = new Invoice(Invoice::INVOICE_TYPE_P_INVOICE);

    $invoice->setBuyer(new Buyer('Nagy Máté', '6750', 'Algyő', 'Szüret utca 44.'));

    $item = new InvoiceItem("Test", 10000.0, 1, 'db', 'EU');
    $item->setNetPrice(1);
    $item->setVatAmount(0);
    $item->setGrossAmount(1);

    $invoice->addItem($item);

    $creditNote = new InvoiceCreditNote(SzamlaAgentUtil::getTodayStr(), 10000.0, Document::PAYMENT_METHOD_BANKCARD, 'TESZT');
    // Jóváírás hozzáadása a számlához
    $invoice->addCreditNote($creditNote);

    print_r($invoice);
    die();

    $result = $agent->generateInvoice($invoice);
    if ($result->isSuccess()) {
        echo 'A számla sikeresen elkészült. Számlaszám: ' . $result->getDocumentNumber();
        var_dump($result->getDataObj());
    }
} catch (\Exception $e) {
    $agent->logError($e->getMessage());
}

die();

$config['db_host'] = 'localhost';
$config['db_user'] = 'cadline';
$config['db_pass'] = 'Shea6hoo';
$config['db_name'] = 'cl_hlusers';

$msh = new hivasok();
$msh->init($config['db_host'], $config['db_name'], $config['db_user'], $config['db_pass']);
$conn = new mysqli($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);

$ip         = $_SERVER['REMOTE_ADDR'];
$eredmeny   = [];
$sesion_id  = bin2hex(openssl_random_pseudo_bytes(10));

if (mysqli_real_escape_string($conn, $_GET['bizt']) !=  mysqli_real_escape_string($conn, $_GET['biztonsagi']) ||  mysqli_real_escape_string($conn, $_GET['confirm']) != "Y") {
    $eredmeny["hiba"] = "Your security answer was wrong or you forgot the confirm checkbox!
        <br /><br />
        <a href='javascript:location.reload()'>Continue</a>.";
} else {
    $query = "SELECT ip, COUNT(ip) as szam FROM o_orders WHERE ip = '".$ip."' AND DATE=CURDATE()";
    $msh->query($query);
    $limit = $msh->fetchNext();

    $msh->query("SELECT `limit` FROM `o_products` limit 1");
    $max_limit = $msh->fetchNext();

    if ($limit['szam'] < $max_limit['limit']) { // Napi limit
        define('PATH_CODEGEN', "/usr/local/sbin/codegen");

        $kategoria  = mysqli_real_escape_string($conn, $_GET['kategoria']); // Lehet: perp, upgrade, akcio, nonprofit, hardlock, module
        $hl_prot    = mysqli_real_escape_string($conn, $_GET['hl_prot']);
        $program    = mysqli_real_escape_string($conn, $_GET['prg']);
        $cntry      = mysqli_real_escape_string($conn, $_GET['cntry']);
        $ma         = date("Y-m-d");
        $email      = mysqli_real_escape_string($conn, $_GET['email']);
        $u_name     = mysqli_real_escape_string($conn, $_GET['name']);
        $info       = mysqli_real_escape_string($conn, $_GET['info']);

        $query = "SELECT DISTINCT `email`, `sub_email` FROM `o_products` WHERE `lang` = '{$cntry}'";
        $msh->query($query);
        $kapcsolat = $msh->fetchNext();

        if ($kapcsolat['email'] == "") {
            $eredmeny["hiba"] = "Access denied
                <br /><br />
                <a href='javascript:location.reload()'>Continue</a>.";
            echo json_encode($eredmeny);
            return false;
        }

        $osszeg = "SELECT * FROM `o_products` WHERE `termek` = '".$program."' AND `lang` = '".$cntry."' AND `kategoria` = '".$kategoria."'";
        $msh->query($osszeg);
        $ertek2 = $msh->fetchNext();
        $price = $cntry == 11 ? $ertek2["usd"] : $ertek2["euro"];
        $akcio = $ertek2["akcio"];

        if ($akcio != '' && $akcio != null && date('Y-m-d') <= $ertek2['ackio_date']) $price = $akcio;

        // TODO: spanyoloknak nem mukodik
        /*if ($ertek2["is_invoice"] == 0) {
            $eredmeny['hiba'] = "You have invoice(s) more than 14 days overdue.
                <br/>
                The web-order system is temporary not available for attempts to create a new order.
                <br/>
                Please advise as to whether payment has been scheduled.
                <br/>
                If you require any further information from us, please contact us at office@cadline.hu
                <br /><br />
                <a href='javascript:location.reload()'>Continue</a>.";
            echo json_encode($eredmeny);
            return false;
        }*/

        $isInvoice      = false;
        $tax            = TaxPayer::TAXPAYER_HAS_TAXNUMBER;
        $curr           = "EUR";
        $cur            = Currency::CURRENCY_EUR;
        $lang           = Language::LANGUAGE_EN;
        $prod_prefix    = "EU";
        $inv_prefix     = "EUR";
        switch ($cntry)
        {
            case '39': // Olaszorszag
                $lang = Language::LANGUAGE_IT;
                break;
            case '43': // Ausztria
                $lang = Language::LANGUAGE_DE;
                break;
            case '49': // Nemetorszag
                $lang = Language::LANGUAGE_DE;
                break;
            case '38': // Horvatorszag
                $lang       = Language::LANGUAGE_HR;
                break;
            case '33': // Franciaorszag
                $lang       = Language::LANGUAGE_FR;
                break;
            case '42': // Csehorszag
                $lang       = Language::LANGUAGE_CZ;
                break;
            case '48': // Lengyelorszag
                $lang       = Language::LANGUAGE_PL;
                break;
            case '34': // Spanyolorszag
                $lang       = Language::LANGUAGE_ES;
                break;
            case '37': // TESZT
                $tax        = TaxPayer::TAXPAYER_NO_TAXNUMBER;
                $isInvoice  = true;
                break;
            case '82':  //Korea
                $prod_prefix    = "Non-EU";
                break;
            case '61':  //Ausztralia
                $prod_prefix    = "Non-EU";
                break;
            case '88':  //Tajvan
                $prod_prefix = "Non-EU";
                break;
            case '44':  //UK
                $prod_prefix = "Non-EU";
                break;
            case '84':  //Vietnam
                $prod_prefix = "Non-EU";
                break;
            case '52':  //Mexiko
                $prod_prefix = "Non-EU";
                break;
            case '60':  //Malajzia
                $prod_prefix = "Non-EU";
                break;
            case '30': //Gorogorszag
                break;
            case '51': //Portugalia
                break;
            case '11': // USA
                $curr           = "USD";
                $cur            = Currency::CURRENCY_USD;
                $prod_prefix    = "Non-EU";
                $inv_prefix     = "USD";
                break;
            case '71': // Lettorszag
                break;
            default: // Minden mas
                $tax = TaxPayer::TAXPAYER_NO_TAXNUMBER;
                break;
        }

        if (mysqli_real_escape_string($conn, $_GET['user']) == "ismeretlen") {
            if ($kategoria == 'nonp') $status = '4';
            else $status = '11';

            $query = "SELECT id FROM distributors WHERE ctrID = {$cntry}";
            $msh->query($query);
            $dist = $msh->fetchNext();

            if (!empty($dist)) $distID = $dist['id'];
            else $distID = 0;

            $insert = $msh->insert('users', array(
                'strName'       => $u_name,
                'nManagerID'    => '36',
                'nSchoolID'     => '0',
                'strLease'      => '',
                'deleted'       => '0',
                'old_db'        => 'clusers_eng',
                'bNewsletter'   => 'N',
                'strEMail'      => $email,
                'strCurrency'   => $curr,
                'nCtrID'        => $cntry,
                'nUserStatus'   => $status,
                'nDistID'       => $distID
            ));
        }

        $felhasznalo = "SELECT `nUserID` FROM `users` WHERE `strEMail` = '".$email."' limit 1";
        $msh->query($felhasznalo);
        $felh = $msh->fetchNext();
        $user = $felh['nUserID'];

        if (mysqli_real_escape_string($conn, $_GET['user']) == "ismeretlen") {
            $insert = $msh->insert('u_emails', array(
                'email'         => $email,
                'nUserID'       => $user,
                'default'       => '1',
                'active'        => '1',
                'deleted'       => '0',
                'newsletter'    => '0'
            ));
        }

        $query = "SELECT `ctrNameEng` FROM `countries` WHERE `ctrID` = '{$cntry}'";
        $msh->query($query);
        $ctryName = $msh->fetchNext();

        //Utolso order Number
        $msh->query("SELECT `order` FROM `o_orders` WHERE `country` = '{$cntry}' ORDER BY `id` DESC limit 1");
        $order          = $msh->fetchNext();
        $orderNumber    = $order['order'];
        $kezdo          = strpos($orderNumber, "-")+1; // Majd a rakovetkezo, ez kerul be adatbazisba
        $veg            = strpos($orderNumber, "/")-2;
        $szam           = (int)substr($orderNumber, $kezdo, $veg)+1;
        $prOrderNumber  = "E-".$szam."/".date("Y");

        if ($isInvoice && $price != 0) {
            $partners = "SELECT * FROM szamla_agent.partnerek WHERE ország = ".$cntry;
            $msh->query($partners);
            $partner = $msh->fetchNext();

            if ($cntry == 37) {
                $date = new DateTime(date('Y-m'));
                $date->modify('+ 1 month');
                $paymentDue = $date->format('Y-m').'-15';
            } else {
                $date = new DateTime(date('Y-m-d'));
                $date->modify('+'.$partner["fizetési_határidő"]." day");
                $paymentDue = $date->format('Y-m-d');
            }

            //$agent = SzamlaAgentAPI::create('3i73vj72wt7h3ig78wrawt7h3ik5batswt7h3inhzw', false, Log::LOG_LEVEL_ERROR); // Szamla Agent CADLine kulcs
            $agent = SzamlaAgentAPI::create('97039xbwy2gws4iv7yn4xk8cniuird56tyamat6gy3', false, Log::LOG_LEVEL_DEBUG); // Teszt Kulcs

            //$invoice = new Invoice(Invoice::INVOICE_TYPE_E_INVOICE);
            $invoice = new Invoice(Invoice::INVOICE_TYPE_P_INVOICE); //Teszt Szamla

            $header = $invoice->getHeader();
            $header->setPaymentMethod(Invoice::PAYMENT_METHOD_TRANSFER);
            $header->setCurrency($cur);
            $header->setLanguage($lang);
            $header->setPaymentDue($paymentDue);
            $header->setComment("*Please use the invoice number (E-EUR-2020-xxx) as a reference number to identify your payment.

                Banktransfer info:
                K&H BANK Hungary
                IBAN: HU89 1040 0951 4955 4949 4954 1028
                SWIFT CODE: OKHBHUHB");
            //$header->setPrefix($inv_prefix);

            /*$seller = new Seller('K&H Bank EUR', 'IBAN: HU89 1040 0951 4955 4949 4954 1028');
            $seller->setEmailReplyTo('office@cadline.hu');
            $seller->setEmailSubject('Számlaértesítő / Invoice - CadLine Kft.');
            $seller->setEmailContent('Tisztelt/Dear '.$partner["kapcsolattartó_neve"].',


            Mellékelten küldjük aktuális számláját.
                Kérjük, utaláskor a közlemény rovatban KIZÁRÓLAG a számlaszámot tüntesse fel! (pl.: E-HUF-2020-xxxx)

                Amennyiben ezzel kapcsolatban bármilyen kérdése merülne fel, kérjük hívja Ügyfélszolgálatunkat, ahol munkatársaink készséggel állnak ügyfeleink rendelkezésére.

                Cadline Ltd invoice is attached. Please use the invoice number (E-EUR-2020-xxx) as a reference number to identify your payment. Payment made via wire transfer must be made in full including any fees/charges for the wire transfer, which are your responsibility. (If your bank uses an intermediary bank, there may be additional charges.) If payment is not received in full, you will be invoiced for any balance due on the account.
                Payment must be completed by the "due date" of the invoice date.


                Üdvözlettel / Sincerely:
                CadLine Office');
            $invoice->setSeller($seller);*/

            $buyer = new Buyer($partner["partner"], $partner["irányítószám"], $partner["település"], $partner["utca_házszám"]);
            $buyer->setTaxPayer($tax);

            if ($partner["közösségi_adószám"] != "")    $buyer->setTaxNumberEU($partner["közösségi_adószám"]);
            elseif ($partner["adószám"] != "")          $buyer->setTaxNumber($partner["adószám"]);

            if ($prod_prefix == 'Non-EU')   $afa_key = 'EUK'; // Ha non-eu-s a prod prefix, akkor eun kivuli
            if ($prod_prefix == 'EU')       $afa_key = 'EU';

            $buyer->setEmail($partner["email"]);
            $buyer->setSendEmail(true);
            $invoice->setBuyer($buyer);

            $product = "SELECT product_id FROM szamla_agent.web_product WHERE web_id = ".$ertek2['id'];
            $msh->query($product);
            $product_id = $msh->fetchNext();

            $termekek = "SELECT * FROM szamla_agent.termekek WHERE id = ".$product_id["product_id"];
            $msh->query($termekek);
            $termek = $msh->fetchNext();
        }

        $hardlock = "SELECT megnevezés, nettó FROM szamla_agent.termekek WHERE id = 30";
        $msh->query($hardlock);
        $hardlock_price = $msh->fetchNext();

        $verz = "SELECT `verCode`, verID FROM `p_versions` WHERE `verActual` = 'Y'";
        $msh->query($verz);
        $verzi                  = $msh->fetchNext();
        $version                = $verzi['verCode'];
        $prg_product_id         = 1;
        $generate_prev_program  = false;

        $sellDate           = date("Y-m-d H:i:s");
        $actDate            = date("Y-m-d H:i:s");
        $fizetve            = '2050-01-01';
        $time               = date("Y-m-d H:i:s");
        $lastMod            = date("Y-m-d H:i:s");
        $stat               = 0;
        $invoiceDateFrom    = date('Y-m', time());
        $contact            = 0;
        $hiType             = 1;


        // TODO: Adatbazisba bevezetni az o_product tablaba + a szerver.php-ba atvezetni!!!

        $o_types = "SELECT * FROM `o_types` WHERE `id` = ".$ertek2['o_type'];
        $msh->query($o_types);
        $o_type = $msh->fetchNext();

        $type       = $o_type['to'];
        $typeNames  = array(
            2   => 'Interior',
            4   => 'LT',
            6   => 'Studio',
            8   => 'Professional',
            'L' => 'LIVE'
        );

        switch ($kategoria) {
            case 'perp':
                if (mysqli_real_escape_string($conn, $_GET['reszlet']) == "Y") {
                    switch ($cntry) {
                        case '43':
                            $reszlet    = 3;
                            $payment    = 'Instalments: 4  Period: quarterly';
                            $fizHatIdo  = date('Y-m', strtotime($ma. '+365 days'));
                            if (strstr($program, "Professional") || strstr($program, "Prof.")) $payment = 'Instalments: 4  Period: monthly';
                        break;

                        case '39':
                            $reszlet    = 12;
                            $payment    = 'Instalments: 2  Period: yearly';
                            $fizHatIdo  = date('Y-m', strtotime($ma. '+365 days'));
                        break;

                        case '48':
                            $reszlet    = 1;
                            $payment    = 'Instalments: 4  Period: monthly';
                            $fizHatIdo  = date('Y-m', strtotime($ma. '+120 days'));
                        break;

                        case '42':
                            $reszlet    = 1;
                            $payment    = 'Instalments: 6  Period: monthly';
                            $fizHatIdo  = date('Y-m', strtotime($ma. '+180 days'));
                        break;
                    }
                } else {
                    $reszlet    = '';
                    $payment    = 'pay in full';
                    $fizHatIdo  = date('Y-m', strtotime($ma. '+365 days'));
                }

                $keres = "SELECT `verID` FROM `p_versions` ORDER BY `verCode` DESC limit 1";
                $msh->query($keres);
                $limit = $msh->fetchNext();

                $alap_ar    = $price; // $alap_ar megszunik!!!!
                $lan        = "0";
                $ertek      = $price;
                $ev2        = date("Y");
                $elozoEv1   = $ev2-1;
                $elozoEv2   = $ev2-2;
                $elozoEv3   = $ev2-3;
                $elozoEv4   = $ev2-4;
                $msg        = "";
                $msg2       = "";
                $msg3       = "";
                $msg4       = "";

                if ($hl_prot == "Y") { // Ker hardlockot
                    $kulcs          = mysqli_real_escape_string($conn, $_GET['hl_num']);
                    $hardlockPrice  = $hardlock_price["nettó"];
                    $ertek          = $price + $hardlockPrice;
                    $hardlock_id    = $cntry;

                    if ($cntry == "43" || $cntry == "39") $ertek = $price;
                }

                if ($hl_prot == "N") { // Nem ker hardlockot -> szoftveres kulcs
                    $query = "SELECT `hlNum` FROM `hardlock` WHERE `hlNum` LIKE '95%' ORDER BY `hlNum` DESC limit 1";
                    $msh->query($query);
                    $kulcsok        = $msh->fetchNext();
                    $kulcs          = $kulcsok['hlNum']+1;
                    $hardlock_id    = "95";
                }

                $number = substr($kulcs, 2, 4);

                if ((mysqli_real_escape_string($conn, $_GET['code_prev_version']) == "Y" && $generate_prev_program == false) || mysqli_real_escape_string($conn, $_GET['ver_2']) == "Y" || mysqli_real_escape_string($conn, $_GET['ver_3']) == "Y" || mysqli_real_escape_string($conn, $_GET['ver_4']) == "Y") {
                    if ($cntry == '37' || $cntry == '43') $ertek += 150;
                }

                $live = $alap_ar;
                if(mysqli_real_escape_string($conn, $_GET['inclLive']) == "Y") {
                    $live   += 100;
                    $ertek  += 100;
                }

                $subtotal = $price;
                if ((strpos($program, "Interior") || strpos($program, "Professional")) && strpos($program, "LIVE")) {
                    $subtotal -= 100;
                    $live_item = "Subtotal: <b>100</b>";
                }

                if (((strpos($program, "Interior") || strpos($program, "Professional")) && strpos($program, "LIVE") && strpos($program, "option") == FALSE) || mysqli_real_escape_string($conn, $_GET['inclLive']) == "Y") {
                    $query = "SELECT `hlNum` FROM `hardlock` WHERE `hlNum` LIKE '$cntry%' ORDER BY `hlNum` DESC limit 1";
                    $msh->query($query);
                    $live_kulcsok   = $msh->fetchNext();

                    $query = "SELECT * FROM `p_versions` WHERE currentVer = 0 OR currentVer = 2";
                    $msh->query($query);
                    $curr_ver = $msh->fetchNext();

                    $kulcs_live     = $live_kulcsok['hlNum']+2;
                    $number_live    = substr($kulcs_live, 2,4);
                    $version_live   = $curr_ver['verCode'];
                    $lan_live       = "0";
                    $type_live      = "L";
                    $command        = PATH_CODEGEN." -Password " . $cntry . $number_live . $version_live . $lan_live . $type_live;
                    $ph             = popen($command, "r") or die( "A 'codegen' paranccsal nem veheto fel kapcsolat" );
                    $serial_live    = fgets($ph, 1024);
                    pclose($ph);

                    if(mysqli_real_escape_string($conn, $_GET['inclLive']) == "Y") {
                        $item_live = "
    Item: <b>Live</b>

    Subtotal: <b>100</b>";
                    }

                    $live_msg = "Serial code 2019 Live: <b>".$serial_live."</b>";

                    $insert = $msh->insert('hardlock', array(
                        'hlNum'         => $kulcs_live,
                        'hlLan'         => '0',
                        'hlStat'        => '1',
                        'hlDateIssue'   => $ma,
                        'hlUser'        => $user,
                        'hlManID'       => '36',
                        'hlCtrID'       => $cntry,
                        'old_db'        => 'clusers_eng',
                        'hlTime'        => date("Y-m-d H:i:s"),
                        'product_id'    => 2
                    ));

                    $insert = $msh->insert('h_programs', array(
                        'prTypeID'              => 76,
                        'prVerID'               => $curr_ver['verID'],
                        'prLan'                 => '0',
                        'prPass'                => $serial_live,
                        'prSellDate'            => date("Y-m-d H:i:s"),
                        'prOrdNum'              => $prOrderNumber,
                        'prActDate'             =>date("Y-m-d H:i:s"),
                        'prFizetve'             => '2050-01-01',
                        'prTime'                => date("Y-m-d H:i:s"),
                        'prLastMod'             => date("Y-m-d H:i:s"),
                        'prContact'             => '0',
                        'prHlNum'               => $kulcs_live,
                        'prManID'               => '36',
                        'prCtrID'               => $cntry,
                        'prStat'                => '0',
                        'prActCode'             => '',
                        'prInvoiceDateFrom'     => date('Y-m', time()),
                        'prInvoiceDateto'       => $fizHatIdo,
                        'prInvoiceRecurrence'   => $reszlet,
                        'old_db'                => 'clusers_eng',
                        'old_prID'              => '0',
                    ));

                    $insert = $msh->insert('h_history', array(
                        'hiHlNum'   => $kulcs_live,
                        'hiDate'    => date('Y-m-d'),
                        'hiManID'   => 36,
                        'hiTypeID'  => 3,
                        'hiTime'    => date("Y-m-d H:i:s"),
                        'hiInfo'    => "Web order, Aktiválás érvényessége: 2050-01-01",
                    ));
                }

                // 1 evvel ezelotti kulcs generalas
                if (mysqli_real_escape_string($conn, $_GET['code_prev_version']) == "Y") $generate_prev_program = true;

                // 2 evvel ezelotti kulcs generalas
                if (mysqli_real_escape_string($conn, $_GET['ver_2']) == "Y") {
                    $version2   = $verzi['verCode']-2;
                    $command    = PATH_CODEGEN." -Password " . $hardlock_id . $number . $version2 . $lan . $type;
                    $ph         = popen($command, "r") or die( "A 'codegen' paranccsal nem veheto fel kapcsolat" );
                    $serial17_2 = fgets($ph, 1024);
                    pclose($ph);

                    $msg2 = "Serial code $elozoEv2: <b>$serial17_2</b><br/>";

                    $insert = $msh->insert('h_programs', array(
                        'prTypeID'              => $type,
                        'prVerID'               => $verzi['verID']-2,
                        'prLan'                 => '0',
                        'prPass'                => $serial17_2,
                        'prSellDate'            => date("Y-m-d H:i:s"),
                        'prOrdNum'              => $prOrderNumber,
                        'prActDate'             => date("Y-m-d H:i:s"),
                        'prFizetve'             => '2050-01-01',
                        'prTime'                => date("Y-m-d H:i:s"),
                        'prLastMod'             => date("Y-m-d H:i:s"),
                        'prContact'             => '0',
                        'prHlNum'               => $kulcs,
                        'prManID'               => '36',
                        'prCtrID'               => $cntry,
                        'prStat'                => '0',
                        'prActCode'             => '',
                        'prInvoiceDateFrom'     => date('Y-m', time()),
                        'prInvoiceDateto'       => $fizHatIdo,
                        'prInvoiceRecurrence'   => $reszlet,
                        'old_db'                => 'clusers_eng',
                        'old_prID'              => '0',
                    ));
                }

                // 3 evvel ezelotti kulcs generalas
                if (mysqli_real_escape_string($conn, $_GET['ver_3']) == "Y") {
                    $version3   = $verzi['verCode']-3;
                    $command    = PATH_CODEGEN." -Password " . $hardlock_id . $number . $version3 . $lan . $type;
                    $ph         = popen($command, "r") or die( "A 'codegen' paranccsal nem veheto fel kapcsolat" );
                    $serial16   = fgets($ph, 1024);
                    pclose($ph);

                    $msg3 = "Serial code $elozoEv3: <b>$serial16</b><br/>";

                    $insert = $msh->insert('h_programs', array(
                        'prTypeID'              => $type,
                        'prVerID'               => $verzi['verID']-3,
                        'prLan'                 => '0',
                        'prPass'                => $serial16,
                        'prSellDate'            => date("Y-m-d H:i:s"),
                        'prOrdNum'              => $prOrderNumber,
                        'prActDate'             => date("Y-m-d H:i:s"),
                        'prFizetve'             => '2050-01-01',
                        'prTime'                => date("Y-m-d H:i:s"),
                        'prLastMod'             => date("Y-m-d H:i:s"),
                        'prContact'             => '0',
                        'prHlNum'               => $kulcs,
                        'prManID'               => '36',
                        'prCtrID'               => $cntry,
                        'prStat'                => '0',
                        'prActCode'             => '',
                        'prInvoiceDateFrom'     => date('Y-m', time()),
                        'prInvoiceDateto'       => $fizHatIdo,
                        'prInvoiceRecurrence'   => $reszlet,
                        'old_db'                => 'clusers_eng',
                        'old_prID'              => '0',
                    ));
                }

                // 4 evvel ezelotti kulcs generalas
                if (mysqli_real_escape_string($conn, $_GET['ver_4']) == "Y") {
                    $version4   = $verzi['verCode']-4;
                    $command    = PATH_CODEGEN." -Password " . $hardlock_id . $number . $version4 . $lan . $type;
                    $ph         = popen($command, "r") or die( "A 'codegen' paranccsal nem veheto fel kapcsolat" );
                    $serial15   = fgets($ph, 1024);
                    pclose($ph);

                    $msg4 = "Serial code $elozoEv4: <b>$serial15</b><br/>";

                    $insert = $msh->insert('h_programs', array(
                        'prTypeID'              => $type,
                        'prVerID'               => $verzi['verID']-4,
                        'prLan'                 => '0',
                        'prPass'                => $serial15,
                        'prSellDate'            => date("Y-m-d H:i:s"),
                        'prOrdNum'              => $prOrderNumber,
                        'prActDate'             => date("Y-m-d H:i:s"),
                        'prFizetve'             => '2050-01-01',
                        'prTime'                => date("Y-m-d H:i:s"),
                        'prLastMod'             => date("Y-m-d H:i:s"),
                        'prContact'             => '0',
                        'prHlNum'               => $kulcs,
                        'prManID'               => '36',
                        'prCtrID'               => $cntry,
                        'prStat'                => '0',
                        'prActCode'             => '',
                        'prInvoiceDateFrom'     => date('Y-m', time()),
                        'prInvoiceDateto'       => $fizHatIdo,
                        'prInvoiceRecurrence'   => $reszlet,
                        'old_db'                => 'clusers_eng',
                        'old_prID'              => '0',
                    ));
                }

                if (strstr($program, "Professional") || strstr($program, "Prof.")) $prod = "Professional";
                if (strstr($program, "Interior")) $prod = "Interior";
                if (strstr($program, "Studio")) $prod = "Studio";
                break;

            case 'live':
                $kulcs = substr((string)tryToAlloc(($cntry*10000)+1, ($cntry*10000)+9999), 0, 6);

                $query = "SELECT * FROM `p_versions` WHERE currentVer = 0 OR currentVer = 2";
                $msh->query($query);
                $curr_ver = $msh->fetchNext();

                $version        = $curr_ver['verCode'];
                $lan            = 0;
                $hardlock_id    = $cntry;
                $ertek          = $price;
                $alap_ar        = $price;
                $prod           = 'ARCHLINE.XP LIVE';
                $prg_product_id = 2;

                break;

            case 'lt':
                $kulcs = substr((string)tryToAlloc(($cntry*10000)+1, ($cntry*10000)+9999), 0, 6);

                $lan            = 0;
                $hardlock_id    = $cntry;
                $ertek          = $price;
                $alap_ar        = $price;
                $prod           = "ARCHLINE.XP LT";

                if (strpos($program, "LT") && strpos($program, "LIVE")) {
                    $query = "SELECT `hlNum` FROM `hardlock` WHERE `hlNum` LIKE '$cntry%' ORDER BY `hlNum` DESC limit 1";
                    $msh->query($query);
                    $kulcs2 = $msh->fetchNext();
                    $kulcs_live = $kulcs2['hlNum']+2;

                    $query = "SELECT * FROM `p_versions` WHERE currentVer = 0 OR currentVer = 2";
                    $msh->query($query);
                    $curr_ver = $msh->fetchNext();

                    $number_live    = substr($kulcs_live, 2, 4);
                    $version_live   = $curr_ver['verCode'];
                    $lan_live       = 0;
                    $type_live      = "L";
                    $command        = PATH_CODEGEN." -Password " . $cntry . $number_live . $version_live . $lan_live . $type_live;
                    $ph             = popen($command, "r") or die( "A 'codegen' paranccsal nem veheto fel kapcsolat" );
                    $serial_live    = fgets($ph, 1024);
                    pclose($ph);

                    $insert = $msh->insert('hardlock', array(
                        'hlNum'         => $kulcs_live,
                        'hlLan'         => '0',
                        'hlStat'        => '1',
                        'hlDateIssue'   => $ma,
                        'hlUser'        => $user,
                        'hlManID'       => '36',
                        'hlCtrID'       => $cntry,
                        'old_db'        => 'clusers_eng',
                        'hlTime'        => date("Y-m-d H:i:s"),
                        'product_id'    => 2
                    ));

                    $insert = $msh->insert('h_programs', array(
                        'prTypeID'              => 76,
                        'prVerID'               => $curr_ver['verID'],
                        'prLan'                 => '0',
                        'prPass'                => $serial_live,
                        'prSellDate'            => date("Y-m-d H:i:s"),
                        'prOrdNum'              => $prOrderNumber,
                        'prActDate'             => date("Y-m-d H:i:s"),
                        'prFizetve'             => '2050-01-01',
                        'prTime'                => date("Y-m-d H:i:s"),
                        'prLastMod'             => date("Y-m-d H:i:s"),
                        'prContact'             => '0',
                        'prHlNum'               => $kulcs_live,
                        'prManID'               => '36',
                        'prCtrID'               => $cntry,
                        'prStat'                => '0',
                        'prActCode'             => '',
                        'prInvoiceDateFrom'     => date('Y-m', time()),
                        'prInvoiceDateto'       => $fizHatIdo,
                        'prInvoiceRecurrence'   => $reszlet,
                        'old_db'                => 'clusers_eng',
                        'old_prID'              => '0',
                    ));

                    $insert = $msh->insert('h_history', array(
                        'hiHlNum'   => $kulcs_live,
                        'hiDate'    => date('Y-m-d'),
                        'hiManID'   => 36,
                        'hiTypeID'  => 3,
                        'hiTime'    => date("Y-m-d H:i:s"),
                        'hiInfo'    => "Web order, Aktiválás érvényessége: 2050-01-01",
                    ));

                    $live_msg = "Serial code 2019 LIVE: <b>".$serial_live."</b>";
                }
                break;

            case 'upgrade':
                $old_serial = mysqli_real_escape_string($conn, $_GET['old_hlNum']);

                if (strlen($old_serial) == "16") { //Update esete
                    if (substr($old_serial, 6, 1) != $o_type['from'] || substr($old_serial, 6, 1) != 7) {
                        $eredmeny['hiba'] = "Its not a ".$typeNames[$o_type['from']]." serial.
                            <br /><br />
                            <a href='javascript:location.reload()'>Continue</a>.";
                        echo json_encode($eredmeny);
                        return false;
                    }

                    if (substr($old_serial, 6, 1) == "8" && (substr($old_serial, 7, 2) == $verzi['verPassword8and9'])) {
                        $eredmeny['hiba'] = "You can't upgrade this software
                            <br /><br />
                            <a href='javascript:location.reload()'>Continue</a>.";
                        echo json_encode($eredmeny);
                        return false;
                    }

                    $query = "SELECT * FROM `h_programs` WHERE `prPass` = {$old_serial}";
                    $msh->query($query);
                    $hl     = $msh->fetchNext();
                    $hl_num = $hl['prHlNum'];

                    $ertek          = $price;
                    $kulcs          = substr($old_serial, 0, 6);
                    $hardlock_id    = substr($old_serial, 0, 2);
                    $number         = substr($old_serial, 2,4);

                    $query = "SELECT `hlLan` FROM `hardlock` WHERE `hlNum`='".$kulcs."' ORDER BY `hlNum` DESC limit 1";
                    $msh->query($query);
                    $hlLan  = $msh->fetchNext();
                    $lan    = $hlLan['hlLan'];

                    // Ha NOVA, akkor professionalt kap
                    if (substr($old_serial, 6, 1) == 7) $type = 8;

                    $lan2 = 0;

                    if ($lan == 0) $lan2 = 0;
                    elseif ($lan == 1) $lan2 = 0;
                    elseif ($lan == 2) $lan2 = 2;
                    elseif ($lan == 3) $lan2 = 3;
                    elseif ($lan == 4) $lan2 = 4;
                    elseif ($lan == 5) $lan2 = 5;
                    elseif ($lan == 10) $lan2 = 6;
                    elseif ($lan == 15) $lan2 = 7;
                    elseif ($lan == 20) $lan2 = 8;
                    elseif ($lan <= 49) $lan2 = 9;

                    $lan        = $lan2;
                    $command    = PATH_CODEGEN." -Password " . $hardlock_id . $number . $version . $lan . $type;
                    $ph         = popen($command, "r") or die( "A 'codegen' paranccsal nem veheto fel kapcsolat" );
                    $serial     = fgets($ph, 1024);
                    $password   = $serial;
                    pclose($ph);

                    $query = "SELECT * FROM `h_programs` WHERE `prPass`='".$serial."'";
                    $msh->query($query);
                    $prg = $msh->fetchNext();

                    if (empty($prg) == false) {
                        $eredmeny['hiba'] = "You already upgraded this serial number.
                            <br /><br />
                            <a href='javascript:location.reload()'>Continue</a>.";
                        echo json_encode($eredmeny);
                        return false;
                    }

                    // Ha studio, akkor meg kell allapítani hogy volt-e hozzatartozo module, ha igen, akkor ott az mdPrID-t, es a mdPrHlNum-ot kell modositani az uj programhoz
                    if (substr($serial, 6, 1) == "6") {
                        // Regi programhoz tartozo modul(ok)
                        $msh->query("SELECT * FROM `p_modules` WHERE `mdPrHlNum` = '{$kulcs}'");
                        $modules    = $msh->fetchAssoc();
                        $uj_kulcs   = $kulcs;
                    }

                    $prod = "Upgrade";
                    if ($o_type['from'] != $o_type['to']) $hiType = 2;
                    if ($o_type['from'] == $o_type['to']) $hiType = 3;

                    $msh->update("h_programs", array("prStat" => 1),"prPass = '{$old_serial}'");
                } else {
                    $eredmeny['hiba'] = "Wrong serial.
                        <br /><br />
                        <a href='javascript:location.reload()'>Continue</a>.";
                    echo json_encode($eredmeny);
                    return false;
                }
                break;

            case 'crossgrade':
                $old_serial = mysqli_real_escape_string($conn, $_GET['old_hlNum']);

                if (substr($old_serial, 6, 1) != $o_type['from']) {
                    $eredmeny['hiba'] = "Its not a ".$typeNames[$o_type['from']]." serial.
                        <br /><br />
                        <a href='javascript:location.reload()'>Continue</a>.";
                    echo json_encode($eredmeny);
                    return false;
                }

                $verz = "SELECT `verCode` FROM `p_versions` WHERE `verPassword8and9` = '".substr($old_serial, 7, 2)."'";
                $msh->query($verz);
                $verzi = $msh->fetchNext();

                $query = "SELECT hlNum FROM hardlock WHERE hlNum LIKE '95%' AND hlStat = 0  AND (hlDealer = '' OR hlDealer IS NULL) AND (hlUser = '' OR hlUser IS NULL) AND (hlInfo = '' OR hlInfo IS NULL) limit 1";
                $msh->query($query);
                $hlnum          = $msh->fetchNext();
                $kulcs          = $hlnum['hlNum'];
                $prod           = "Crossgrade";
                $regi_kulcs     = substr($old_serial, 0, 6);
                $hardlock_id    = 95;
                $version        = $verzi['verCode'];
                $ertek          = $price;
                $lan            = 0;
                $hiType         = 2;

                $msh->query("SELECT * FROM `p_modules` WHERE `mdPrHlNum` = '{$regi_kulcs}'");
                $modules    = $msh->fetchAssoc();
                $uj_kulcs   = $kulcs;
                break;

            case 'module':
                $hl_num = mysqli_real_escape_string($conn, $_GET['old_hlNum']);
                $query  = "SELECT `prId`, `prPass` FROM `h_programs` WHERE `prHlNum` = '{$hl_num}' ORDER BY `prID` DESC limit 1";
                $msh->query($query);
                $program_adatok = $msh->fetchNext();

                // Csak Studio-hoz lehet kiadni modulokat
                if (substr($program_adatok['prPass'], 6,1) != "6") {
                    $eredmeny['hiba'] = "You can buy modules only for Studio
                        <br /><br />
                        <a href='javascript:location.reload()'>Continue</a>.";
                    echo json_encode($eredmeny);
                    return false;
                }

                $prId       = $program_adatok['prId'];
                $prHlNum    = $hl_num;

                if (strpos($program, "Terrain")) $verz = "2";
                else $verz = "22";

                // A hozzatartozo program serialja
                $password               = $program_adatok['prPass'];
                $command                = PATH_CODEGEN." -Module " . $password . " " . $verz;
                $ph                     = popen($command, "r") or die("A 'codegen' paranccsal nem veheto fel kapcsolat");
                $modcode                = fgets($ph, 1024);
                pclose($ph);

                // Ha mar van ilyen module az adott programhoz
                $query = "SELECT `ID` FROM `p_modules` WHERE `mdPrID` = '{$prId}'  AND `mdID` = '{$verz}' AND `mdPrHlNum` = '{$prHlNum}'";
                $msh->query($query);
                $module = $msh->fetchNext();

                if ($module['ID']) {
                    $eredmeny['hiba'] = "You already have this module
                        <br /><br />
                        <a href='javascript:location.reload()'>Continue</a>.";
                    echo json_encode($eredmeny);
                    return false;
                }

                $insert = $msh->insert('p_modules', array(
                    'mdID'          => $verz,
                    'mdPrID'        => $prId,
                    'mdPrHlNum'     => $prHlNum,
                    'mdCode'        => $modcode,
                    'mdDate'        => $ma,
                    'mdPrice'       => '0',
                    'mdInvNum'      => '',
                    'mdOrdNum'      => $prOrderNumber,
                    'mdIsPurchase'  => '0',
                ));

                $ertek  = $price;
                $serial = $modcode;
                $prod   = "Module";
                break;

            case 'nonp':
                //Ha mar volt nala ebben az evben?
                $nonpr  = mysqli_real_escape_string($conn, $_GET['nonpro_ev']);
                $datum  = mysqli_real_escape_string($conn, $_GET['datum']); // Ezt kérte speciálisan a partner. Attól függetlenül nem ez a dátum kerül be az adatbázisba
                $date   = date_create($datum);
                $datum  = date_format($date, "d/m/Y");
                $expire = date_format($date, "Y-m-d");

                $ev = substr($nonpr, 3, 4);

                $query = "SELECT `verID`, `verCode`, `verPassword8and9` FROM `p_versions` WHERE `verName` = '{$nonpr}'";
                $msh->query($query);
                $vcode = $msh->fetchNext();

                if (strpos($program, "LIVE")) {
                    $prg_product_id = 2;
                    $type           = "L";
                }

                $query = "SELECT SUBSTRING(`prPass`, 8, 2) AS `prPass` FROM `h_programs` WHERE `prHlNum` IN (SELECT `hlNum` FROM `hardlock` WHERE `hlUser` = '{$user}' AND product_id = '{$prg_product_id}') AND `prHlNum` LIKE '99%'";
                $msh->query($query);
                $nonprofit_kulcsok_evben = $msh->fetchAssoc();

                $evek = array();
                foreach ($nonprofit_kulcsok_evben as $v) {
                    $b      = (object)$v;
                    $evek[] = $b->prPass;
                }

                // Ha mar volt nonprofit kulcsa az adott evben akkor nem enged tovább
                if (!empty($evek)) {
                    if (in_array($vcode['verPassword8and9'], $evek) !== FALSE) {
                        $eredmeny['hiba'] = "You already have a non-profit key for this product
                            <br /><br />
                            <a href='javascript:location.reload()'>Continue</a>.";
                        echo json_encode($eredmeny);
                        return false;
                    }
                }

                $query = "SELECT `hlNum` FROM `hardlock` WHERE `hlNum` LIKE '99%' AND `hlStat` = 0 AND `hlLan` = 0 ORDER BY `hlNum` ASC limit 1";
                $msh->query($query);
                $nonprofitok    = $msh->fetchNext();
                $kulcs          = $nonprofitok['hlNum'];

                // Ha nincs mar, akkor letre kell hozni!!!
                if (empty($nonprofitok['hlNum'])) {
                    $eredmeny['hiba'] = "There are no free nonprofit keys yet, please contact us.";
                    echo json_encode($eredmeny);
                    return false;
                }

                $msh->update("hardlock", array("hlStat"=>'1', "hlUser"=>$user, "old_hlID"=>'', "old_db"=>'clusers_eng', "hlDateIssue"=>$ma, "product_id"=>2, "hlCtrID"=>$cntry),"hlNum = {$kulcs}");

                $version        = $vcode['verCode'];
                $hardlock_id    = substr($kulcs, 0, 2);
                $lan            = 0;
                $contact        = 5;
                $fizetve        = date('Y-m-d', strtotime($ma. '+60 days'));

                if ($expire < $fizetve) $fizetve = $expire;

                if (($cntry == 61 || $cntry == 37) && strpos($program, "LIVE") == FALSE) {
                    $query_live = "SELECT `hlNum` FROM `hardlock` WHERE `hlNum` LIKE '99%' AND `hlStat` = 0 AND `hlLan` = 0 ORDER BY `hlNum` ASC limit 1";
                    $msh->query($query_live);
                    $nonprofitok_live   = $msh->fetchNext();

                    $query = "SELECT * FROM `p_versions` WHERE currentVer = 0 OR currentVer = 2";
                    $msh->query($query);
                    $curr_ver = $msh->fetchNext();

                    $kulcs_live         = $nonprofitok_live['hlNum'];
                    $number_live        = substr($kulcs_live, 2,4);
                    $version_live       = $curr_ver['verCode'];
                    $lan_live           = 0;
                    $type_live          = "L";

                    $command        = PATH_CODEGEN." -Password " . 99 . $number_live . $version_live . $lan_live . $type_live;
                    $ph             = popen($command, "r") or die( "A 'codegen' paranccsal nem veheto fel kapcsolat" );
                    $serial_live    = fgets($ph, 1024);
                    pclose($ph);

                    $msh->update("hardlock", array("hlStat"=>'1', "hlUser"=>$user, "old_hlID"=>'', "old_db"=>'clusers_eng', "hlDateIssue"=>$ma, "product_id"=>2, "hlCtrID"=>$cntry),"hlNum = {$kulcs_live}");

                    $insert = $msh->insert('h_programs', array(
                        'prTypeID'              => 76,
                        'prVerID'               => $curr_ver['verID'],
                        'prLan'                 => 0,
                        'prPass'                => $serial_live,
                        'prSellDate'            => date("Y-m-d H:i:s"),
                        'prOrdNum'              => $prOrderNumber,
                        'prActDate'             => date("Y-m-d H:i:s"),
                        'prFizetve'             => date('Y-m-d', strtotime($ma. '+60 days')),
                        'prTime'                => date("Y-m-d H:i:s"),
                        'prLastMod'             => date("Y-m-d H:i:s"),
                        'prContact'             => '5',
                        'prHlNum'               => $kulcs_live,
                        'prManID'               => 36,
                        'prCtrID'               => $cntry,
                        'prStat'                => 0,
                        'prActCode'             => '',
                        'prInvoiceDateFrom'     => date('Y-m', time()),
                        'prInvoiceDateto'       => '',
                        'prInvoiceRecurrence'   => '',
                        'old_db'                => 'clusers_eng',
                        'old_prID'              => 0,
                    ));

                    $insert = $msh->insert('h_history', array(
                        'hiHlNum'   => $kulcs_live,
                        'hiDate'    => date('Y-m-d'),
                        'hiManID'   => 36,
                        'hiTypeID'  => 3,
                        'hiTime'    => date("Y-m-d H:i:s"),
                        'hiInfo'    => "Web order, Aktiválás érvényessége: ".date('Y-m-d', strtotime($ma. '+60 days')),
                    ));

                    $live_nonp = "Activation key Live: <b>$serial_live</b><br/>";
                }

                if ($cntry == 82) $ertek = $price; // Koreaban a Non-Profit fizetos
                else $ertek = 0;

                if ($_FILES) {
                    user_error(print_r($_FILES, true));
                    $uploads_dir = 'tmpl/';
                    $target_path = $uploads_dir.basename($_FILES['file']['name'] );
                    if (move_uploaded_file($_FILES['file']['tmp_name'], $target_path))
                        echo 'File uploaded';
                    else {
                        $eredmeny['hiba'] = 'Error in uploading file ';
                        echo json_encode($eredmeny);
                        return false;
                    }
                }

                $prod = "Non-profit";
                break;

            case 'hardlock':
                $regi_kulcs = substr(mysqli_real_escape_string($conn, $_GET['old_hlNum']),0,6);
                $kulcs      = mysqli_real_escape_string($conn, $_GET['hl_num']);

                // megadtak-e, letezik-e uj kulcs
                if (!$regi_kulcs || empty($regi_kulcs) || strlen($regi_kulcs) != 6) {
                    $eredmeny['hiba'] = "There is a problem with the hardlock key
                        <br /><br />
                        <a href='javascript:location.reload()'>Continue</a>.";
                    echo json_encode($eredmeny);
                    return false;
                } else {
                    $oldHlNum = "SELECT * FROM `hardlock` WHERE hlNum = '".$regi_kulcs."'";
                    $msh->query($oldHlNum);
                    $talalat = $msh->fetchNext();
                    if (!$talalat['hlNum']) {
                        $eredmeny['hiba'] = "There is a problem with the hardlock key
                            <br /><br />
                            <a href='javascript:location.reload()'>Continue</a>.";
                        echo json_encode($eredmeny);
                        return false;
                    } else {
                        $query = "SELECT * FROM `h_programs` WHERE `prHlNum` = '".$regi_kulcs."' ORDER BY `prID` DESC limit 1";
                        $msh->query($query);
                        $utolsoProgram = $msh->fetchNext();

                        $eddigi_ver_id = $utolsoProgram['prVerID'];

                        $verz = "SELECT `verCode` FROM `p_versions` WHERE `verID` = '".$eddigi_ver_id."'";
                        $msh->query($verz);
                        $verzi      = $msh->fetchNext();
                        $version    = $verzi['verCode'];
                        $type       = $utolsoProgram['prTypeID'];
                        $ertek      = $price;
                    }
                }

                $hardlock_msg       = "Old hardlock: {$regi_kulcs}";
                $hardlock_msg      .= "New hardlock: {$$kulcs}";
                $sellDate           = $utolsoProgram['prSellDate'];
                $actDate            = $utolsoProgram['prActDate'];
                $fizetve            = $utolsoProgram['prFizetve'];
                $time               = $utolsoProgram['prTime'];
                $lastMod            = $utolsoProgram['prLastMod'];
                $contact            = $utolsoProgram['prContact'];
                $stat               = 0;
                $cntry              = $utolsoProgram['prCtrID'];
                $invoiceDateFrom    = $utolsoProgram['prInvoiceDateFrom'];
                $fizHatIdo          = $utolsoProgram['prInvoiceDateto'];
                $reszlet            = $utolsoProgram['prInvoiceRecurrence'];
                $lan                = $talalat["hlLan"];
                $ertek              = $price;
                $prod               = "Hardlock";
                $hardlock_id        = substr($kulcs, 0, 2);

                $msh->query("SELECT * FROM `p_modules` WHERE `mdPrHlNum` = '{$regi_kulcs}'");
                $modules    = $msh->fetchAssoc();
                $uj_kulcs   = $kulcs;
                break;
        }

        if ($ertek2['until'] != '' && $ertek2['until'] != NULL) $fizetve = $ertek2['until'];
        $number = substr($kulcs, 2,4);

        if ($kategoria != "module") {
            $command    = PATH_CODEGEN." -Password " . $hardlock_id . $number . $version . $lan . $type;
            $ph         = popen($command, "r") or die( "A 'codegen' paranccsal nem veheto fel kapcsolat" );
            $serial     = fgets($ph, 1024);
            $password   = $serial;
            pclose($ph);
        }

        if ($kategoria != "module") {
            // hardlock tablaban benne van mar a kulcs? Akkor update. Ha nincs, akkor insert
            $van = "SELECT * FROM `hardlock` WHERE `hlNum` = '".$kulcs."'";
            $msh->query($van);
            $result = $msh->fetchNext();
            /*if (!empty($result)) {
                $update = $msh->update("hardlock", array("hlStat"=>'1', "hlLan"=>'0', "hlDateIssue"=>$ma, "hlManID"=>'36', "hlCtrID"=>$cntry, "product_id"=>$prg_product_id, "hlTime"=>date("Y-m-d H:i:s"), "hlUser"=>$user), "hlNum = {$kulcs}");
            } else {
                $insert = $msh->insert('hardlock', array(
                    'hlNum'         => $kulcs,
                    'hlLan'         => '0',
                    'hlStat'        => '1',
                    'hlDateIssue'   => $ma,
                    'hlUser'        => $user,
                    'hlManID'       => '36',
                    'hlCtrID'       => $cntry,
                    'old_db'        => 'clusers_eng',
                    'hlTime'        => date("Y-m-d H:i:s"),
                    'product_id'    => $prg_product_id
                ));
            }*/
        }

        //o_ordersbe bekerules
        /*$orders_insert = $msh->insert('o_orders', array(
            'ip'            => $ip,
            'country'       => $cntry,
            'date'          => $ma,
            'software'      => $program,
            'user_name'     => $u_name,
            'user_email'    => $email,
            'order'         => $prOrderNumber,
            'input_key'     => $regi_kulcs,
            'output_key'    => $serial,
            'price'         => $ertek,
            'info'          => $info,
            'instalments'   => $payment
        ));*/

        // verID meghatarozasa -> mindig az aktualis evhez tartozot valasztja ki
        $query = "SELECT `verID` FROM `p_versions` WHERE `verCode` = '".$version."'";
        $msh->query($query);
        $tomb = $msh->fetchNext();

        $userNumber = $lan == 0 || IsSoftwareKey($serial) == false ? 1 : $lan;

        if ($generate_prev_program) {
            // Jelenleg meg 2019-es programot is adunk!
            $ev2                    = date("Y");
            $elozoEv1               = $ev2-1;
            $ver_prev               = $verzi['verCode']-1;
            $command                = PATH_CODEGEN." -Password " . $hardlock_id . $number . $ver_prev . $lan . $type;
            $ph                     = popen($command, "r") or die( "A 'codegen' paranccsal nem veheto fel kapcsolat" );
            $serial_prev            = fgets($ph, 1024);
            pclose($ph);

            $lt_message = "Serial code $elozoEv1: <b>".$serial_prev."</b>";
            $msg_2019   = "Serial $elozoEv1: <b>".$serial_prev."</b>";
            $msg        = "Serial code $elozoEv1: <b>$serial_prev</b><br/>";
        }

        if ($type == "L") $type = 76;

        /*if ($kategoria != "module") {
            for ($i = 1; $i <= $userNumber; $i++) {
                $insert = $msh->insert('h_programs', array(
                    'prTypeID'              => $type,
                    'prVerID'               => $tomb['verID'],
                    'prLan'                 => $lan,
                    'prPass'                => $serial,
                    'prSellDate'            => $sellDate,
                    'prOrdNum'              => $prOrderNumber,
                    'prActDate'             => $actDate,
                    'prFizetve'             => $fizetve,
                    'prTime'                => $time,
                    'prLastMod'             => $lastMod,
                    'prPrice'               => $ertek,
                    'prContact'             => $contact,
                    'prHlNum'               => $kulcs,
                    'prManID'               => '36',
                    'prCtrID'               => $cntry,
                    'prStat'                => $stat,
                    'prActCode'             => '',
                    'prInvoiceDateFrom'     => $invoiceDateFrom,
                    'prInvoiceDateto'       => $fizHatIdo,
                    'prInvoiceRecurrence'   => $reszlet,
                    'old_db'                => 'clusers_eng',
                    'old_prID'              => '0',
                    'prHiType'              => $hiType
                ));
            }
        }*/

        if ($generate_prev_program) {
            // Jelenleg meg 2019-es programot is adunk!
            for ($i = 1; $i <= $userNumber; $i++) {
                $insert = $msh->insert('h_programs', array(
                    'prTypeID'              => $type,
                    'prVerID'               => $tomb['verID']-1,
                    'prLan'                 => $lan,
                    'prPass'                => $serial_prev,
                    'prSellDate'            => date("Y-m-d H:i:s"),
                    'prOrdNum'              => $prOrderNumber,
                    'prActDate'             => date("Y-m-d H:i:s"),
                    'prFizetve'             => '2050-01-01',
                    'prTime'                => date("Y-m-d H:i:s"),
                    'prLastMod'             => date("Y-m-d H:i:s"),
                    'prPrice'               => $alap_ar,
                    'prContact'             => '0',
                    'prHlNum'               => $kulcs,
                    'prManID'               => '36',
                    'prCtrID'               => $cntry,
                    'prStat'                => '1',
                    'prActCode'             => '',
                    'prInvoiceDateFrom'     => date('Y-m', time()),
                    'prInvoiceDateto'       => $fizHatIdo,
                    'prInvoiceRecurrence'   => $reszlet,
                    'old_db'                => 'clusers_eng',
                    'old_prID'              => '0',
                ));
            }
        }

        if ($kategoria == 'hardlock' || $kategoria == 'crossgrade') { // Eddig programokat tiltani
            $update = $msh->update("h_programs",array("prStat"=>'1'),"prHlNum = {$regi_kulcs}");
            $update = $msh->update("hardlock", array("hlNewHlNum"=>$kulcs), "hlNum = {$regi_kulcs}");
            $update = $msh->update("hardlock", array('hlDatePro' => date('Y-m-d', time()), 'hlStat' => 2), "hlNum = {$regi_kulcs}");
            $update = $msh->update("h_programs", array('prStat' => 1), "prHlNum = {$regi_kulcs}");
            $update = $msh->update("hardlock", array("hlOldHlNum"=>$regi_kulcs), "hlNum = {$kulcs}");
            $update = $msh->update("hardlock", array("hlStat"=>'1', "hlLan"=>'0', "hlDateIssue"=>$ma, "hlManID"=>'36', "hlCtrID"=>$cntry, "hlTime"=>date("Y-m-d H:i:s"), "hlUser"=>$user), "hlNum = {$kulcs}");

            $insert = $msh->insert("h_history", array(
                "hiHlNum"   => $regi_kulcs,
                "hiDate"    => date('Y-m-d', time()),
                "hiManID"   => 36,
                "hiTypeID"  => 5,
                "hiTime"    => date('Y-m-d H:i:s', time()),
                "hiInfo"    => "Web order: Új kulcs"
            ));
        }

        if (($kategoria == "upgrade" || $kategoria == "crossgrade" || $kategoria == "hardlock") && !empty($modules)) {
            // Ha van a module, akkor uj modulok generalasa kulccsal egyutt
            if (!empty($modules)) {
                $query = "SELECT `prHlNum`, `prID`, `prPass` FROM `h_programs` WHERE `prHlNum` = '{$kulcs}' ORDER BY `prID` DESC limit 1";
                $msh->query($query);
                $program_adatok = $msh->fetchNext();

                $prId       = $program_adatok['prID'];
                $password   = $program_adatok['prPass'];

                $msh->query("SELECT `mdID` FROM `p_modules` WHERE `mdPrHlNum` = '".$kulcs."'");
                $b = $msh->fetchAssoc();

                $email_m1_nev   = "";
                $email_m1_kulcs = "";
                $email_m2_nev   = "";
                $email_m2_kulcs = "";

                $e = 0;

                foreach ($b as $b) {
                    $r = (object)$b;
                    $e++;
                    $verz                   = $r->mdID;
                    $command                = PATH_CODEGEN." -Module " . $password . " " . $verz;
                    $ph                     = popen( $command, "r" ) or die( "A 'codegen' paranccsal nem veheto fel kapcsolat" );
                    $modcode                = fgets( $ph, 1024 );
                    pclose($ph);

                    $insert = $msh->insert('p_modules', array(
                        'mdID'          => $verz,
                        'mdPrID'        => $prId,
                        'mdPrHlNum'     => $uj_kulcs,
                        'mdCode'        => $modcode,
                        'mdDate'        => $ma,
                        'mdPrice'       => '0',
                        'mdInvNum'      => '',
                        'mdOrdNum'      => $prOrderNumber,
                        'mdIsPurchase'  =>'0',
                    ));

                    if ($verz == "2") $mod_nev = "Module - Terrain";
                    else $mod_nev = "Module - Rendering";

                    if ($e == 1) {
                        $email_m1_nev   = $mod_nev;
                        $email_m1_kulcs = $modcode;
                    } elseif ($e == 2){
                        $email_m2_nev   = $mod_nev;
                        $email_m2_kulcs = $modcode;
                    } else {
                        $email_m1_nev   = "";
                        $email_m1_kulcs = "";
                        $email_m2_nev   = "";
                        $email_m2_kulcs = "";
                    }
                }
            }
        }

        /*$insert = $msh->insert('h_history', array(
            'hiHlNum'   => $kulcs,
            'hiDate'    => date('Y-m-d'),
            'hiManID'   => 36,
            'hiTypeID'  => 3,
            'hiTime'    => date("Y-m-d H:i:s"),
            'hiInfo'    => "Web order, Aktiválás érvényessége: 2050-01-01",
        ));*/

        require_once("messages.php");
        switch ($kategoria) {
            case 'perp':
                if ($hl_prot == "Y") { // Ezt marciusban vissza kell kommentezni !!!!!! Ez az elozo evi programot is legeneralja!!! Eredeti: mysqli_real_escape_string($conn, $_GET['code_prev_version']) == "Y"
                    if (($serial_prev != "" && $serial_prev != null) || mysqli_real_escape_string($conn, $_GET['ver_2']) == "Y" || mysqli_real_escape_string($conn, $_GET['ver_3']) == "Y" || mysqli_real_escape_string($conn, $_GET['ver_4']) == "Y") {
                        if ($cntry == "43" || $cntry == "39" || $cntry == "37") $message = $message['teljes_hl17_np'];
                        else $message = $message['teljes_hl17'];
                    } else {
                        if ($cntry == "43" || $cntry == "39") $message = $message['teljes_hl_np'];
                        else $message = $message['teljes_hl'];
                    }
                }

                if ($hl_prot == "N") { // Ezt marciusban vissza kell kommentezni !!!!!! Ez az elozo evi programot is legeneralja!!! Eredeti: mysqli_real_escape_string($conn, $_GET['code_prev_version']) == "Y"
                    if (($serial_prev != "" && $serial_prev != null) || mysqli_real_escape_string($conn, $_GET['ver_2']) == "Y" || mysqli_real_escape_string($conn, $_GET['ver_3']) == "Y" || mysqli_real_escape_string($conn, $_GET['ver_4']) == "Y")
                        $message = $message['teljes_sw17'];
                    else
                        $message = $message['teljes_sw'];
                }
                break;

            case 'live':
                $message = $message['teljes_live'];
                break;

            case 'lt':
                $message = $message['teljes_live'];
                break;

            case 'upgrade':
                if ($email_m1_nev != "") $message = $message['upgrade_modulokkal'];
                else $message = $message['upgrade'];
                break;

            case 'crossgrade':
                $message = $message['upgrade'];
                break;

            case 'module':
                $message = $message['module'];
                break;

            case 'nonp':
                $message = $message['nonprofit'];
                break;

            case 'hardlock':
                if ($email_m1_nev != "") $message = $message['hardlock_modulokkal'];
                else $message = $message['hardlock'];
                break;
        }

        $to      = $kapcsolat['email'];
        $subject = 'ARCHLine.XP order: '.$ctryName['ctrNameEng'].' '.$prOrderNumber.' '.$prod;
        $headers = "Content-Type: text/html; charset=utf-8\r\n";

        if ($cntry == "37") $headers .= 'Cc: mate.nagy@cadline.hu' . "\r\n";
        else $headers .= 'Cc: office@cadline.hu' . "\r\n";

        if ($kapcsolat['sub_email'] != null && $kapcsolat['sub_email'] != "") $headers .= 'Bcc: '.$kapcsolat['sub_email'] . "\r\n";

        mail($to, $subject, $message, $headers);

        $eredmeny['sikeres'] = "<b>Thank You for Your Order.<b><br />
            We have accepted your online purchase order.
            Once processed, invoice will be sent for your e-mail address.
            Please allow 1 working day for your order to be processed.
            <br /><br />
            <a href='order.php'>Continue</a>.";

        if ($isInvoice && $price != 0) { // Non-profit programnal nem kell szamlat generalni
            $live_price = 100;
            if (strpos($program, "Including LIVE")) $price = $price - $live_price;

            if (is_numeric($afa_key) && $afa_key > 0) { // Default afa
                $vat_amount_live        = $live_price  * $afa; //csak Afa osszege
                $brut_amount_live       = $live_price  * ($afa+1); // Brutto teljes ar
                $vat_amount_otheritem   = $price * $afa;
                $brut_amount_otheritem  = $price * ($afa+1);
                $vat_amount_hardlock    = $hardlock_price["nettó"] * $afa;
                $brut_amount_hardlock   = $hardlock_price["nettó"] * ($afa+1);
            } else {
                $vat_amount_live        = 0; //csak Afa osszege
                $brut_amount_live       = $live_price; // Brutto teljes ar
                $vat_amount_otheritem   = 0;
                $brut_amount_otheritem  = $price;
                $vat_amount_hardlock    = 0;
                $brut_amount_hardlock   = $hardlock_price["nettó"];
            }

            if ($cntry == 33) $comment = "Client: ".$u_name." - "." Serial: ".$kulcs." order ".$prOrderNumber;
            else $comment = $kulcs." order ".$prOrderNumber;

            $item = new InvoiceItem($termek["megnevezés"], $price, 1.0, $termek["egység"], $afa_key);
            $item->setNetPrice($price);
            $item->setVatAmount($vat_amount_otheritem);
            $item->setGrossAmount($brut_amount_otheritem);
            $item->setComment($comment);

            $itemLedger = new InvoiceItemLedger('', '', strval($termek["árbevétel_főkönyvi_szám"]), '');
            $item->setLedgerData($itemLedger);

            $invoice->addItem($item);

            if ($hl_prot == "Y") {
                if ($afa_key == "EUK") $revenueLedgerNumber = 931;
                else $revenueLedgerNumber = 9313;

                $item = new InvoiceItem($prod_prefix." ARCHLine.XP Hardlock", $hardlock_price["nettó"], 1.0, $termek["egység"], $afa_key);
                $item->setComment($kulcs." order ".$prOrderNumber);
                $item->setNetPrice($hardlock_price["nettó"]);
                $item->setVatAmount($vat_amount_hardlock);
                $item->setGrossAmount($brut_amount_hardlock);

                $itemLedger = new InvoiceItemLedger('', '', strval($revenueLedgerNumber), '');
                $item->setLedgerData($itemLedger);

                $invoice->addItem($item);
            }

            if (mysqli_real_escape_string($conn, $_GET['inclLive']) == "Y" || strpos($program, "Including LIVE") == TRUE) {
                if ($afa_key == "EUK") $revenueLedgerNumber = 931;
                else $revenueLedgerNumber = 9312;

                $item = new InvoiceItem($prod_prefix." ARCHLine.XP LIVE License", $live_price, 1.0, $termek["egység"], $afa_key);
                $item->setComment($kulcs_live." order ".$prOrderNumber);
                $item->setNetPrice($live_price);
                $item->setVatAmount($vat_amount_live);
                $item->setGrossAmount($brut_amount_live);

                $itemLedger = new InvoiceItemLedger('', '', strval($revenueLedgerNumber), '');
                $item->setLedgerData($itemLedger);

                $invoice->addItem($item);
            }

            $result = $agent->generateInvoice($invoice);

            if ($result->isSuccess()) { // Az invoice mezo alapertelmezetten 0, ha sikeres a szamla generalas, updateljuk 1-re
                $query = "UPDATE o_orders SET invoice = 1 WHERE country = {$cntry} AND o_orders.order = '{$prOrderNumber}'";
                $msh->query($query);
            }
        }

        $query = "SELECT invoice FROM o_orders WHERE country = {$cntry} AND o_orders.order = '{$prOrderNumber}' ORDER BY id desc";
        $msh->query($query);
        $inv = $msh->fetchNext();

        if ($isInvoice && $price != 0 && $inv['invoice'] != 1) { // Nem sikerult a szamlat legeneralni, emailt kuldunk az office-nak
            $message  = "";
            $message .= "Email: ".$kapcsolat['email']."<br/>";
            $message .= "Orders: <br/>";
            $message .= "Order number: {$prOrderNumber} <br/>";
            $message .= "Program: {$program}";

            $to      = "office@cadline.hu";
            $subject = "Számlagenerálás hiba";
            $headers = "Content-Type: text/html; charset=utf-8\r\n";
            mail($to, $subject, $message, $headers);

            $eredmeny['hiba'] = "Order accepted, but error at making invoice! Please contact office@cadline.hu.
                <br /><br />
                <a href='javascript:location.reload()'>Continue</a>.";
            echo json_encode($eredmeny);
            return false;
        }
    } else {
        $eredmeny['hiba'] = "You've reached your daily limit for orders. Please try it again tomorrow or contact <a href='mailto:office@cadline.hu'>office@cadline.hu</a>
            <br /><br />
            <a href='javascript:location.reload()'>Continue</a>.";
    }
}
echo json_encode($eredmeny);

function IsSoftwareKey($serial = "")
{
    if ($serial == "") return false;

    $ph         = popen(PATH_CODEGEN." -IsSoftwareKey ".$serial, "r") or die("A 'codegen' paranccsal nem veheto fel kapcsolat");
    $szoftveres = fgets($ph, 1024);
    pclose($ph);

    return ($szoftveres == 'true');
}

function tryToAlloc($min = 990001, $max = 997000)
{
    $config['db_host'] = 'localhost';
    $config['db_user'] = 'cadline';
    $config['db_pass'] = 'Shea6hoo';
    $config['db_name'] = 'cl_hlusers';

    $msh = new hivasok();
    $msh->init($config['db_host'], $config['db_name'], $config['db_user'], $config['db_pass']);
    $conn = new mysqli($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);

    $ret = 0;
    if ((int)$min == 0 || (int)$max == 0) return $ret;

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

    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;
}
