<?php
if (!class_exists('Database')) require_once("crm_database.class.php");
if (!isset($crm_config)) require_once('crm_config.php');

class crm_users
{
    public static function SetUserStatus($nUserID = 0, $newStatus = 0)
    {
        if ((int)$nUserID == 0 || (int)$newStatus == 0) return false;

        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`users` WHERE nUserID = ?";
        Database::getInstance()->query($query, array('i', (int)$nUserID));
        $crmUser = Database::getInstance()->fetchNext();

        if (empty($crmUser) || (int)$crmUser['nUserStatus'] >= (int)$newStatus) return false;

        $tomb = array(
            'nUserID'       => (int)$nUserID,
            'val'           => (int)$newStatus,
            'changeDate'    => date('Y-m-d H:i:s', time()),
            'nManagerID'    => _MANAGER_
        );

        Database::getInstance()->update(CRMADATBAZIS . ".users", array('nUserStatus' => (int)$newStatus), array('nUserID' => (int)$nUserID), 'ii');
        Database::getInstance()->insert(CRMADATBAZIS . ".u_userstatus_history", $tomb, 'iisi');

        return true;
    }

    public static function AddUser($tomb = array(), $newsletter = 1, $bind_type)
    {
        if (trim($tomb['strName']) == '' || trim($tomb['strEMail']) == '') return 0;

        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`u_emails` WHERE email = ?";
        Database::getInstance()->query($query, array('s', trim(addslashes($tomb['strEMail']))));
        $exist = Database::getInstance()->fetchNext();
        if (!$exist) { // ha nincs a crm-ben user rekordja, akkor létrehozza
            if (!isset($tomb['dateInsert'])) {
                $tomb['dateInsert'] = time();
                $bind_type .= 'i';
            }
            if (!isset($tomb['old_db'])) {
                $tomb['old_db'] = (strpos($_SERVER['HTTP_HOST'], ".com") ? 'clusers_eng' : 'clusers');
                $bind_type .= 's';
            }

            $nUserID = Database::getInstance()->insert(CRMADATBAZIS . ".users", $tomb, $bind_type);

            Database::getInstance()->insert(
                CRMADATBAZIS . ".u_emails",
                array(
                    'email'         => trim(addslashes($tomb['strEMail'])),
                    'nUserID'       => $nUserID,
                    'newsletter'    => $newsletter
                ),
                'sii'
            );
        } else {
            $nUserID = $exist['nUserID'];
        }
        return $nUserID;
    }

    public static function AddUserHistory($tomb = array())
    {
        if (!isset($tomb['nUserID']) || !isset($tomb['nTopicID'])) return false;

        //ezeket mindenképpen kitölti (kötelező mezők))
        $rec['nUserID']     = $tomb['nUserID'];
        $rec['nTopicID']    = $tomb['nTopicID'];
        $rec['dateEvent']   = (isset($tomb['dateEvent']) ? $tomb['dateEvent'] : date('Y-m-d', time()));
        $rec['strPlace']    = (isset($tomb['strPlace']) ? $tomb['strPlace'] : "web");
        $rec['strInfo']     = (isset($tomb['strInfo']) ? $tomb['strInfo'] : '');
        $rec['nManagerID']  = (isset($tomb['nManagerID']) ? $tomb['nManagerID'] : 36);
        $rec['insertDate']  = date('Y-m-d H:i:s', time());
        $rec['updateDate']  = date('Y-m-d H:i:s', time());

        $bind_type = 'iisssiss';

        //ezeket csak akkor tölti ki, ha megkapta az értékét, egyébként NULL
        if (isset($tomb['strTime'])) {
            $rec['strTime'] = $tomb['strTime'];
            $bind_type .= 's';
        }
        if (isset($tomb['strAccno'])) {
            $rec['strAccno'] = $tomb['strAccno'];
            $bind_type .= 's';
        }
        if (isset($tomb['datePaydate'])) {
            $rec['datePaydate'] = $tomb['datePaydate'];
            $bind_type .= 's';
        }
        if (isset($tomb['strAccno2'])) {
            $rec['strAccno2'] = $tomb['strAccno2'];
            $bind_type .= 's';
        }
        if (isset($tomb['datePaydate2'])) {
            $rec['datePaydate2'] = $tomb['datePaydate2'];
            $bind_type .= 's';
        }
        if (isset($tomb['bContract'])) {
            $rec['bContract'] = $tomb['bContract'];
            $bind_type .= 's';
        }
        if (isset($tomb['applicationID'])) {
            $rec['applicationID'] = $tomb['applicationID'];
            $bind_type .= 'i';
        }

        $newID = Database::getInstance()->insert(CRMADATBAZIS . ".u_history", $rec, $bind_type);

        return $newID;
    }

    public static function UpdateUserHistory($tomb = array(), $nEventID = 0, $bind_type)
    {
        if (empty($tomb) || (int)$nEventID == 0) return false;

        $tomb['updateDate'] = date('Y-m-d H:i:s', time());
        $bind_type .= 'si';
        Database::getInstance()->update(CRMADATBAZIS . ".u_history", $tomb, array('nEventID' => $nEventID), $bind_type);

        return true;
    }

    public static function GetValidLease($nUserID = 0, $level = 0)
    {
        $nTopicID   = 0;
        $lease      = false;

        switch ((int)$level) {
            case 1: {
                    $nTopicID = _COURSE_PRICE_PRELIMINARY_;
                    break;
                }
            case 2: {
                    $nTopicID = _COURSE_PRICE_INTERMEDIATE_;
                    break;
                }
        }

        if ((int)$nUserID == 0 || (int)$level == 0 || (int)$nTopicID == 0) return false;

        $query = "SELECT *, dateEvent AS validFrom, DATE_ADD(dateEvent, INTERVAL " . _LEASE_VALID_DAYS_ . " DAY) AS validThrough FROM `" . CRMADATBAZIS . "`.`u_history` WHERE nUserID = ? AND nTopicID = ? AND DATE_ADD(dateEvent, INTERVAL " . _LEASE_VALID_DAYS_ . " DAY) >= CURRENT_DATE ORDER BY nEventID DESC";
        Database::getInstance()->query($query, array('ii', (int)$nUserID, (int)$nTopicID));
        $lease = Database::getInstance()->fetchNext();
        return (($lease && count($lease)) ? $lease : false);
    }

    public static function levelesemeny($email, $osztaly, $fv, $topicid, $likeegyezes, $ujinfo, $nyelv = "", $hibainfo = "")
    {
        if (!is_numeric($topicid)) {
            Database::getInstance()->insert(
                JMLADATBAZIS . '.a_hibak',
                array(
                    'osztaly'   => $osztaly,
                    'fv'        => $fv,
                    'hiba'      => "Hibas topic id: {$topicid}",
                    'datum'     => date('Y-m-d H:i:s', time())
                ),
                'ssss'
            );
            return "nincstopic";
        }

        $query = "SELECT nUserID FROM `" . CRMADATBAZIS . "`.`u_emails` WHERE email = ? AND deleted = ?";
        Database::getInstance()->query($query, array('si', $email, 0));
        $user = Database::getInstance()->fetchAssoc();

        if (count($user)) {
            foreach ($user as $row) {
                self::levelbeszuras($row['nUserID'], $email, $osztaly, $fv, $topicid, $likeegyezes, $ujinfo, $nyelv, $hibainfo);
            }
        }
    }

    public static function levelbeszuras($nUserID, $email, $osztaly, $fv, $topicid, $likeegyezes, $ujinfo, $nyelv = "", $hibainfo = "")
    {
        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`u_history` 
            WHERE dateEvent = ? AND nTopicID = ? AND nUserID = ? AND (strInfo = ? OR strInfo LIKE ?)";
        Database::getInstance()->query($query, array('siiss', date('Y-m-d', time()), $topicid, $nUserID, $likeegyezes, "%{$likeegyezes}%"));
        $res = Database::getInstance()->fetchAssoc();

        if (count($res) == 0) {
            self::AddUserHistory(array(
                'nUserID'   => $nUserID,
                'nTopicID'  => $topicid,
                'strInfo'   => $ujinfo
            ));

            // nUserStatus atallitasa
            self::SetUserStatus($nUserID, 1);

            // esely atallitasa
            $user2 = (object)$res[0];

            if ((int)$user2->nEsely < 2) {
                $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`hardlock` WHERE hlUser = ? AND SUBSTRING(hlNum, 1, 2) = ? AND hlStat = ?";
                Database::getInstance()->query($query, array('ssi', $nUserID, '36', 1));
                $felhasz = Database::getInstance()->fetchNext();

                if (empty($felhasz)) {
                    $query = "SELECT count(nEventID) darab FROM `" . CRMADATBAZIS . "`.`u_history` WHERE nUserID = ?";
                    Database::getInstance()->query($query, array('i', $nUserID));
                    $res = Database::getInstance()->fetchNext();
                    $levelesemenyekszama = (object)$res;

                    if ($levelesemenyekszama->darab >= 2)
                        Database::getInstance()->update(CRMADATBAZIS . ".users", array('nEsely' => 2), array('nUserID' => $nUserID), 'ii');
                    elseif ($levelesemenyekszama->darab == 1)
                        Database::getInstance()->update(CRMADATBAZIS . ".users", array('nEsely' => 1), array('nUserID' => $nUserID), 'ii');
                }
            }
        }
    }

    public static function deleteUser($nUserID)
    {
        Database::getInstance()->delete(CRMADATBAZIS . ".u_history", array('nUserID' => $nUserID), 'i');
        Database::getInstance()->delete(CRMADATBAZIS . ".u_userstatus_history", array('nUserID' => $nUserID), 'i');
        Database::getInstance()->delete(CRMADATBAZIS . ".u_emails", array('nUserID' => $nUserID), 'i');
        Database::getInstance()->delete(CRMADATBAZIS . ".users", array('nUserID' => $nUserID), 'i');
    }

    public static function getFirstDayEmailTemplate($email)
    {
        $url_1 = 'https://www.archlinexp.com/maintenance/followedlinks.php?id=' . base64_encode('?email=' . $email . '&alias=trial-first');
        $url_2 = 'https://www.archlinexp.com/maintenance/followedlinks.php?id=' . base64_encode('?email=' . $email . '&alias=trial-first-[2]');

        $template = array();

        $template['subject']    = "All the inspiration you need for your ARCHLine.XP project";
        $template['body']       = "<a href='https://www.archlinexp.com/'>
            <img src='https://www.archlinexp.com/images/2021/11/16/al_logo_trial_download.png' style='margin-left: 5%;' />
            </a>
            <br/>
            <br/>
            <br/>
            
            <div style='font-family: Raleway, sans-serif; text-align: center; margin: 0px 60px 0px 60px; font-size: 16px;'>
                <img src='https://www.archlinexp.com/images/2021/11/17/trial_email_image_2.jpg'  style='width: 75%; display: block; margin-left: auto; margin-right: auto;' />
                <br/>
                
				<h2>Ready to start creating your first design?</h2>
				<br/>

				<p>
                    Let's help you get started as quickly as possible.
                    <br/>

                    But before you jump in... Would you like to find out how you can get more out of ARCHLine.XP while saving yourself dozens of hours in the process.
                    <br/>

                    Check out our courses.
                    <br/>

                    <b>Are you an architect? - ARCHITECTURAL MODELING COURSE</b>
				</p>

                <a href='{$url_1}' style='background-color: #e47d25; font-size: 20px; color: #000000; font-weight: bold; text-decoration: none; padding: 10px 10px; border-radius: 5px; display: inline-block; mso-padding-alt: 0;'>
                    <i style='letter-spacing: 20px; mso-font-width: -90%; mso-text-raise: 20pt;'>&nbsp;</i>
                    <span style='mso-text-raise: 10pt;'>Start Exploring</span>
                    <i style='letter-spacing: 20px; mso-font-width: -90%;'>&nbsp;</i>
                </a>
				<br/>
                <br/>
					
				<p>
					<b>Are you an interior designer? - INTERIOR DESIGN COURSE</b>
				</p>

                <a href='{$url_2}' style='background-color: #e47d25; font-size: 20px; color: #000000; font-weight: bold; text-decoration: none; padding: 10px 10px; border-radius: 5px; display: inline-block; mso-padding-alt: 0;'>
                    <i style='letter-spacing: 20px; mso-font-width: -90%; mso-text-raise: 20pt;'>&nbsp;</i>
                    <span style='mso-text-raise: 10pt;'>Start Exploring</span>
                    <i style='letter-spacing: 20px; mso-font-width: -90%;'>&nbsp;</i>
                </a>
				<br/>
				<br/>

				<a href='https://www.archlinexp.com/leiratkozas/" . $email . "'>Unsubscribe</a>
			</div>";

        return $template;
    }

    public static function getThreeDayEmailTemplate($email)
    {
        $url_1 = 'https://www.archlinexp.com/maintenance/followedlinks.php?id=' . base64_encode('?email=' . $email . '&alias=trial-second');
        $url_2 = 'https://www.archlinexp.com/maintenance/followedlinks.php?id=' . base64_encode('?email=' . $email . '&alias=trial-second-[2]');

        $template = array();

        $template['subject']    = "Welcome to the future of your work using ARCHLine.XP";
        $template['body']       = "<a href='https://www.archlinexp.com/'>
            <img src='https://www.archlinexp.com/images/2021/11/16/al_logo_trial_download.png' style='margin-left: 5%;' />
            </a>
            <br/>
            <br/>
            <br/>
            
            <div style='font-family: Raleway, sans-serif; text-align: center; margin: 0px 60px 0px 60px; font-size: 16px;'>
                <img src='https://www.archlinexp.com/images/2021/11/17/archlinexp_images_katerina_koldova_1920_1080_03.png'  style='width: 75%; display: block; margin-left: auto; margin-right: auto;' />
                <br/>
                
				<h2>Courses, case studies, tutorials</h2>
				<br/>

				<p>
                    You've opened the door to the ARCHLine.XP CAD/BIM design software.
                    <br/>

                    Many courses, case studies, tutorials are ready to guide on your next project, from floor plan to stunning visuals.
                    <br/>

                    It's time to start.
                    <br/>

                    <b>Are you an architect? -</b> 12 tips to design walls.
				</p>

                <a href='{$url_1}' style='background-color: #e47d25; font-size: 20px; color: #000000; font-weight: bold; text-decoration: none; padding: 10px 10px; border-radius: 5px; display: inline-block; mso-padding-alt: 0;'>
                    <i style='letter-spacing: 20px; mso-font-width: -90%; mso-text-raise: 20pt;'>&nbsp;</i>
                    <span style='mso-text-raise: 10pt;'>Start Exploring</span>
                    <i style='letter-spacing: 20px; mso-font-width: -90%;'>&nbsp;</i>
                </a>
				<br/>
                <br/>
					
				<p>
					<b>Are you an interior designer? -</b> Modern Kitchen Modelling
				</p>

                <a href='{$url_2}' style='background-color: #e47d25; font-size: 20px; color: #000000; font-weight: bold; text-decoration: none; padding: 10px 10px; border-radius: 5px; display: inline-block; mso-padding-alt: 0;'>
                    <i style='letter-spacing: 20px; mso-font-width: -90%; mso-text-raise: 20pt;'>&nbsp;</i>
                    <span style='mso-text-raise: 10pt;'>Start Exploring</span>
                    <i style='letter-spacing: 20px; mso-font-width: -90%;'>&nbsp;</i>
                </a>
				<br/>
				<br/>

				<a href='https://www.archlinexp.com/leiratkozas/" . $email . "'>Unsubscribe</a>
			</div>";

        return $template;
    }

    public static function getSevenDayEmailTemplate($email)
    {
        $url_1 = 'https://www.archlinexp.com/maintenance/followedlinks.php?id=' . base64_encode('?email=' . $email . '&alias=trial-third');
        $url_2 = 'https://www.archlinexp.com/maintenance/followedlinks.php?id=' . base64_encode('?email=' . $email . '&alias=trial-third-[2]');

        $template = array();

        $template['subject']    = "ARCHLine.XP Trial is for trying new things";
        $template['body']       = "<a href='https://www.archlinexp.com/'>
            <img src='https://www.archlinexp.com/images/2021/11/16/al_logo_trial_download.png' style='margin-left: 5%;' />
            </a>
            <br/>
            <br/>
            <br/>
            
            <div style='font-family: Raleway, sans-serif; text-align: center; margin: 0px 60px 0px 60px; font-size: 16px;'>
                <img src='https://www.archlinexp.com/images/2021/11/26/trial_7_days.png'  style='width: 75%; display: block; margin-left: auto; margin-right: auto;' />
                <br/>
                
				<h2>High-quality documents and presentations</h2>
				<br/>

				<p>
                    ARCHLine.XP gives you a lot more control over how your project look.
                    <br/>

                    Learn how to document, visualize or take quantity take-off.
                    <br/>

                    Learn quickly the main points.
                    <br/>

                    The Layout tool offers features that allow you to create high-quality documents about your project.
				</p>

                <a href='{$url_1}' style='background-color: #e47d25; font-size: 20px; color: #000000; font-weight: bold; text-decoration: none; padding: 10px 10px; border-radius: 5px; display: inline-block; mso-padding-alt: 0;'>
                    <i style='letter-spacing: 20px; mso-font-width: -90%; mso-text-raise: 20pt;'>&nbsp;</i>
                    <span style='mso-text-raise: 10pt;'>Start Exploring</span>
                    <i style='letter-spacing: 20px; mso-font-width: -90%;'>&nbsp;</i>
                </a>
				<br/>
                <br/>
					
				<p>
                    Taking a good photo-realistic image is not the same as pressing a button. 
                    <br/>

                    Learn how to render in ARCHLine.XP.
				</p>

                <a href='{$url_2}' style='background-color: #e47d25; font-size: 20px; color: #000000; font-weight: bold; text-decoration: none; padding: 10px 10px; border-radius: 5px; display: inline-block; mso-padding-alt: 0;'>
                    <i style='letter-spacing: 20px; mso-font-width: -90%; mso-text-raise: 20pt;'>&nbsp;</i>
                    <span style='mso-text-raise: 10pt;'>Rendering</span>
                    <i style='letter-spacing: 20px; mso-font-width: -90%;'>&nbsp;</i>
                </a>
				<br/>
				<br/>

				<a href='https://www.archlinexp.com/leiratkozas/" . $email . "'>Unsubscribe</a>
			</div>";

        return $template;
    }

    public static function getFourteenDayEmailTemplate($email)
    {
        $template = array();

        $template['subject']    = "Trials are for trying new things";
        $template['body']       = "ARCHLine.XP gives you a lot more control over how your project look. <br/><br/>

        Learn how to document, visualize or take quantity take-off. <br/><br/>
        
        Learn quickly the main points.";

        return $template;
    }

    public static function getTwentyoneDayEmailTemplate($email)
    {
        $template = array();

        $template['subject']    = "How to Grow Your Business with ARCHLine.XP LIVE";
        $template['body']       = "You already started your journey. Why stop now? <br/><br/>

        Check out what designers like you were interested: <br/>";

        return $template;
    }

    public static function getTwentyfourDayEmailTemplate($email)
    {
        $template = array();

        $template['subject']    = "Great news: You've received an offer";
        $template['body']       = "Great ideas deserve to get done. Check out this personal offer, made to help your professional work whatever you'll want later. <br/><br/>

        This is the best offer we have: <br/>
        15% coupon code. Save 15% Off. <br/><br/>
        
        Coupon ends on 11/30/2021. <br/>
        VIEW COUPON";

        return $template;
    }

    public static function getLastEmailTemplate($email)
    {
        $template = array();

        $template['subject']    = "Buy now - your trial is about to expire";
        $template['body']       = "Now your trial is about to expire, consider converting to perpetual license. <br/><br/>

        Trial version shows the number of days before expires. <br/><br/>
        
        You cannot extend the trial period, but you can still use your software after purchase. <br/><br/>
        
        This is the best offer we have: <br/>
        15% coupon code. Save 15% Off. <br/><br/>
        
        Coupon ends on 11/30/2021. <br/>
        VIEW COUPON";

        return $template;
    }
}

class Login extends Database
{
    private $username;
    private $password;
    private $salt = "\c1afgWsv\$FdxMDd=ImjOl%vxp\$ecFw%";

    public function __construct($username, $password)
    {
        parent::__construct();

        unset($this->username);
        unset($this->password);

        $this->username = $username;
        $this->password = $password;
    }

    public function getUsername()
    {
        return $this->username;
    }
    private function getSaltedPassword()
    {
        return hash_hmac("sha512", $this->password, $this->salt);
    }

    public function setPassword($password)
    {
        $this->password = $password;
    }
    public function hashSha512()
    {
        return password_hash($this->getSaltedPassword(), PASSWORD_DEFAULT);
    }

    public function verifyPassword()
    {
        $query = "SELECT id, username, password FROM `" . CRMADATBAZIS . "`.`schools` WHERE username = ? LIMIT 1";
        $this->query($query, array('s', $this->username));

        $school   = $this->fetchNext();
        $password = $school["password"];
        return password_verify($this->getSaltedPassword(), $password);
    }
}

class Course
{
    public static function getCourseByUrl($url)
    {
        $query = "SELECT * FROM `" . JMLADATBAZIS . "`.`aleducation_courses` WHERE url = ?";
        Database::getInstance()->query($query, array('s', $url));

        return Database::getInstance()->fetchNext();
    }

    public static function getApplicationPercentage($courseId, $userId)
    {
        $query = "SELECT * FROM www_archline_hu.aleducation_applications WHERE user_id = {$userId} AND course_id = {$courseId}";
        Database::getInstance()->query($query, array('ii', $userId, $courseId));

        $result = Database::getInstance()->fetchNext();

        return empty($result) ? 0 : $result['percentage'];
    }

    public static function getCourseApplication($courseId, $userId)
    {
        $query = "SELECT * FROM `" . JMLADATBAZIS . "`.`aleducation_applications` WHERE user_id = ? AND course_id = ?";
        Database::getInstance()->query($query, array('ii', $userId, $courseId));

        return Database::getInstance()->fetchNext();
    }

    public static function getCourses($id)
    {
        $response = array();

        $query = "SELECT * FROM `" . JMLADATBAZIS . "`.`aleducation_courses` WHERE id = ?";
        Database::getInstance()->query($query, array('i', $id));

        $course = Database::getInstance()->fetchNext();

        $response['title']      = $course['title'];
        $response['lessons']    = json_decode($course['lessons'])->courses;

        return $response;
    }

    public static function get_string_between($string, $start, $end)
    {
        $string = ' ' . $string;
        $ini = strpos($string, $start);
        if ($ini == 0) return '';
        $ini += strlen($start);
        $len = strpos($string, $end, $ini) - $ini;
        return substr($string, $ini, $len);
    }
}

class Event extends Database
{
    private $event;

    public function __construct($event)
    {
        parent::__construct();

        unset($this->event);

        $this->event = $event;

        if (isset($this->event->evt_id)) {
            $this->setEventDatas();
            $this->setYoutubeLink();
        }
    }

    private function setEventDatas()
    {
        $query = "SELECT alias, title, startdate AS eventStart, enddate AS eventEnd FROM `" . JMLADATBAZIS . "`.`eng_icagenda_events` WHERE id = ? LIMIT 1";
        $this->query($query, array('i', $this->event->evt_id));
        $event = $this->fetchNext();

        $this->event->title = $event['title'];
        $this->event->url   = 'https://' . $_SERVER['SERVER_NAME'] . '/' . $this->event->evt_id . '-' . $event['alias'];
        $this->event->eventStart = $event['eventStart'];
        $this->event->eventEnd = $event['eventEnd'];
    }

    private function setReminderEvent()
    {
        $evtDate = new DateTime($this->event->date);
        $evtDate->modify('+30 min');
        $evtBegin = $evtDate->format('Y-m-d H:i') . ':00';

        $query = "SELECT id, title, startdate AS eventStart, enddate AS eventEnd FROM `" . JMLADATBAZIS . "`.`eng_icagenda_events` WHERE startdate = ? LIMIT 1";
        $this->query($query, array('s', $evtBegin));
        $event = $this->fetchNext();

        $this->event->title = $event['title'];
        $this->event->eventStart = $event['eventStart'];
        $this->event->eventEnd = $event['eventEnd'];
        $this->event->evt_id = $event['id'];
    }

    private function setYoutubeLink()
    {
        $query = "SELECT value FROM `" . JMLADATBAZIS . "`.`eng_icagenda_customfields_data` WHERE parent_id = ? AND slug = ? LIMIT 1";
        $this->query($query, array('is', $this->event->evt_id, 'video_url'));
        $details = $this->fetchNext();

        $videoID = substr($details['value'], strpos($details['value'], "embed/") + 6);

        $this->event->youtubeLink = 'https://www.youtube.com/watch?v=' . $videoID;
    }

    public function getYoutubeLink()
    {
        return $this->event->youtubeLink;
    }

    private function getExpoUsers()
    {
        $query = "SELECT email FROM cl_hlusers.expo_users WHERE event_id = ? GROUP BY email";
        $this->query($query, array('i', $this->event->evt_id));
        return $this->fetchAssoc();
    }

    public function sendEventReminder($mailconfig)
    {
        $this->setReminderEvent();

        if ($this->event->title == null)
            return false;

        $this->setYoutubeLink();

        $expoUsers = $this->getExpoUsers();

        $premiereDate = new DateTime($this->event->eventStart);
        $premiere = $premiereDate->format('Y-m-d H:i:s');

        $endDate = new DateTime($this->event->eventEnd);
        $end = $endDate->format('Y-m-d H:i:s');

        $date = str_replace(' ', 'T', $premiere);
        $date = str_replace('-', '', $date);
        $date = str_replace(':', '', $date);

        $endDate = str_replace(' ', 'T', $end);
        $endDate = str_replace('-', '', $endDate);
        $endDate = str_replace(':', '', $endDate);

        $details        = "Watch it here: +%3Ca+href%3D%27++++++++++++{$this->event->youtubeLink}++++++++++++%27%3E++++++++++++{$this->event->youtubeLink}++++++++++++%3C/a%3E";
        $details        = str_replace(" ", "+", $details);
        $googleTitle    = str_replace(" ", "+", $this->event->title);

        $url        = "https://www.google.com/calendar/event?action=TEMPLATE";
        $urlPart    = "&location=online&text=$googleTitle&dates=$date/$endDate&ctz=Europe/Budapest&details=$details";
        $urlPart    = htmlentities($urlPart);
        $url       .= $urlPart;

        foreach ($expoUsers as $expoUser) {
            $body = "Hello, <br><br>

                You are receiving this email because you have signed up for the ARCHLine.XP Virtual Expo presentation below. <br><br>
                    
                Title: <b>{$this->event->title}</b> <br><br>
                    
                Premiere: <b>{$premiere} (GMT+02:00)</b> <br><br>
                    
                <a href='{$url}'>Add to Google Calendar</a> <br><br>
                    
                <b>Watch it here:</b> <a href='{$this->event->youtubeLink}'>{$this->event->youtubeLink}</a> <br><br>
                    
                <b>What you will need:</b> <br>
                You will need sound enabled on your computer, and a YouTube/Gmail account if you want to comment during the show. Commenting is not obligatory, but it greatly improves the quality and relevance of the webinar, so make sure you ask your questions before or during the talk.
                <br><br>

                <b>Please note:</b> The webinar will be recorded, and it will later be added to our archive shows. By joining the webinar you agree that your contribution (comments) will be visible on the video.
                <br><br>

                Should you have any questions, email us at <a href='mailto:info@archlinexp.com'>info@archlinexp.com</a>. <br><br>
                    
                Follow us on <a href='https://www.instagram.com/archlinexp/'>Instagram</a>, <a href='https://www.facebook.com/CadlineNetworkLtd'>Facebook</a>, <a href='https://www.linkedin.com/company/9486761/admin/'>LinkedIn</a> and <a href='https://www.youtube.com/c/Archlinexp_InteriorDesignSoftware'>YouTube</a>!
                <br><br>
                    
                We are looking forward to seeing you at the show! <br><br>
                    
                Best Wishes: <br>
                The CadLine Team";

            $mail           = new PHPMailer();
            $mail->CharSet  = 'UTF-8';
            $mail->Host     = $mailconfig['Host'];
            $mail->SMTPAuth = true;

            $mail->Username = $mailconfig['Username'];
            $mail->Password = $mailconfig['Password'];

            $mail->From     = 'info@archlinexp.com';
            $mail->FromName = 'info@archlinexp.com';
            $mail->AddAddress($expoUser['email'], $expoUser['email']);

            $mail->IsHTML(true);

            $mail->Subject = $this->event->subject;
            $mail->Body    = $body;
            $mail->Send();
        }

        return true;
    }

    private function sendEmail()
    {
        define('_JEXEC', 1);
        define('JPATH_BASE', $_SERVER['DOCUMENT_ROOT']);

        require_once($_SERVER['DOCUMENT_ROOT'] . '/maintenance/libraries/phpmailer/PHPMailerAutoload.php');
        require_once($_SERVER['DOCUMENT_ROOT'] . '/maintenance/config.mail.php');
        require_once(JPATH_BASE . '/includes/defines.php');
        require_once(JPATH_BASE . '/includes/framework.php');

        $mainframe = JFactory::getApplication('site');
        $mainframe->initialise();

        $lang = JFactory::getLanguage();

        $lang->load('com_icagenda', JPATH_BASE);

        $timeZone = 'GMT';

        $googleCalendar = $this->createGoogleCalendarLink();

        if (isset($this->event->zone)) {
            $sign   = '';
            $offset = substr($this->event->zone, 0, strpos($this->event->zone, "_"));
            $offset = $offset + 2;
            $offset = str_replace('.', ':', $offset);

            if (substr($offset, 0, 1) != '-') $sign = '+';
            if (substr($offset, 0, 2) != ':') $offset .= ':00';

            $timeZone .= $sign . $offset;
        } else {
            $timeZone .= '+2:00';
        }

        $sitename       = '';
        $subject        = JText::_('COM_ICAGENDA_REGISTRATION_EMAIL_USER_DATE_DEFAULT_SUBJECT');
        $body           = JText::_('COM_ICAGENDA_REGISTRATION_EMAIL_USER_NEW');
        $adminbody      = JText::_('COM_ICAGENDA_REGISTRATION_EMAIL_ADMIN_NEW');
        $adminsubject   = 'Event registration';
        $link           = "<a href='" . $this->event->url . "'>" . $this->event->url . "</a>";

        $replacements = array(
            '[SITENAME]'    => $sitename,
            '[LINK]'        => $link,
            '[TITLE]'       => $this->event->title,
            '[DATE]'        => $this->event->date . " ($timeZone)",
            '[EMAIL]'         => $this->event->userEmail,
            '[COUNTRY]'     => $this->event->ctrName,
            '[NAME]'        => $this->event->userName,
            '[GOOGLE_CAL]'  => $googleCalendar,
            '[RERUN]'       => $this->event->rerun . " ($timeZone)"
        );

        foreach ($replacements as $key => $value) {
            $subject      = str_replace($key, $value, $subject);
            $body         = str_replace($key, $value, $body);
            $adminbody    = str_replace($key, $value, $adminbody);
        }

        $mail           = new PHPMailer();
        $mail->CharSet  = 'UTF-8';
        $mail->Host     = $mailconfig['Host'];
        $mail->SMTPAuth = true;

        $mail->Username = $mailconfig['Username'];
        $mail->Password = $mailconfig['Password'];

        $mail->From     = 'info@archlinexp.com';
        $mail->FromName = 'www.archlinexp.com';
        $mail->AddAddress($this->event->userEmail, $this->event->userName);

        $mail->IsHTML(true);

        $mail->Subject = $subject;
        $mail->Body    = $body;

        $adminMail           = new PHPMailer();
        $adminMail->CharSet  = 'UTF-8';
        $adminMail->Host     = $mailconfig['Host'];
        $adminMail->SMTPAuth = true;

        $adminMail->Username = $mailconfig['Username'];
        $adminMail->Password = $mailconfig['Password'];

        $adminMail->From     = 'info@archlinexp.com';
        $adminMail->FromName = 'www.archlinexp.com';
        $adminMail->AddAddress('marketing@cadline.hu');

        $adminMail->IsHTML(true);

        $adminMail->Subject = $adminsubject;
        $adminMail->Body    = $adminbody;
        $adminMail->Send();

        /*$sql = "SELECT * FROM `".CRMADATBAZIS."`.`partners` WHERE ctrID = ?";
        $this->query($sql, array('i', $this->event->ctrID));
        $partner = $this->fetchNext();

		if (!empty($partner)) {
            $partnerMailer              = new PHPMailer();
            $partnerMailer->CharSet     = 'UTF-8';
            $partnerMailer->Host        = $mailconfig['Host'];
            $partnerMailer->SMTPAuth    = true;

            $partnerMailer->Username = $mailconfig['Username'];
            $partnerMailer->Password = $mailconfig['Password'];

            $partnerMailer->From        = 'info@archlinexp.com';
            $partnerMailer->FromName    = 'www.archlinexp.com';
            $partnerMailer->AddAddress($partner['email']);

            $partnerMailer->IsHTML(true);

            $partnerMailer->Subject = $adminsubject;
            $partnerMailer->Body    = $adminbody;
            $partnerMailer->Send();
		}*/

        if ($mail->Send())
            return true;
        else
            return false;
    }

    public function createGoogleCalendarLink()
    {
        $startdate = new DateTime($this->event->date);
        $startdate = $startdate->format(DateTime::ATOM);
        $startdate = str_replace('-', '', $startdate);
        $startdate = str_replace(':', '', $startdate);
        $startdate = substr($startdate, 0, strpos($startdate, "+"));

        $enddate = new DateTime($this->event->endDate);
        $enddate = $enddate->format(DateTime::ATOM);
        $enddate = str_replace('-', '', $enddate);
        $enddate = str_replace(':', '', $enddate);
        $enddate = substr($enddate, 0, strpos($enddate, "+"));

        $details    = "Watch it here: <a href='" . $this->event->url . "'>" . $this->event->url . "</a>";
        $details    = str_replace(" ", "+", $details);
        $title      = str_replace(" ", "+", $this->event->title);

        $url        = "https://www.google.com/calendar/event?action=TEMPLATE";
        $urlPart    = "&location=online&text=$title&dates=$startdate/$enddate&details=$details";
        $urlPart    = htmlentities($urlPart);
        $url       .= $urlPart;

        return $url;
    }

    public function registration()
    {
        $sql = "SELECT * FROM `" . CRMADATBAZIS . "`.`expo_users` WHERE email = ? AND event_id = ?";
        $this->query($sql, array('si', $this->event->userEmail, $this->event->evt_id));
        $user = $this->fetchNext();

        $country                = explode('_', $this->event->cntry);
        $this->event->ctrID     = $country[0];
        $this->event->ctrName   = $country[1];

        if (empty($user)) {
            $expoUser = array(
                'email'     => $this->event->userEmail,
                'country'   => $this->event->ctrName,
                'reg_date'  => date('Y-m-d'),
                'event_id'  => $this->event->evt_id
            );

            $this->insert(CRMADATBAZIS . ".expo_users", $expoUser, 'sssi');
        }

        $sqlEmail = "SELECT * FROM `" . CRMADATBAZIS . "`.`u_emails` WHERE email = ?";
        $this->query($sqlEmail, array('s', $this->event->userEmail));
        $exist = $this->fetchNext();

        $expoTopic = $this->event->evt_id == '104' ? 333 : 387;

        if (empty($exist)) {
            $crm_user = array(
                'strName'       => $this->event->userName,
                'strEmail'      => $this->event->userEmail,
                'nUserProf'     => 0,
                'nCtrID'        => $this->event->ctrID,
                'dateInsert'    => time(),
                'old_db'        => 'clusers_eng'
            );
            $nUserID = $this->insert(CRMADATBAZIS . ".users", $crm_user, 'ssiiis');

            $u_email = array(
                'email'         => $this->event->userEmail,
                'nUserID'       => $nUserID,
                'default'       => 1,
                'active'        => 1,
                'deleted'       => 0,
                'newsletter'    => 1
            );
            $this->insert(CRMADATBAZIS . ".u_emails", $u_email, 'siiiii');
        } else {
            $nUserID = $exist['nUserID'];

            $sqlUser = "SELECT old_db FROM `" . CRMADATBAZIS . "`.`users` WHERE nUserID = ?";
            $this->query($sqlUser, array('i', $nUserID));
            $crmUser = $this->fetchNext();

            if ($this->event->evt_id == '104')
                $expoTopic = 333;
            else
                $expoTopic = $crmUser['old_db'] == 'clusers' ? 391 : 387;
        }

        $sqlHistory = "SELECT * FROM `" . CRMADATBAZIS . "`.`u_history` WHERE nUserID = ? AND nTopicID = ? AND strInfo = ?";
        $this->query($sqlHistory, array('iis', $nUserID, $expoTopic, $this->event->title));
        $u_history = $this->fetchNext();

        if (empty($u_history)) {
            $history = array(
                'nUserID'       => $nUserID,
                'nTopicID'      => $expoTopic,
                'strPlace'      => 'online',
                'strInfo'       => $this->event->title,
                'nManagerID'    => 36,
                'insertDate'    => date('Y-m-d H:i:s'),
                'dateEvent'     => $this->event->date
            );
            $this->insert(CRMADATBAZIS . ".u_history", $history, 'iississ');
        }

        return $this->sendEmail();
    }

    public function registerToWinLIVE()
    {
        $sql = "SELECT * FROM `" . CRMADATBAZIS . "`.`live_prize` WHERE email = ?";
        $this->query($sql, array('s', $this->event->userEmail));
        $user = $this->fetchNext();

        $country                = explode('_', $this->event->cntry);
        $this->event->ctrID     = $country[0];
        $this->event->ctrName   = $country[1];

        if (!empty($user))
            return false;

        $live_prize = array(
            'email'     => $this->event->userEmail,
            'name'      => $this->event->userName,
            'reg_date'  => date('Y-m-d'),
            'country'   => $this->event->ctrName
        );

        $this->insert(CRMADATBAZIS . ".live_prize", $live_prize, 'ssss');

        $sqlEmail = "SELECT * FROM `" . CRMADATBAZIS . "`.`u_emails` WHERE email = ?";
        $this->query($sqlEmail, array('s', $this->event->userEmail));
        $u_email = $this->fetchNext();

        if (!empty($u_email)) {
            $history = array(
                'nUserID'       => $u_email['nUserID'],
                'nTopicID'      => 388,
                'strPlace'      => 'online',
                'strInfo'       => 'LIVE nyereményjátékra jelentkezett',
                'nManagerID'    => 36,
                'insertDate'    => date('Y-m-d H:i:s'),
                'dateEvent'     => date('Y-m-d')
            );

            $sqlHistory = "SELECT * FROM `" . CRMADATBAZIS . "`.`u_history` WHERE nUserID = ? AND nTopicID = ?";
            $this->query($sqlHistory, array('ii', $u_email['nUserID'], 388));
            $u_history = $this->fetchNext();

            if (empty($u_history))
                $this->insert(CRMADATBAZIS . ".u_history", $history, 'iississ');
        }

        return $this->sendLiveEmail();
    }

    private function sendLiveEmail()
    {
        define('_JEXEC', 1);
        define('JPATH_BASE', $_SERVER['DOCUMENT_ROOT']);

        require_once($_SERVER['DOCUMENT_ROOT'] . '/maintenance/libraries/phpmailer/PHPMailerAutoload.php');
        require_once($_SERVER['DOCUMENT_ROOT'] . '/maintenance/config.mail.php');
        require_once(JPATH_BASE . '/includes/defines.php');
        require_once(JPATH_BASE . '/includes/framework.php');

        $mainframe = JFactory::getApplication('site');
        $mainframe->initialise();

        $lang = JFactory::getLanguage();

        $lang->load('com_icagenda', JPATH_BASE);

        $subject        = 'Win ARCHLine.XP LIVE License - Signup Confirmed!';
        $body           = JText::_('COM_ICAGENDA_WIN_AL_LIVE');

        $replacements = array(
            '[NAME]'        => $this->event->userName
        );

        foreach ($replacements as $key => $value) {
            $body = str_replace($key, $value, $body);
        }

        $mail           = new PHPMailer();
        $mail->CharSet  = 'UTF-8';
        $mail->Host     = $mailconfig['Host'];
        $mail->SMTPAuth = true;

        $mail->Username = $mailconfig['Username'];
        $mail->Password = $mailconfig['Password'];

        $mail->From     = 'info@archlinexp.com';
        $mail->FromName = 'www.archlinexp.com';
        $mail->AddAddress($this->event->userEmail, $this->event->userName);

        $mail->IsHTML(true);

        $mail->Subject = $subject;
        $mail->Body    = $body;


        $adminMail           = new PHPMailer();
        $adminMail->CharSet  = 'UTF-8';
        $adminMail->Host     = $mailconfig['Host'];
        $adminMail->SMTPAuth = true;

        $adminMail->Username = $mailconfig['Username'];
        $adminMail->Password = $mailconfig['Password'];

        $adminMail->From     = 'info@archlinexp.com';
        $adminMail->FromName = 'www.archlinexp.com';
        $adminMail->AddAddress('ztoth@cadline.hu', 'Zoltan Toth');

        $adminMail->IsHTML(true);

        $adminMail->Subject = 'Virtual Expo - LIVE Registration';
        $adminMail->Body    = "<b>Name: </b> {$this->event->userName}
            <br/>
            
            <b>Email:</b> {$this->event->userEmail}
            <br/>
            
            <b>Country:</b> {$this->event->ctrName}";

        $adminMail->Send();

        if ($mail->Send())
            return true;
        else
            return false;
    }

    /* --------------- WORKSHOP --------------- */

    public function registrationToWebinar()
    {
        $this->setWebinar();

        $this->event->nUserID = $this->getUserID();

        $query = "SELECT * FROM www_archline_hu.alworkshops_application
			WHERE course_id = ? AND email = ? AND published = ?";

        $this->query($query, array('iss', $this->event->course_id, $this->event->userEmail, 'Y'));
        $exist = $this->fetchNext();

        if (empty($exist)) {
            $topicID = $this->event->crm_db == 'clusers' ? 336 : 333;

            $history = array(
                'nUserID'       => $this->event->nUserID,
                'nTopicID'      => $topicID,
                'dateEvent'     => $this->event->workshop['start_date'],
                'strPlace'      => $this->event->workshop['title'],
                'strInfo'       => $this->event->workshop['course_name'],
                'nManagerID'    => 36,
                'insertDate'    => date('Y-m-d H:i:s', time())
            );

            $this->insert(CRMADATBAZIS . ".u_history", $history, 'iisssis');

            $this->createWorkshopApplication();
            $this->sendWorkshopEmail();

            return true;
        } else {
            return false;
        }
    }

    private function sendWorkshopEmail()
    {
        require_once($_SERVER['DOCUMENT_ROOT'] . '/maintenance/libraries/phpmailer/PHPMailerAutoload.php');
        require_once($_SERVER['DOCUMENT_ROOT'] . '/maintenance/config.mail.php');

        $template     = $this->getEmailTemplate();
        $body         = $template['introtext'] . $template['fulltext'];
        $title         = $template['title'];

        $replacements = array(
            '{NAME}'        => $this->event->userName,
            '{TITLE}'        => $this->event->workshop['title'],
            '{START_DATE}'     => $this->event->workshop['start_date'],
            '{START_TIME}'  => $this->event->workshop['start_time'],
            '{FINISH_DATE}'    => $this->event->workshop['finish_date'],
            '{FINISH_TIME}'    => $this->event->workshop['finish_time'],
            '{LOCATION}'    => $this->event->workshop['location'],
            '{ATTENDEES}'      => 0,
            '{PRICE}'       => $this->event->workshop['price'],
            '{PRICE_TOTAL}' => 0,
            '{VAT}'         => $this->event->workshop['vat']
        );

        foreach ($replacements as $key => $value) {
            $body = str_replace($key, $value, $body);
        }

        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->CharSet         = 'UTF-8';
        $mail->Host         = $mailconfig['Host'];
        $mail->SMTPAuth     = true;
        $mail->Username     = $mailconfig['Username'];
        $mail->Password        = $mailconfig['Password'];
        $mail->SMTPSecure    = $mailconfig['SMTPSecure'];
        $mail->Port         = $mailconfig['Port'];
        $mail->Subject         = $title;
        $mail->AltBody         = strip_tags($body);
        $mail->isHTML(TRUE);
        $mail->setFrom($mailconfig['from_hu']);
        $mail->addAddress($this->event->userEmail);
        //$mail->addBCC('marketing@cadline.hu');
        $mail->msgHTML($body);

        if ($mail->send()) {
            unset($mail);

            return true;
        } else {
            return false;
        }
    }

    private function getEmailTemplate()
    {
        $table = $this->event->crm_db == 'clusers' ? 'jml_content' : 'eng_content';

        $query = "SELECT * FROM www_archline_hu.{$table} WHERE id = ?";
        $this->query($query, array('i', $this->event->workshop['email_template']));

        return $this->fetchNext();
    }

    public function setWebinar()
    {
        $sql = "SELECT * FROM www_archline_hu.alworkshops_courses WHERE id = ?";
        $this->query($sql, array('i', $this->event->course_id));
        $workshop = $this->fetchNext();

        $this->event->workshop = $workshop;
    }

    private function getUserID()
    {
        $sql = "SELECT nUserID FROM cl_hlusers.u_emails WHERE email = ?";
        $this->query($sql, array('s', $this->event->userEmail));
        $exist = $this->fetchNext();

        if (!$exist) {
            if ($this->event->userName > '' && $this->event->userEmail > '') {
                $user = array(
                    'strName'       => $this->event->userName,
                    'strEmail'      => $this->event->userEmail,
                    'nUserProf'     => 0,
                    'nCtrID'        => $this->event->cntry,
                    'dateInsert'    => time(),
                    'old_db'        => $this->event->crm_db
                );
                $nUserID = $this->insert(CRMADATBAZIS . ".users", $user, 'ssiiis');

                $u_email = array(
                    'email'         => $this->event->userEmail,
                    'nUserID'       => $nUserID,
                    'default'       => 1,
                    'active'        => 1,
                    'deleted'       => 0,
                    'newsletter'    => 1
                );
                $this->insert(CRMADATBAZIS . ".u_emails", $u_email, 'siiiii');
            }
        } else {
            $nUserID = $exist['nUserID'];
        }

        return $nUserID;
    }

    public function createWorkshopApplication()
    {
        $application = array(
            'course_id' => $this->event->course_id,
            'user_id'   => 0,
            'attendees' => 1,
            'price_per_attendee' => 0,
            'price_total' => 0,
            'price_vat' => 0,
            'gepet_kerek' => 'N',
            'berletem_van' => 'N',
            'date' => date('Y-m-d H:i:s', time()),
            'name' => $this->event->userName,
            'email' => $this->event->userEmail
        );

        $this->insert('www_archline_hu.alworkshops_application', $application, 'iiiiiisssss');
    }

    public function getEvent()
    {
        return $this->event;
    }
}
