<?php
require $_SERVER['DOCUMENT_ROOT'] . '/public/order/dompdf/autoload.inc.php';
require $_SERVER['DOCUMENT_ROOT'] . '/public/order/phpmailer/PHPMailerAutoload.php';

use Dompdf\Dompdf;

class Pay extends Controller
{
    function __construct()
    {
        parent::__construct();

        $this->load->library('session');
        $this->load->model('mpay');
        $this->load->library('Product');

        if (
            $_SESSION['user_id'] == '' && $this->uri->segment(2) != 'login'
            && $this->uri->segment(2) != 'orderFromBarion'
            && $this->uri->segment(2) != 'createPassword'
        ) {
            $_SESSION['prod_id'] = $this->uri->segment(3);
            redirect('pay/login');
        }
    }

    function index()
    {
        if ($this->uri->segment(2) != 'index')
            redirect('pay/index');

        if ($this->uri->segment(3) == '' || !is_numeric($this->uri->segment(3))) {
            $this->load->view('pay/404.php');
            return;
        }

        $afa_key            = "27";
        $product_id         = $this->uri->segment(3);
        $payData            = array();
        $payData['product'] = $this->mpay->getProduct($product_id);

        if ($payData['product']->kategoria == 'credit') {
            header('Location: https://www.archline.hu/vasarlas');
            die();
        }

        if (empty($payData['product'])) {
            $this->load->view('pay/404.php');
            return;
        }

        if ($payData['product']->type == 76)
            $payData['logo'] = 'https://pay.archline.hu/assets/img/livelogo.png';
        else
            $payData['logo'] = 'https://pay.archline.hu/assets/img/logo_web.png';

        $license = $this->mpay->getLicenseAgreement($payData['product']->kategoria)->content;
        $license = str_replace('{DATE}', date('Y.m.d'), $license);

        $payData['currentVer']  = $this->mpay->getSelectedVersion($payData['product']->o_type, $payData['product']->kategoria, $payData['product']->id);
        $payData['error']       = $this->session->flashdata('error');
        $payData['license']     = $license;
        $payData['policy']      = $this->mpay->getPrivacyPolicy();
        $payData['crmUser']     = $payData['product']->kategoria == 'upgrade' ? array() : $this->mpay->getCRMprofile($_SESSION['user_id']);
        $payData['countries']   = $this->mpay->getCountries();
        $payData['readOnly']    = $payData['product']->kategoria == 'upgrade';
        $payData['service']     = $this->mpay->getServiceAgreement($payData['product']->id)->content;
        $payData['inst']        = Product::getInstalment($payData['product']->id, $payData['product']->seq, $payData['product']->o_type, $payData['product']->ackio_date);
        $payData['needCoupon']  = (($payData['product']->kategoria == 'perp' || $payData['product']->kategoria == 'live') && $payData['product']->cont_id == 0) || ($payData['product']->kategoria == 'upgrade' && $payData['product']->seq == 2) ? true : false;
        $payData['afa']         = $afa_key / 100;
        $payData['vat']         = $payData['product']->price * $payData['afa'];
        $payData['brut']        = $payData['product']->price * ($payData['afa'] + 1);

        $this->load->view('pay/index.php', $payData);
    }

    function login()
    {
        if ($_SESSION['user_id'] != '')
            redirect('pay');

        $username = $this->input->post('username');
        $password = $this->input->post('password');

        $payData = array();

        if ($_POST['login-btn']) {
            $user = $this->mpay->login($username, $password);

            if (!$user) {
                $payData['error'] = 'Hibás felhasználónév vagy jelszó!';
            } else {
                $_SESSION['user_id'] = $user->nUserID;
                redirect('pay/index/' . $_SESSION['prod_id']);
            }
        }

        $this->load->view('pay/login.php', $payData);
    }

    function createPassword()
    {
        $serial = $orderNum = '';

        $user                   = new stdClass();
        $user->userID           = $_POST['userID'];
        $user->product_id       = $_POST['product_id'];
        $user->notes            = $_POST['notes'];
        $orderNum               = $_POST['order_num'];

        $product = $this->mpay->getProduct($user->product_id);

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

        $eventID = $this->mpay->getEventID($product->cont_id,  $product->kategoria);

        $this->mpay->generatePassword($user->userID, $user->product_id, $serial, $price, $user->notes, $orderNum, $product);
        $this->mpay->createUserHistory($user->userID, $product->cont_id, $product->kategoria, $product->price, $eventID, '', $product->o_type);
        $this->mpay->updateUserStatus($user->userID, 11);
        $this->mpay->updateOrder($orderNum, $serial);
    }

    function orderFromBarion()
    {
        $serial = $price = $orderNum = '';
        $couponPrice = isset($_POST['couponPrice']) && $_POST['couponPrice'] != '' && $_POST['couponPrice'] > 0 ? $_POST['couponPrice'] : 0;

        $user                   = new stdClass();
        $user->name             = $_POST['name'];
        $user->email            = $_POST['email'];
        $user->tax_number       = $_POST['tax_number'];
        $user->postcode         = $_POST['postcode'];
        $user->city             = $_POST['city'];
        $user->address          = $_POST['address'];
        $user->notes            = $_POST['notes'];
        $user->currency_code    = $_POST['currency_code'];
        $user->product_id       = $_POST['product_id'];
        $user->userID           = $_POST['userID'];

        $product = $this->mpay->getProduct($user->product_id);

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

        $license    = $this->mpay->getLicenseAgreement($product->kategoria);
        $curr_ver   = $this->mpay->getCurrentVersion($product->kategoria, '8', $user->product_id);
        $orderNum   = $this->mpay->getOrderNumber(36);

        $this->mpay->createOrder($product->termek, $orderNum, $user->name, $user->email, 36, $serial, $price, $user->notes);
        $this->mpay->updateBilling($user, $user->userID);
        $this->mpay->uploadTermsAndConditionsPDF($curr_ver->year, $user->userID, $license->id, $product->cont_id);
        $this->mpay->createUserHistory($user->userID, $product->cont_id, $product->kategoria, $product->price, 78, '(Barion)', $product->o_type, $couponPrice);

        echo $orderNum;
    }

    function order()
    {
        $this->load->helper('email');

        $serial = $price = $orderNum = '';
        $coupon = $this->input->post('coupon');

        $user                   = new stdClass();
        $user->name             = $this->input->post('name');
        $user->email            = $this->input->post('email');
        $user->tax_number       = $this->input->post('tax_number');
        $user->postcode         = $this->input->post('postcode');
        $user->city             = $this->input->post('city');
        $user->address          = $this->input->post('address');
        $user->notes            = $this->input->post('notes');
        $user->currency_code    = $this->input->post('currency_code');
        $user->product_id       = $this->input->post('product_id');
        $user->userID           = $this->input->post('userID');
        $user->inputSerial      = $this->input->post('serial');

        if ($user->name == '') {
            $this->session->set_flashdata('error', 'Érvénytelen mező: Név');
            redirect('pay/index/' . $user->product_id);
        }

        if ($user->email == '') {
            $this->session->set_flashdata('error', 'Érvénytelen mező: Email cím');
            redirect('pay/index/' . $user->product_id);
        }

        if (!is_numeric($user->postcode) || strlen($user->postcode) != 4) {
            $this->session->set_flashdata('error', 'Érvénytelen mező: Irányítószám');
            redirect('pay/index/' . $user->product_id);
        }

        if ($user->city == '') {
            $this->session->set_flashdata('error', 'Érvénytelen mező: Város');
            redirect('pay/index/' . $user->product_id);
        }

        if ($user->address == '') {
            $this->session->set_flashdata('error', 'Érvénytelen mező: Utca, házszám');
            redirect('pay/index/' . $user->product_id);
        }

        $product = $this->mpay->getProduct($user->product_id);
        $netto = $product->price;
        $inst = $user->product_id == 1823 ? 3 : Product::$instalments; // Torolni

        if ($this->input->post('instalments') == 'true')
            $netto = $product->price / $inst;

        // Torolni
        if ($user->product_id == 1823 && $this->input->post('instalments') == 'true')
            $netto = 49000;

        $couponPrice = 0;

        if (isset($coupon) && $coupon != '' && $this->input->post('instalments') != 'true') {
            $couponCode = $this->mpay->getCoupon($coupon, $product->id);

            if ($couponCode['error'] == true) {
                $this->session->set_flashdata('error', $couponCode['error_message']);
                redirect('pay/index/' . $user->product_id);
            }

            $netto = $netto - $couponCode['coupon_price'];
            $couponPrice = (int)$couponCode['coupon_price'];
        }

        $afa_key            = "27";
        $afa                = $afa_key / 100;
        $brut_amount_item   = $netto * ($afa + 1);
        $price              = $brut_amount_item;

        $license    = $this->mpay->getLicenseAgreement($product->kategoria);
        $curr_ver   = $this->mpay->getCurrentVersion($product->kategoria, '8', $user->product_id);
        $orderNum   = $this->mpay->getOrderNumber(36);

        $this->mpay->createOrder($product->termek, $orderNum, $user->name, $user->email, 36, $serial, $price, $user->notes);
        $this->mpay->updateBilling($user, $user->userID);
        $this->mpay->updateUserStatus($user->userID, 10);
        $this->mpay->sendEmail($user, $orderNum, $product, $this->input->post('instalments'), $couponPrice);

        if ($product->seq != 2) {
            $this->mpay->uploadTermsAndConditionsPDF($curr_ver->year, $user->userID, $license->id, $product->cont_id);
            $this->mpay->sendCustomEmail($user->email, $product->termek, $product->cont_id);
        }

        $this->mpay->createUserHistory($user->userID, $product->cont_id, $product->kategoria, $product->price, 78, '', $product->o_type, $couponPrice);

        if ($couponPrice > 0) {
            $this->mpay->changeCoupon($coupon, $user->userID);
        }

        redirect('pay/success');
    }

    function sendMaintenanceEmail()
    {
        try {
            $product        = $this->mpay->getProduct($_POST['product_id']);
            $license        = $this->mpay->getMaintenanceAgreement($product->o_type, $_POST['product_id']);
            $curr_ver       = $this->mpay->getCurrentVersion($product->kategoria, 8, $_POST['product_id']);
            /*$maintPrice     = (int)Product::getMaintenancePrice();
            $updatePrice    = (int)$product->price - $maintPrice;*/

            $license = str_replace('{NAME}', $_POST['name'], $license);
            $license = str_replace('{ADDRESS}', $_POST['postcode'] . ' ' . $_POST['city'] . ', ' . $_POST['address'], $license);
            $license = str_replace('{TAX_NUMBER}', $_POST['tax_number'], $license);
            $license = str_replace('{EMAIL}', $_POST['email'], $license);
            $license = str_replace('{HLNUM}', substr($_POST['serial'], 0, 6), $license);
            $license = str_replace('{DATE}', date('Y.m.d'), $license);
            $license = str_replace('{CONTACT}', $_POST['contact'], $license);
            $license = str_replace('{PHONE}', $_POST['telephone'], $license);
            /*$license = str_replace('{MAINTENANCE_PRICE}', '<b>' . number_format($maintPrice, 0, ',', '.') . '</b>', $license);
            $license = str_replace('{UPDATE_PRICE}', '<b>' . number_format($updatePrice, 0, ',', '.') . '</b>', $license);*/

            $pdf = new DOMPDF();
            $pdf->loadHtml($license, 'UTF-8');
            $pdf->render();
            $output = $pdf->output();

            $unwanted_array = array(
                'Á' => 'A',
                'É' => 'E',
                'Í' => 'I',
                'Ó' => 'O',
                'Ö' => 'O',
                'Ő' => 'O',
                'Ú' => 'U',
                'Ü' => 'U',
                'Ű' => 'U',
                'á' => 'a',
                'é' => 'e',
                'í' => 'i',
                'ó' => 'o',
                'ö' => 'o',
                'ő' => 'o',
                'ú' => 'u',
                'ü' => 'u',
                'ű' => 'u'
            );

            $name       = strtr($_POST['name'], $unwanted_array);
            $name       = str_replace(' ', '_', $name);
            $file_name  = $name . '_Karbantartasi_Szerzodes_' . $curr_ver->year . '.pdf';

            $put = file_put_contents($file_name, $output);

            $message = '{';
            $message .= '"product_id":"' . $_POST['product_id'] . '",';
            $message .= '"name":"' . $_POST['name'] . '",';
            $message .= '"address":"' . $_POST['postcode'] . ' ' . $_POST['city'] . ', ' . $_POST['address'] . '",';
            $message .= '"tax_number":"' . $_POST['tax_number'] . '",';
            $message .= '"email":"' . $_POST['email'] . '",';
            $message .= '"serial":"' . $_POST['serial'] . '",';
            $message .= '"contact":"' . $_POST['contact'] . '",';
            $message .= '"phone":"' . $_POST['telephone'] . '",';
            $message .= '"file_put_contents":"' . $put . '",';
            $message .= '"file_name":"' . $file_name . '",';
            $message .= '"email_send":"false"';
            $message .= '}';

            $debug = array(
                'data'          => $message,
                'insert_date'   => date('Y-m-d H:i:s'),
                'session_id'    => 'Karbantartasi_szerzodes'
            );

            $this->db->insert('cl_hlusers.debug_table', $debug);
            $debugID = $this->db->insert_id();

            $cc = $_POST['email'] == 'nagy.mate960814@gmail.com' ? 'mate.nagy@cadline.hu' : 'office@cadline.hu';

            $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($_POST['email'], $_POST['name']);
            $mail->addCC($cc);
            $mail->addBCC('mate.nagy@cadline.hu');
            $mail->IsHTML(true);
            $mail->AddAttachment($file_name);
            $mail->Subject = 'Megújuló Karbantartási szerződés';
            $mail->Body = 'Kedves Vásárlónk! <br><br>
 
            Köszönjük a megrendelésed. Az elektronikus számlát elküldtük. <br>
            Csatoltan küldjük a <b></b>SZOFTVER SZOLGÁLTATÁSI SZERZŐDÉS – MEGÚJULÓ KARBANTARTÁSI Szerződést.</b> <br><br>
            
            Kérjük aláírva küldd vissza. <br>
            <b>A szerződés hatályba lépésének feltétele az aláírt szerződés visszaküldése email-ben az <a href="mailto:office@cadline.hu">office@cadline.hu</a> címre</b> (vagy postai úton történő érkeztetése), <b>és napja az első esedékes díj megfizetésének dátuma.</b>
            <br>
            A számla összegének beérkezése és az aláírt szerződés visszaküldése után elkészül a sorozatszámod és küldjük a szoftver telepítési útmutatót.
            <br><br>

            <b>Termék: </b>' . $product->termek . '
            <br><br>

            A karbantartási szerződés lemondására a Felhasználói fiókban az Adatlapon, a Licencadatoknál van lehetőség a szerződés feltételeinek megfelelően.
            <br><br>
            
            Üdvözlettel <br><br>
            
            <b>CadLine Kft</b> <br>
            1037 Budapest, <br>
            Montevideo utca 3/B';

            $send = $mail->Send();

            $message = '{';
            $message .= '"product_id":"' . $_POST['product_id'] . '",';
            $message .= '"name":"' . $_POST['name'] . '",';
            $message .= '"address":"' . $_POST['postcode'] . ' ' . $_POST['city'] . ', ' . $_POST['address'] . '",';
            $message .= '"tax_number":"' . $_POST['tax_number'] . '",';
            $message .= '"email":"' . $_POST['email'] . '",';
            $message .= '"serial":"' . $_POST['serial'] . '",';
            $message .= '"contact":"' . $_POST['contact'] . '",';
            $message .= '"phone":"' . $_POST['telephone'] . '",';
            $message .= '"file_put_contents":"' . $put . '",';
            $message .= '"file_name":"' . $file_name . '",';
            $message .= '"email_send":"' . $send . '"';
            $message .= '}';

            $query = "UPDATE cl_hlusers.debug_table d
            SET d.data = '{$message}'
            WHERE debug_id = {$debugID}";
            $this->db->query($query);
        } catch (\Exception $e) {
            $message = '{';
            $message .= '"product_id":"' . $_POST['product_id'] . '",';
            $message .= '"name":"' . $_POST['name'] . '",';
            $message .= '"address":"' . $_POST['postcode'] . ' ' . $_POST['city'] . ', ' . $_POST['address'] . '",';
            $message .= '"tax_number":"' . $_POST['tax_number'] . '",';
            $message .= '"email":"' . $_POST['email'] . '",';
            $message .= '"serial":"' . $_POST['serial'] . '",';
            $message .= '"contact":"' . $_POST['contact'] . '",';
            $message .= '"phone":"' . $_POST['telephone'] . '",';
            $message .= '"email_send":"false",';
            $message .= '"error":"' . $e->getMessage() . '"';
            $message .= '}';

            $debug = array(
                'data'          => $message,
                'insert_date'   => date('Y-m-d H:i:s'),
                'session_id'    => 'Karbantartasi_szerzodes'
            );

            $this->db->insert('cl_hlusers.debug_table', $debug);
        }
    }

    function getBillingInformation()
    {
        $serial = $_POST['serial'];

        $crmUser = $this->mpay->getBillingInformation($serial);

        echo json_encode($crmUser);
    }

    function checkPassword()
    {

        $product = $this->mpay->getProduct($_POST['product_id']);

        $currentVersion = $this->mpay->getCurrentVersion($product->kategoria, $product->type, $_POST['product_id']);
        $checkPassword  = $this->mpay->checkPassword($_POST['serial'], $product->type, $product->o_type, $currentVersion->verPassword8and9);

        echo json_encode($checkPassword);
    }

    function success()
    {
        $this->load->view('pay/success.php');
    }

    function checkCoupon()
    {
        $coupon = $_POST['coupon'];
        $prodId = $_POST['productId'];

        $couponCode = $this->mpay->getCoupon($coupon, $prodId);

        echo json_encode($couponCode);
    }
}
