<?php
require '/var/www/hosting/archlinexp.com/partners/public/order/hivasok.php';
require '/var/www/hosting/archlinexp.com/partners/public/order/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\Document\Proforma;
use \SzamlaAgent\Item\ProformaItem;

class Mpay extends Model
{
    function __construct()
    {
        parent::__construct();

        $this->load->library('PasswordHash');
        $this->load->library('Product');
    }

    function login($username, $password)
    {
        $user = $this->db->query("SELECT nUserID, password FROM www_archline_hu.jml_users WHERE username = '{$username}' OR email = '{$username}'")->row();

        if (empty($user))
            return false;

        $phpass = new PasswordHash(10, true);
        $ok     = $phpass->CheckPassword($password, $user->password);

        if (!$ok)
            return false;

        return $user;
    }

    function getCRMprofile($nUserID)
    {
        $query = "SELECT nUserID AS nUserID, strInvoiceName AS name, strCompany AS company, strInvoiceZip AS zip,
            strInvoiceCity AS city, strInvoiceEMail AS email, strTaxNumber AS taxNumber,
            strEUTaxNumber AS euTaxNumber, strInvoiceAddress AS street, nInvoiceCtrID AS ctrID
            FROM cl_hlusers.users
            WHERE nUserID = {$nUserID}";
        $crm_user = $this->db->query($query)->row();

        return $crm_user;
    }

    function getCountries()
    {
        $query = "SELECT ctrID, ctrName
            FROM cl_hlusers.countries
            WHERE show_u = 1 AND id NOT IN (11, 442, 444, 445, 446, 448)
            ORDER BY ctrName";
        $countries = $this->db->query($query)->result();

        return $countries;
    }

    function getMaintenanceAgreement($type, $productID)
    {
        switch ($type) {
            case 2:
                $moduleID = 493;
                break;
            case 3:
                $moduleID = 494;
                break;
            case 4:
                $moduleID = 499;
                break;
            default:
                $moduleID = 492;
                break;
        }

        if ($productID == 1823)
            $moduleID = 508;

        $query = "SELECT id, content
            FROM www_archline_hu.jml_modules
            WHERE id = {$moduleID}";
        $license = $this->db->query($query)->row();

        return $license->content;
    }

    function getLicenseAgreement($category = '')
    {
        $id = $category == 'live' ? 600 : 510;

        $query = "SELECT id, content
            FROM www_archline_hu.jml_modules
            WHERE id = {$id}";
        $license = $this->db->query($query)->row();

        return $license;
    }

    function getServiceAgreement($productID)
    {
        $moduleID = $productID == 1823 ? 498 : 498;

        $query = "SELECT id, content
            FROM www_archline_hu.jml_modules
            WHERE id = 498";
        $license = $this->db->query($query)->row();

        return $license;
    }

    function getPrivacyPolicy()
    {
        $query = "SELECT introtext FROM www_archline_hu.jml_content
            WHERE id = 584";
        $policy = $this->db->query($query)->row();

        return $policy->introtext;
    }

    function getInvoiceName($id)
    {
        $query = "SELECT t.megnevezés AS name
            FROM szamla_agent.termekek t
            LEFT JOIN szamla_agent.web_product wp ON wp.product_id = t.id
            WHERE wp.web_id = {$id}";
        $product = $this->db->query($query)->row();

        return $product->name;
    }

    function getProduct($id)
    {
        $query = "SELECT * FROM cl_hlusers.o_products
            WHERE id = {$id} AND lang = 36 AND seq > 0";
        $product = $this->db->query($query)->row();

        if ($product->akcio != '' && $product->akcio != null && date('Y-m-d') <= $product->ackio_date)
            $product->price = $product->akcio;
        else
            $product->price = $product->huf;

        return $product;
    }

    function getBillingInformation($serial)
    {
        $hlNum = substr($serial, 0, 6);

        $query = "SELECT u.nUserID AS userID, u.strInvoiceName AS name, u.strInvoiceEMail AS email, strInvoiceZip AS zip, strInvoiceCity AS city, 
                u.strInvoiceAddress AS street, u.strTaxNumber AS strTaxNumber
            FROM cl_hlusers.hardlock h
            LEFT JOIN cl_hlusers.users u ON u.nUserID = h.hlUser
            WHERE h.hlNum = {$hlNum}";

        return $this->db->query($query)->row();
    }

    function getVersionDescription($ver8and9)
    {
        $query = "SELECT * FROM cl_hlusers.p_versions WHERE verPassword8and9 = {$ver8and9}";

        return $this->db->query($query)->row();
    }

    function getCurrentVersion($product = 'perp', $type = 8, $productID)
    {
        if ($product == 'live' || $type == 76 || $type == 'L' || $productID == 1299)
            $query = "SELECT * FROM cl_hlusers.p_versions WHERE verID = 23";
        else
            $query = "SELECT * FROM cl_hlusers.p_versions WHERE currentVer = 0 OR currentVer = 1";

        // $query = "SELECT * FROM cl_hlusers.p_versions WHERE verID = 23";

        // Frissites
        if ($productID == '1545' || $productID == '1546' || $productID == '1547' || $productID == '1552')
            $query = "SELECT * FROM cl_hlusers.p_versions WHERE verID = 25";

        // Karbantartas
        if ($productID == '1297' || $productID == '1298' || $productID == '1300' || $productID == '1551' || $productID == '1823')
            $query = "SELECT * FROM cl_hlusers.p_versions WHERE verID = 25";

        $curr_ver = $this->db->query($query)->row();

        return $curr_ver;
    }

    function createUserHistory($nUserID, $contact, $kategoria, $price, $nTopicID, $info = '', $o_type = 0, $couponPrice = 0)
    {
        $history = array(
            'nTopicID'      => $nTopicID,
            'nUserID'       => $nUserID,
            'strPlace'      => 'web',
            'nManagerID'    => 36,
            'insertDate'    => date('Y-m-d H:i:s'),
            'dateEvent'     => date('Y-m-d')
        );

        switch ($contact) {
            case 11: // Licensz - bérlés
                if ($kategoria == 'live')
                    $history['strInfo'] = 'LIVE Licenc ';
                else
                    $history['strInfo'] = 'Licenc ';

                if ($o_type == 13)
                    $history['strInfo'] .= '2 havi részletben. ' . $price . ' + Áfa';
                elseif ($o_type == 12)
                    $history['strInfo'] .= '3 havi részletben. ' . $price . ' + Áfa';
                elseif ($o_type == 11)
                    $history['strInfo'] .= '4 havi részletben. ' . $price . ' + Áfa';
                else
                    $history['strInfo'] .= '5 havi részletben. ' . $price . ' + Áfa';
                break;

            case 4: // Frissités
                $history['strInfo'] = 'Frissítés. ' . $price . ' + Áfa';
                break;
            case 3: // Licensz - részlet
                if ($kategoria == 'live')
                    $history['strInfo'] = 'LIVE Licenc 3 havi részletben. ' . $price . ' + Áfa';
                else
                    $history['strInfo'] = 'Licenc 4 havi részletben. ' . $price . ' + Áfa';
                break;

            case 2: // Karbantartási szerződés
                if ($couponPrice > 0) {
                    $history['strInfo'] = 'Karbantartási szerződés. ' . $price . ' - ' . $couponPrice . ' + Áfa';
                } else {
                    $history['strInfo'] = 'Karbantartási szerződés. ' . $price . ' + Áfa';
                }
                break;

            case 1: // Előfizetői
                $history['strInfo'] = 'Előfizetés. ' . $price . ' + Áfa';
                break;

            case 0: // Licensz - egy összeg
                if ($kategoria == 'live') {
                    if ($couponPrice > 0) {
                        $history['strInfo'] = 'LIVE Licenc egy összeg. ' . $price . ' - ' . $couponPrice . ' + Áfa';
                    } else {
                        $history['strInfo'] = 'LIVE Licenc egy összeg. ' . $price . ' + Áfa';
                    }
                } else {
                    if ($couponPrice > 0) {
                        $history['strInfo'] = 'Licenc egy összeg. ' . $price . ' - ' . $couponPrice . ' + Áfa';
                    } else {
                        $history['strInfo'] = 'Licenc egy összeg. ' . $price . ' + Áfa';
                    }
                }
                break;

            default:
                break;
        }

        $history['strInfo'] .= ' ' . $info;

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

    function getPayment($contact)
    {
        $payment    = new stdClass();
        $date       = new DateTime();

        switch ($contact) {
            case 3: // Licensz - részlet
                if ($date->format('d') <= 15)
                    $date->modify('+1 months');
                else
                    $date->modify('+2 months');

                $prInvoiceDateFrom  = $date->format('Y-m');
                $prInvoiceDateTo    = $date->modify('+2 months');
                $prInvoiceDateTo    = $date->format('Y-m');

                $payment->prInvoiceDateFrom     = $prInvoiceDateFrom;
                $payment->prInvoiceDateTo       = $prInvoiceDateTo;
                $payment->prInvoiceRecurrence   = 1;
                break;

            case 1: // Előfizetői
                if ($date->format('d') < 15)
                    $date->modify('+2 months');
                else
                    $date->modify('+3 months');

                $prInvoiceDateFrom  = $date->format('Y-m');
                $prInvoiceDateTo    = $date->modify('+20 months');
                $prInvoiceDateTo    = $date->format('Y-m');

                $payment->prInvoiceDateFrom = $prInvoiceDateFrom;
                $payment->prInvoiceDateTo = $prInvoiceDateTo;
                $payment->prInvoiceRecurrence = 1;
                break;

            default:
                break;
        }

        return $payment;
    }

    function createHardlock($prod, $cntry)
    {
        $kulcs = (string)$this->tryToAlloc(($cntry * 10000) + 1, ($cntry * 10000) + 9999);

        $hardlock = array(
            'hlNum'         => $kulcs,
            'hlCtrID'       => 36,
            'hlLan'         => 0,
            'hlStat'        => 0,
            'hlManID'       => 36,
            'product_id'    => $prod
        );

        $this->db->insert('cl_hlusers.hardlock', $hardlock);

        return $kulcs;
    }

    function createProgram($password, $verID, $typeID, $price, $contact, $notes, $orderNum)
    {
        $payment = $this->getPayment($contact);

        $programs = array(
            'prTypeID'              => $typeID,
            'prVerID'               => $verID,
            'prLan'                 => 0,
            'prPass'                => $password,
            'prPrice'               => $price,
            'prHlNum'               => substr($password, 0, 6),
            'prContact'             => $contact,
            'prCtrID'               => 36,
            'prManID'               => 36,
            'prStat'                => 0,
            'prHiType'              => 1,
            'twtw'                  => 1,
            'prSellDate'            => date('Y-m-d'),
            'prInfo'                => $notes,
            'prOrdNum'              => $orderNum,
            'prInvoiceDateFrom'     => $payment->prInvoiceDateFrom,
            'prInvoiceDateTo'       => $payment->prInvoiceDateTo,
            'prInvoiceRecurrence'   => $payment->prInvoiceRecurrence
        );

        $history = array(
            'hiHlNum'   => substr($password, 0, 6),
            'hiDate'    => date('Y-m-d'),
            'hiManID'   => 36,
            'hiTypeID'  => 2,
            'hiTime'    => date('Y-m-d H:i:s')
        );

        $this->db->insert('cl_hlusers.h_programs', $programs);
        $this->db->insert('cl_hlusers.h_history', $history);
    }

    function getEventID($contact, $kategoria)
    {
        $eventID = '';

        switch ($contact) {
            case 3: // Licensz - részlet
                if ($kategoria == 'live')
                    $eventID = 376;
                else
                    $eventID = 331;
                break;

            case 1: // Előfizetői
                $eventID = 24;
                break;

            case 0: // Licensz - egy összeg
                if ($kategoria == 'live')
                    $eventID = 376;
                else
                    $eventID = 331;
                break;

            default:
                break;
        }

        return $eventID;
    }

    function generatePassword($nUserID, $productID, &$serial, &$price, $notes, &$orderNum, $product)
    {
        if ($product->kategoria == 'live')
            $cntry = 36;
        else
            $cntry = 95;

        $curr_ver   = $this->getCurrentVersion($product->kategoria, '8', $productID);
        $version    = $curr_ver->verCode;
        $type       = $product->type == 76 ? "L" : 8;
        $prod       = $product->type == 76 ? 2 : 1;
        $lan        = "0";

        $query = "SELECT hlNum
            FROM cl_hlusers.hardlock
            WHERE hlNum LIKE '{$cntry}%' AND (hlInfo IS NULL OR hlInfo = '') AND hlStat = 0 AND
            (hlUser IS NULL OR hlUser = '') AND hlLan = 0";
        $hardlock = $this->db->query($query)->row();

        /*if (!empty($hardlock))
            $kulcs = $hardlock->hlNum;
        else
            $kulcs = (string)$this->createHardlock($prod, $cntry);*/

        $kulcs = (string)$this->createHardlock($prod, $cntry);

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

        $afa_key            = "27";
        $afa                = $afa_key / 100;
        $brut_amount_item   = $product->price * ($afa + 1);
        $price              = $brut_amount_item;
        //$orderNum           = $this->getOrderNumber(36);

        $this->createProgram($serial, $curr_ver->verID, $product->type, $brut_amount_item, $product->cont_id, $notes, $orderNum);

        $query = "UPDATE cl_hlusers.hardlock
            SET hlUser = '{$nUserID}', hlStat = 1, product_id = {$prod}
            WHERE hlNum = '{$kulcs}'";
        $this->db->query($query);

        $license = $this->getLicenseAgreement();

        $this->uploadTermsAndConditionsPDF($curr_ver->year, $nUserID, $license->id, $product->cont_id);
    }

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

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

    function getCoupon($coupon, $prodId = 0)
    {
        $result                     = array();
        $result['error']            = false;
        $result['error_message']    = '';

        $coupon = $this->db->query("SELECT * FROM `cl_hlusers`.`al_coupons` WHERE `coupon` = '{$coupon}' LIMIT 1")->row();
        if (empty($coupon)) {
            $result['error']            = true;
            $result['error_message']    = 'Érvénytelen kupon.';

            return $result;
        }

        if (date('Y-m-d') > $coupon->expire_date) {
            $result['error']            = true;
            $result['error_message']    = 'Ez a kupon lejárt.';

            return $result;
        }

        if ($coupon->used == 1) {
            $result['error']            = true;
            $result['error_message']    = 'Ezt a kupont már használták';

            return $result;
        }

        $product    = $this->getProduct($prodId);
        $price      = $product->price - $coupon->price;

        /*
        ha a price kisebb, mint 1000, akkor a kupont osszuk el 2-vel és a frissitésből és a karbantartásiból vegyük le
        */
        if ($price < 1000) {
            $result['error']            = true;
            $result['error_message']    = 'Hibás kupon, kérem forduljon az értékesítőhöz';

            $this->sendErrorMail($coupon->coupon, $coupon->price, $product->termek);

            return $result;
        }

        if ($product->seq == 2 && $product->o_type != 1) {
            $maintenance        = $this->getProduct(1297);
            $maintenancePrice   = $maintenance->price;
            //$maintenancePrice   = 164000;

            $updatePrice = $price - $maintenancePrice;

            if ($updatePrice < 1000) {
                $couponHalfPrice    = (int)$coupon->price / 2;
                $updatePrice        = $product->price - $maintenancePrice;

                if (((int)($updatePrice - $couponHalfPrice) < 1000) || ((int)($maintenancePrice - $couponHalfPrice) < 1000)) {
                    $result['error']            = true;
                    $result['error_message']    = 'Hibás kupon, kérem forduljon az értékesítőhöz';

                    $this->sendErrorMail($coupon->coupon, $coupon->price, $product->termek);

                    return $result;
                }
            }
        }

        $result['coupon_price'] = (int)$coupon->price;

        return $result;
    }

    function sendErrorMail($coupon, $couponPrice, $productName)
    {
        $headers    = "Content-Type: text/html; charset=utf-8\r\n";
        $subject    = "Hibás kupon - " . $coupon;
        $message    = 'Hibás kupon: <br/>';
        $message    .= '<ul>';
        $message    .= '<li>Kupon: ' . $coupon . '</li>';
        $message    .= '<li>Kupon összege: ' . $couponPrice . '</li>';
        $message    .= '<li>Termék neve: ' . $productName . '</li>';
        $message    .= '</ul>';

        mail('info@cadline.hu', $subject, $message, $headers);
    }

    function changeCoupon($coupon, $nUserID = 0)
    {
        $updateUsedQuery = "UPDATE cl_hlusers.al_coupons
            SET used = 1
            WHERE coupon = '{$coupon}' LIMIT 1;";
        $this->db->query($updateUsedQuery);

        if ($nUserID > 0) {
            $updateUsedByQuery = "UPDATE cl_hlusers.al_coupons
                SET used_by = {$nUserID}
                WHERE coupon = '{$coupon}' LIMIT 1;";
            $this->db->query($updateUsedByQuery);

            $userHistory = $this->db->query("SELECT nEventID, strInfo FROM cl_hlusers.u_history WHERE nUserID = {$nUserID} AND nTopicID = 78 ORDER BY nEventID DESC LIMIT 1")->row();
            $newInfo = $userHistory->strInfo . ' (' . $coupon . ')';

            $updateHistoryQuery = "UPDATE cl_hlusers.u_history
                SET strInfo = '{$newInfo}'
                WHERE nEventID = " . $userHistory->nEventID . ";";
            $this->db->query($updateHistoryQuery);
        }
    }

    function getOrderNumber($cntry)
    {
        $order          = $this->db->query("SELECT `order` FROM `cl_hlusers`.`o_orders` WHERE `country` = '{$cntry}' ORDER BY `id` DESC limit 1")->row();
        $orderNumber    = $order->order;
        $kezdo          = strpos($orderNumber, "-") + 1;
        $veg            = strpos($orderNumber, "/") - 2;
        $szam           = (int)substr($orderNumber, $kezdo, $veg) + 1;
        $prOrderNumber  = "E-" . $szam . "/" . date("Y");

        return $prOrderNumber;
    }

    function createOrder($prod_name, $orderNumber, $u_name, $email, $cntry, $serial, $price, $info)
    {
        $order = array(
            'software'      => $prod_name,
            'ip'            => $_SERVER['REMOTE_ADDR'],
            'country'       => $cntry,
            'date'          => date('Y-m-d'),
            'user_name'     => $u_name,
            'user_email'    => $email,
            'order'         => $orderNumber,
            'output_key'    => $serial,
            'price'         => $price,
            'info'          => $info
        );

        $this->db->insert('cl_hlusers.o_orders', $order);
    }

    function updateOrder($orderNum, $password)
    {
        if ($orderNum != '') {
            $updateQuery = "UPDATE cl_hlusers.o_orders
                SET output_key = '{$password}'
                WHERE order = '{$orderNum}' AND country = 36";
            $this->db->query($updateQuery);
        }
    }

    function updateUserStatus($nUserID, $nUserStatus)
    {
        $selectQuery = "SELECT nUserStatus FROM cl_hlusers.users WHERE nUserID = {$nUserID}";
        $user = $this->db->query($selectQuery)->row();

        $oldStatus = array(
            'nUserID'       => $nUserID,
            'val'           => $user->nUserStatus,
            'changeDate'    => date('Y-m-d H:i:s'),
            'nManagerID'    => 36
        );

        $this->db->insert('cl_hlusers.u_userstatus_history', $oldStatus);

        $updateQuery = "UPDATE cl_hlusers.users
            SET nUserStatus = '{$nUserStatus}'
            WHERE nUserID = '{$nUserID}'";
        $this->db->query($updateQuery);
    }

    function sendCustomEmail($email, $productName, $contId)
    {
        $message = '<html><body style="font-family: Arial, Helvetica, sans-serif;">
            <b>Kedves Vásárlónk!</b> <br/>
            Köszönjük a megrendelést, az elektronikus számlát elküldtük. <br/>
            A számla összegének beérkezése után küldjük a szoftver telepítési útmutatót. <br/><br/>

            <b>Termék:</b> ' . $productName . '<br/><br/>
            
            Üdvözlettel: <br/>
            <b>CadLine Kft.</b>
            </html></body>';

        $termek = $contId == 4 ? 'ARCHLine.XP frissítés' : 'ARCHLine.XP';

        $mail = new PHPMailer;
        $mail->IsSMTP();
        $mail->Host = 'localhost';
        $mail->CharSet  = 'UTF-8';
        $mail->SMTPAuth = true;
        $mail->Username = 'www.smtp@cadline.hu';
        $mail->Password = 'Chieng0t';
        $mail->WordWrap = 50;
        $mail->From = 'info@cadline.hu';
        $mail->FromName = 'www.archline.hu';
        $mail->AddAddress($email);
        $mail->IsHTML(true);
        $mail->Subject = 'Sikeres megrendelés - ' . $termek;
        $mail->Body = $message;
        $mail->Send();
    }

    function sendEmail($user, $orderNum, $product, $instalments, $couponPrice = 0)
    {
        $prod_name  = $this->getInvoiceName($product->id);
        $price      = $product->price;
        $afa_key    = "27";
        $afa        = $afa_key / 100;
        $inv_prefix = "HUF";

        $currentDate = new DateTime(date('Y-m-d'));
        $currentDate->modify("+8 day");
        $paymentDue = $currentDate->format('Y-m-d');

        if ($product->akcio != '' && $product->akcio != null && date('Y-m-d') <= $product->ackio_date && $paymentDue > $product->ackio_date) {
            $paymentDue = $product->ackio_date;
        }

        if ($user->email == 'nagy.mate960814@gmail.com')
            $key = 'kjjyxaexnidzkjek22c4nidzkjmn3g8dnidzkj6ip2'; // Teszt Kulcs
        else
            $key = '3i73vj72wt7h3ig78wrawt7h3ik5batswt7h3inhzw'; // CADLine kulcs

        $agent = SzamlaAgentAPI::create($key, false, Log::LOG_LEVEL_OFF);
        $agent->setXmlFileSave(false);

        if ($user->email == 'nagy.mate960814@gmail.com')
            $invoice = new Invoice(Invoice::INVOICE_TYPE_P_INVOICE); //Teszt Szamla
        else
            $invoice = new Invoice(Invoice::INVOICE_TYPE_E_INVOICE); // Elektronikus Szamla

        $header = $invoice->getHeader();
        $header->setPaymentMethod(Invoice::PAYMENT_METHOD_TRANSFER);
        $header->setCurrency(Currency::CURRENCY_FT);
        $header->setLanguage(Language::LANGUAGE_HU);
        $header->setPaymentDue($paymentDue);
        $header->setOrderNumber($orderNum);
        $header->setComment("*Kérjük, utaláskor a közlemény rovatban KIZÁRÓLAG a számlaszámot tüntesse fel! (pl.: E-HUF-" . date('Y') . "-xxxx)

            A sorozatszámot a CADLINE a vonatkozó számla kiegyenlítése után teszi elérhetővé.
            
            Számla adatokat a kiállítástól számítva 8 napon belül áll módunkban javítani");

        if ($user->email != 'nagy.mate960814@gmail.com')
            $header->setPrefix('HUF');

        $header->setEuVat(false);

        $seller = new Seller('K&H Bank', '10200885-32613151-00000000');
        $seller->setEmailReplyTo('office@cadline.hu');
        $seller->setEmailSubject('Számlaértesítő - CadLine Kft.');
        $seller->setEmailContent('Tisztelt ' . $user->name . ',

            Köszönjük megrendelését, mellékelten küldjük aktuális számláját.

            A vásárláskor elfogadott Általános szerződési feltételeket itt tudja megtekinteni és letölteni https://www.archline.hu/szamlazasi-adatok. Későbbiek folyamán szüksége lenne rá a weboldalon a Felhasználói Adatlapon a „Számlázás és szerződések" menüpont alatt megtalálhatja.

            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.

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

        $buyer = new Buyer($user->name, strval($user->postcode), $user->city, $user->address);

        if ($user->tax_number != '') {
            $buyer->setTaxNumber(strval($user->tax_number));
            $tax = TaxPayer::TAXPAYER_HAS_TAXNUMBER;
        } else {
            $tax = TaxPayer::TAXPAYER_NO_TAXNUMBER;
        }

        $buyer->setTaxPayer($tax);
        $buyer->setEmail($user->email);
        $buyer->setSendEmail(true);
        $invoice->setBuyer($buyer);

        if ($couponPrice > 0 && ($product->kategoria == 'perp' || $product->kategoria == 'live') && $product->cont_id == 0) {
            $price = $price - $couponPrice;
        }

        $vat_amount_item   = $price * $afa;
        $brut_amount_item  = $price * ($afa + 1);

        $ledger_number = $product->cont_id == 1 ? 9151 : 9111;

        $prodName = '';
        $inst = Product::getInstalment($product->id, $product->seq, $product->o_type, $product->ackio_date);

        $unit = 'db';
        $comment = '';

        if ($product->seq == 2 && $product->o_type != 1) {
            $maintenance        = $this->getProduct(1297);
            $maintenancePrice   = $maintenance->price;
            //$maintenancePrice   = 164000;

            if ($instalments == 'true') {
                $maintenancePrice = $inst == 3 ? 49300 : $maintenancePrice / $inst;
                $price = $price / $inst;

                if ($inst >= 3 && $product->akcio != '' && $product->akcio != null && date('Y-m-d') <= $product->ackio_date) {
                    if ($product->id == 1298) {
                        $maintenancePrice = 54667;
                    }

                    if ($product->id == 1300) {
                        $maintenancePrice = 41000;
                    }

                    if ($product->id == 1551) {
                        $maintenancePrice = 41000;
                    }
                }
            }

            $updatePrice = round($price - $maintenancePrice);

            if ($couponPrice > 0 && $instalments != 'true') {
                $updatePrice = $updatePrice - $couponPrice;

                if ($updatePrice < 1000) {
                    $couponHalfPrice    = (int)$couponPrice / 2;
                    $updatePrice        = round($price - $maintenancePrice) - $couponHalfPrice;
                    $maintenancePrice   = (int)$maintenancePrice - $couponHalfPrice;
                }
            }

            $brut_amount_item   = $updatePrice * ($afa + 1);
            $vat_amount_item    = $updatePrice * $afa;
            $price              = $updatePrice;

            $brutMaintenancePrice   = $maintenancePrice * ($afa + 1);
            $vatMaintenance         = $maintenancePrice * $afa;

            $prodName = 'ARCHLine.XP frissítés';

            /*if ($product->id == 1551 && $instalments == 'true') {
                $prodName = 'ARCHLine.XP frissítés első részlet';
            }*/
        } elseif ($product->kategoria == 'upgrade' && $product->seq == 1) {
            $prodName = $product->type == 76 ? 'ARCHLine.XP LIVE frissítés' : 'ARCHLine.XP frissítés';
        } else {
            $prodName = $product->termek;

            if ($product->seq == 2 && $product->o_type == 1) {
                if ($instalments == 'true') {
                    $price = $price / $inst;
                    $prodName = 'ARCHLine.XP havi karbantartási díj';
                    $comment = 'részlet';
                } else {
                    $prodName = 'ARCHLine.XP egyösszegű karbantartási díj';

                    if ($couponPrice > 0) {
                        $price = $price - $couponPrice;
                    }
                }

                // Torolni
                /*if ($instalments == 'true' && $product->id == '1823')
                    $price = 49000;*/

                $vat_amount_item   = $price * $afa;
                $brut_amount_item  = $price * ($afa + 1);

                $ledger_number = 9131;
            }
        }

        if ($product->cont_id == 11) {
            if ($product->type == 8)
                $prodName = 'ARCHLine.XP licenc bérleti díj';
            else
                $prodName = 'ARCHLine.XP LIVE licenc bérleti díj';

            $ledger_number = 9141;
            $unit = 'hó';
        }

        if ($product->id == 721) {
            $prodName = 'ARCHLine.XP licenc';
        }

        if ($product->id == 251) {
            $prodName = 'ARCHLine.XP LIVE licenc';
        }

        /*if ($product->id == 290 || $product->id == 1797)
            $unit = 'hó';*/

        $unitPrice = $price;
        $quantity = 1.0;
        if ($product->id == 290) {
            $quantity = 2.0;
            $unitPrice = $price / 2;
            $unit = 'hó';
            $prodName = 'ARCHLine.XP előfizetési díj';
            $comment = 'ARCHLine.XP 12 HAVI ELŐFIZETÉS';
        }

        $item = new InvoiceItem($prodName, $unitPrice, $quantity, $unit, $afa_key);
        $item->setNetPrice($price);
        $item->setVatAmount($vat_amount_item);
        $item->setGrossAmount($brut_amount_item);

        if ($comment != '')
            $item->setComment($comment);

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

        $invoice->addItem($item);

        if ($product->seq == 2 && $product->o_type != 1) {
            if ($instalments == 'true')
                $maintName = 'ARCHLine.XP havi karbantartási díj';
            else
                $maintName = 'ARCHLine.XP egyösszegű karbantartási díj';

            $item = new InvoiceItem($maintName, $maintenancePrice, 1.0, "db", $afa_key);
            $item->setNetPrice($maintenancePrice);
            $item->setVatAmount($vatMaintenance);
            $item->setGrossAmount($brutMaintenancePrice);

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

            $invoice->addItem($item);
        }

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

        $invoice                    = array();
        $invoice['nUserID']         = $user->userID;
        $invoice['documentNumber']  = $invNumber;
        $invoice['product']         = $prodName;
        $invoice['invoiceCreated']  = date('Y-m-d');
        $invoice['amount']          = $brut_amount_item;

        $this->db->insert('cl_hlusers.invoices', $invoice);

        $headers    = "Content-Type: text/html; charset=utf-8\r\n";
        $subject    = "Megrendelés: " . $product->termek;
        $message    = 'Az alábbi megrendelés érkezett: <br/>';
        $message    .= '<ul>';
        $message    .= '<li>Vásárló neve: <a href="https://crm.cadline.hu/hu/users/show/' . $user->userID . '">' . $user->name . '</a></li>';
        $message    .= '<li>Vásárló email címe: ' . $user->email . '</li>';
        $message    .= '<li>Termék neve: ' . $product->termek . '</li>';
        $message    .= '<li>Számlaszám: ' . $invNumber . '</li>';
        $message    .= '</ul>';

        if ($user->email != 'nagy.mate960814@gmail.com')
            mail('office@cadline.hu', $subject, $message, $headers);
    }

    function checkPassword($serial, $type, $o_type, $currentVersion)
    {
        $error = array();

        if (substr($serial, 0, 2) != 36 && substr($serial, 0, 2) != 95) {
            $error['error'] = true;
            $error['msg']   = 'Érvénytelen mező: Sorozatszám';
            return $error;
        }

        $exist = $this->db->query("SELECT prID, prVerID FROM cl_hlusers.h_programs WHERE prPass = '{$serial}' LIMIT 1")->row();
        if ($serial == '' || empty($exist)) {
            $error['error'] = true;
            $error['msg']   = 'Érvénytelen mező: Sorozatszám';
            return $error;
        }

        $productType = $type == 76 ? 'L' : $type;
        if ((substr($serial, 6, 1) == '2' || substr($serial, 6, 1) == '6') && $productType == '8') {
            $productType = substr($serial, 6, 1);
        }

        if (substr($serial, 6, 1) != $productType) {
            $error['error'] = true;
            $error['msg']   = 'Érvénytelen mező: Sorozatszám';
            return $error;
        }

        $verID = $this->getVerIDFromverPassword8and9($currentVersion)->verID;

        $hlNum = substr($serial, 0, 6);
        $checkLatestVersion = $this->db->query("SELECT * FROM cl_hlusers.h_programs WHERE prHlNum LIKE '{$hlNum}%' ORDER BY prVerID DESC LIMIT 1")->row();
        if (!empty($checkLatestVersion) && $checkLatestVersion->prVerID == $verID) {
            $error['error'] = true;
            $error['msg']   = 'Már rendelkezik a legújabb változattal.';
            return $error;
        }

        $version = $this->getVersionDescription(substr($serial, 7, 2));

        if ($o_type == 16)
            return '';

        if (!empty($checkLatestVersion) && $version->verID != $checkLatestVersion->prVerID) {
            $serialVersion = $this->getVersionDescription(substr($checkLatestVersion->prPass, 7, 2));
            $error['error'] = true;
            $error['msg']   = 'Van újabb sorozatszáma: ' . $serialVersion->year;
            return $error;
        }

        if ($o_type == 4 && $currentVersion - $o_type >= substr($serial, 7, 2))
            return '';

        if ($currentVersion - $o_type != substr($serial, 7, 2)) {
            $error['error'] = true;
            $error['msg']   = 'Érvénytelen mező: ' . $version->description . ' sorozatszámot adott meg';
            return $error;
        }

        return '';
    }

    function getVerIDFromverPassword8and9($verPassword8and9)
    {
        $query = "SELECT * FROM cl_hlusers.p_versions WHERE verPassword8and9 = {$verPassword8and9}";

        return $this->db->query($query)->row();
    }

    function getVersionFromVerID($verID)
    {
        $query = "SELECT * FROM cl_hlusers.p_versions WHERE verID = {$verID}";

        return $this->db->query($query)->row();
    }

    function getSelectedVersion($o_type, $category, $productID)
    {
        $currentVersion = $this->getCurrentVersion($category, '8', $productID);
        $prevVersion = $currentVersion->verID - $o_type;

        return $this->getVersionFromVerID($prevVersion);
    }

    function updateBilling($user, $nUserID)
    {
        $query = "SELECT * FROM cl_hlusers.users WHERE nUserID = '{$nUserID}'";
        $crmUser = $this->db->query($query)->row();

        if ($crmUser->strInvoiceName == '' && $crmUser->strInvoiceEMail == '' && $crmUser->strInvoiceAddress == '') {
            $query = "UPDATE cl_hlusers.users
                SET nInvoiceCtrID = 36, strInvoiceName = '{$user->name}', strInvoiceZip = '{$user->postcode}',
                strInvoiceCity = '{$user->city}', strInvoiceAddress = '{$user->address}',
                strInvoiceEMail = '{$user->email}', strTaxNumber = '{$user->tax_number}',
                strInvoiceEAccount = 'Y'";

            if ($user->tax_number != '')
                $query .= ", strCompany = '{$user->name}'";

            $query .= " WHERE nUserID = '{$nUserID}'";

            $this->db->query($query);
        }
    }

    function uploadTermsAndConditionsPDF($year, $user_id, $doc_id, $cont_id)
    {
        $post = [
            'year'      => $year,
            'nUserID'   => $user_id,
            'doc_id'    => $doc_id,
            'cont_id'   => $cont_id
        ];

        $login      = 'mate.nagy@cadline.hu';
        $password   = 'Aa2mmxt7Eiq8';
        $url        = 'https://crm.cadline.hu/imre.php';
        $ch         = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");

        curl_exec($ch);

        curl_close($ch);
    }
}
