<?php
if (!class_exists('crm_hardlock')) require_once("common_cadline_libraries/crm_hardlock.class.php");
if (!class_exists('Tester')) require_once("common_cadline_libraries/crm_hardlock.class.php");
if (!class_exists('Event')) require_once("common_cadline_libraries/crm_users.class.php");
require_once('libraries/phpmailer/PHPMailerAutoload.php');
require_once('config.mail.php');

/* EXPO REMINDER BEGIN */
/*$date = new DateTime();
$fullDate = $date->format('Y-m-d');
$minutes = $date->format('i');

if (($fullDate == '2022-11-22' || $fullDate == '2022-11-23') && ($minutes == '00' || $minutes == '30')) {
    $eventDatas = new stdClass();
    $eventDatas->subject = 'Join our event, YouTube link has arrived!';
    $eventDatas->date = $date->format('Y-m-d H:i');

    $event = new Event($eventDatas);
    $sendEmail = $event->sendEventReminder($mailconfig);
}*/
/* EXPO REMINDER END */

/*if (date('Y-m-d H:i') == '2022-06-29 08:00') {
    require_once('libraries/phpmailer/PHPMailerAutoload.php');
    require_once('config.mail.php');

    $query = "SELECT em.email AS user_email, jml_u.name AS user_name
        FROM www_archline_hu.alworkshops_application app
        LEFT JOIN www_archline_hu.jml_users jml_u ON jml_u.id = app.user_id
        LEFT JOIN cl_hlusers.u_emails em ON em.nUserID = jml_u.nUserID
        WHERE app.course_id = 1394 AND em.newsletter = 1
        GROUP BY jml_u.nUserID";
    crm_database::getInstance()->query($query);
    $res = crm_database::getInstance()->fetchAssoc();

    foreach ($res as $value) {
        $subject        = 'Emlékeztető: ARCHLine.XP Középfokú tanfolyam';
        $body           = '<b>Kedves ' . $value['user_name'] . '</b>, <br/><br/>

            Köszönjük a jelentkezésedet a tanfolyamra. A következő adásunk témája: Tetőtér beépítése <br/><br/>

            <b>Mikor?</b> <br/>
            2022. Június 29. 10:00 <br/>
            <a href="https://youtu.be/bzOYWVo7eYA">Itt nézheted</a> <br/><br/>

            <b>Mire lesz szükséged:</b> <br/>
            Győződj meg arról, hogy az eszközön, amin nézni fogod, van hang, továbbá egy YouTube vagy Gmail fiók is kelleni fog, ha szeretnél az adás alatt kommentálni, vagy kérdezni.<br/><br/>

            <br/>

            <b>Fontos:</b> <br/>
            Az adást fel fogjuk venni, és később is elérhető lesz a YouTube csatornánkon. Azzal, hogy részt veszel az Élő adáson, elfogadod, hogy a hozzászólásaid láthatóak lesznek a felvett anyagon. <br/><br/>

            Ha bármi kérdésed van, fordjulj hozzánk az <a href="mailto:info@cadline.hu">info@cadline.hu</a> email címen <br/><br/>

            Találkozunk az élő adásban! <br/><br/>


            Üdvözlettel,

            A CADLine csapata';

        $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@cadline.hu';
        $mail->FromName = 'info@cadline.hu';
        $mail->AddAddress($value['user_email'], $value['user_name']);

        $mail->IsHTML(true);

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

    die();
}*/


/*if (date('Y-m-d H:i') == '2022-05-18 08:01') {
    // define('_JEXEC', 1);
    // define('JPATH_BASE', '..');

    require_once('libraries/phpmailer/PHPMailerAutoload.php');
    require_once('config.mail.php');

    $query = "SELECT * FROM www_archline_hu.alworkshops_application
        WHERE course_id = 1419 GROUP BY email";
    crm_database::getInstance()->query($query);
    $res = crm_database::getInstance()->fetchAssoc();

    foreach ($res as $value) {
        $subject        = 'Emlékeztető: ARCHLine.XP LIVE 2022 Újdonságok';
        $body           = '<b>Kedves ' . $value['name'] . '</b>, <br/><br/>

            Köszönjük a jelentkezésedet a webinárra. A következő adásunk témája: ARCHLine.XP LIVE 2022 Újdonságok 2.rész <br/><br/>

            <b>Mikor?</b> <br/>
            2022. Május 18. 16:30 <br/>
            <a href="https://youtu.be/k4HymyOkDZs">Itt nézheted</a> <br/><br/>

            <b>Mire lesz szükséged:</b> <br/>
            Győződj meg arról, hogy az eszközön, amin nézni fogod, van hang, továbbá egy YouTube vagy Gmail fiók is kelleni fog, ha szeretnél az adás alatt kommentálni, vagy kérdezni.<br/><br/>

            <br/>

            <b>Fontos:</b> <br/>
            Az adást fel fogjuk venni, és később is elérhető lesz a YouTube csatornánkon. Azzal, hogy részt veszel az Élő adáson, elfogadod, hogy a hozzászólásaid láthatóak lesznek a felvett anyagon. <br/><br/>

            Ha bármi kérdésed van, fordjulj hozzánk az <a href="mailto:info@cadline.hu">info@cadline.hu</a> email címen <br/><br/>

            Találkozunk az élő adásban! <br/><br/>


            Üdvözlettel,

            A CADLine csapata';

        $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@cadline.hu';
        $mail->FromName = 'info@cadline.hu';
        $mail->AddAddress($value['email'], $value['name']);

        $mail->IsHTML(true);

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

    die();
}*/

/*if (date('Y-m-d H:i') == '2022-05-18 08:02') {
    // define('_JEXEC', 1);
    // define('JPATH_BASE', '..');

    require_once('libraries/phpmailer/PHPMailerAutoload.php');
    require_once('config.mail.php');

    $query = "SELECT * FROM www_archline_hu.alworkshops_application
        WHERE course_id = 1420 GROUP BY email";
    crm_database::getInstance()->query($query);
    $res = crm_database::getInstance()->fetchAssoc();

    foreach ($res as $value) {
        $subject        = 'Reminder: ARCHLine.XP LIVE 2022 New Features';
        $body           = "<b>Dear " . $value['name'] . "</b>, <br/><br/>

            Thank you for signing up to our ARCHLine.XP Webinars <br/><br/>

            <b>The next show is on</b> <br/>
            2022. May 18, 3PM CET <br/>
            <a href='https://youtu.be/XiymR-PW-lM'>Watch it here</a> <br/><br/>

            <b>What you'll need:</b> <br/>
            A device with sound, so that you can hear us. Also, if you want to comment, you will need a Google or YouTube account. You can watch the shows without these accounts, too, but then you won't be able to comment.<br/><br/>

            <br/>

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

            Should you have any questions, reach out to us on the <a href='mailto:info@archlinexp.com'>info@archlinexp.com</a> email address <br/><br/>

            See you at the show! <br/><br/>


            Best wishes,
            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@cadline.hu';
        $mail->FromName = 'info@cadline.hu';
        $mail->AddAddress($value['email'], $value['name']);

        $mail->IsHTML(true);

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

    die();
}*/



/* --------------------------------- Masnapi reminder --------------------------------- */

/*if (date('Y-m-d H:i') == '2021-11-11 10:00') {
    // define('_JEXEC', 1);
    // define('JPATH_BASE', '..');

    require_once('/maintenance/libraries/phpmailer/PHPMailerAutoload.php');
    require_once('/maintenance/config.mail.php');

    $query = "SELECT * FROM www_archline_hu.alworkshops_application
        WHERE course_id = 1289 OR course_id = 1320 GROUP BY email";
    crm_database::getInstance()->query($query);
    $res = crm_database::getInstance()->fetchAssoc();

    foreach ($res as $value) {
        $subject        = 'Nézd meg újra: Életteli látvány és animáció a LIVE-ban';
        $body           = "Helló!<br/>
            Láttad a tegnapi webináriumot a Életteli látvány és animáció a LIVE-ban címmel? <br/>
            Ha igen, reméljük, hogy tetszett! Több időre van szükséged a gyakorláshoz? Nézd meg újra itt: <a href='https://youtu.be/HblUO3URDBk'>https://youtu.be/HblUO3URDBk</a> <br/><br/>

            Ha nem láttad, és még mindig érdekel, akkor még itt nézheted meg: <a href='https://youtu.be/HblUO3URDBk'>https://youtu.be/HblUO3URDBk</a> <br/><br/>


            Üdvözlettel, <br/>
            A CADLine csapata";

        $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@cadline.hu';
        $mail->FromName = 'info@cadline.hu';
        $mail->AddAddress($value['email'], $value['name']);

        $mail->IsHTML(true);

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

    die();
}*/

/*if (date('Y-m-d H:i') == '2021-11-11 10:01') {
    // define('_JEXEC', 1);
    // define('JPATH_BASE', '..');

    require_once('/maintenance/libraries/phpmailer/PHPMailerAutoload.php');
    require_once('/maintenance/config.mail.php');

    $query = "SELECT * FROM www_archline_hu.alworkshops_application
        WHERE course_id = 1288 OR course_id = 1342 GROUP BY email";
    crm_database::getInstance()->query($query);
    $res = crm_database::getInstance()->fetchAssoc();

    foreach ($res as $value) {
        $subject        = 'Watch it again: Breathtaking visuals and animations in LIVE';
        $body           = "Hello! <br/>
            Did you catch the Webinar yesterday about Breathtaking visuals and animations in LIVE? <br/>
            If you did, we hope you enjoyed it! Need more time to practice? Watch it again here: <a href='https://youtu.be/ZVUHcWmFfpA'>https://youtu.be/ZVUHcWmFfpA</a> <br/><br/>

            If you missed the show, you can watch it here: <a href='https://youtu.be/ZVUHcWmFfpA'>https://youtu.be/ZVUHcWmFfpA</a> <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@cadline.hu';
        $mail->FromName = 'info@cadline.hu';
        $mail->AddAddress($value['email'], $value['name']);

        $mail->IsHTML(true);

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

    die();
}*/

/*if ($_SERVER['REMOTE_ADDR'] == '82.131.186.171') {
    require_once("../common_cadline_libraries/crm_users.class.php");
    require_once('../maintenance/libraries/phpmailer/PHPMailerAutoload.php');

    $emailTemplate  = crm_users::getSevenDayEmailTemplate('mate.nagy@cadline.hu');

    $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('mate.nagy@cadline.hu');

    $mail->IsHTML(true);

    $mail->Subject = $emailTemplate['subject'];
    $mail->Body    = $emailTemplate['body'];
    $mail->Send();
    die();
}*/

if (date('H:i') == '10:00') {
    require_once("../common_cadline_libraries/crm_users.class.php");
    require_once('../maintenance/libraries/phpmailer/PHPMailerAutoload.php');

    $date = date('Y-m-d');
    $dateBefore = new DateTime();
    $dateBefore->modify('-30 day');
    $monthDate = $dateBefore->format('Y-m-d');

    $query = "SELECT * FROM cl_hlusers.u_emails
        WHERE newsletter = 1 AND trial_download_date != '' AND trial_download_date >= '{$monthDate}'";
    crm_database::getInstance()->query($query);
    $res = crm_database::getInstance()->fetchAssoc();

    foreach ($res as $value) {
        $needEmail = false;

        $day1 = new DateTime($value['trial_download_date']);
        $day1->modify('+1 day');

        $day3 = new DateTime($value['trial_download_date']);
        $day3->modify('+3 day');

        $day7 = new DateTime($value['trial_download_date']);
        $day7->modify('+7 day');

        $day14 = new DateTime($value['trial_download_date']);
        $day14->modify('+14 day');

        $day21 = new DateTime($value['trial_download_date']);
        $day21->modify('+21 day');

        $day24 = new DateTime($value['trial_download_date']);
        $day24->modify('+24 day');

        $day30 = new DateTime($value['trial_download_date']);
        $day30->modify('+30 day');

        if ($day1->format('Y-m-d') == $date) {
            $emailTemplate  = crm_users::getFirstDayEmailTemplate($value['email']);
            $needEmail      = true;
        } elseif ($day3->format('Y-m-d') == $date) {
            $emailTemplate  = crm_users::getThreeDayEmailTemplate($value['email']);
            $needEmail      = true;
        } elseif ($day7->format('Y-m-d') == $date) {
            $emailTemplate  = crm_users::getSevenDayEmailTemplate($value['email']);
            $needEmail      = true;
        } elseif ($day14->format('Y-m-d') == $date) {
            $emailTemplate  = crm_users::getFourteenDayEmailTemplate($value['email']);
            //$needEmail      = true;
        } elseif ($day21->format('Y-m-d') == $date) {
            $emailTemplate  = crm_users::getTwentyoneDayEmailTemplate($value['email']);
            //$needEmail      = true;
        } elseif ($day24->format('Y-m-d') == $date) {
            $emailTemplate  = crm_users::getTwentyfourDayEmailTemplate($value['email']);
            //$needEmail      = true;
        } elseif ($day30->format('Y-m-d') == $date) {
            $emailTemplate  = crm_users::getLastEmailTemplate($value['email']);
            //$needEmail      = true;
        }

        if ($needEmail) {
            $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($value['email'], $value['email']);

            $mail->IsHTML(true);

            $mail->Subject = $emailTemplate['subject'];
            $mail->Body    = $emailTemplate['body'];
            $mail->Send();
        }
    }
}

$action         = Tester::getCronTime();
$timer_result   = '';
$error_result   = '';

switch ($action) {
    case Time::sDay:
        if (date('Y-m-d') == '2023-06-01') {
            /* NÉMET WEBOLDAL BEGIN */
            $query = "UPDATE www_archline_hu.dtch_menu SET link = 'index.php?option=com_sppagebuilder&view=page&id=46' WHERE id = 131";
            crm_database::getInstance()->query($query);

            $query = "UPDATE www_archline_hu.dtch_menu SET link = 'index.php?option=com_sppagebuilder&view=page&id=47' WHERE id = 283";
            crm_database::getInstance()->query($query);
            /* NÉMET WEBOLDAL END */

            /* ANGOL WEBOLDAL BEGIN */
            $query = "UPDATE www_archline_hu.eng_sh404sef_urls SET rank = 1 WHERE id = 87489";
            crm_database::getInstance()->query($query);
            $query = "UPDATE www_archline_hu.eng_sh404sef_urls SET rank = 0 WHERE id = 80561";
            crm_database::getInstance()->query($query);

            $query = "UPDATE www_archline_hu.eng_sh404sef_urls SET rank = 1 WHERE id = 86094";
            crm_database::getInstance()->query($query);
            $query = "UPDATE www_archline_hu.eng_sh404sef_urls SET rank = 0 WHERE id = 79698";
            crm_database::getInstance()->query($query);
            /* ANGOL WEBOLDAL END */

            /*$query = "UPDATE cl_hlusers.o_products SET ackio_date = '2023-05-31' WHERE lang = 0 AND id >= 1288;";
            crm_database::getInstance()->query($query);*/
        }

        $date = new DateTime();
        $date->modify("-14 day");
        $day = $date->format("Y-m-d");

        $deleteFloatingLog = "DELETE FROM local_crm.floating_log WHERE substr(inserted, 1, 10) <= '{$day}'";
        Database::getInstance()->query($deleteFloatingLog);

        Tester::syncSwitchTable();

        $time_start     = microtime(true);
        $error_result   .= Tester::oneDay();
        $timer_result   .= 'One day: ' . Tester::calculateElapsedTime($time_start) . '\n';

    case Time::sTwelveHour:
        $time_start     = microtime(true);
        $error_result   .= Tester::twelveHour();
        $timer_result   .= 'Twelve hour: ' . Tester::calculateElapsedTime($time_start) . '\n';

    case Time::sSixHour:
        $time_start     = microtime(true);
        $error_result   .= Tester::sixHour();
        $timer_result   .= 'Six hour: ' . Tester::calculateElapsedTime($time_start) . '\n';

    case Time::sThreeHour:
        $time_start     = microtime(true);
        $error_result   .= Tester::threeHour();
        $timer_result   .= 'Three hour: ' . Tester::calculateElapsedTime($time_start) . '\n';

    case Time::sHour:
        $time_start     = microtime(true);
        $error_result   .= Tester::oneHour();
        $timer_result   .= 'One hour: ' . Tester::calculateElapsedTime($time_start) . '\n';

    case Time::sFifteenMin:
        $time_start     = microtime(true);
        $error_result   .= Tester::fifteenMinutes();
        $timer_result   .= 'Fifteen minutes: ' . Tester::calculateElapsedTime($time_start) . '\n';

    case Time::sFiveMin:
        $time_start     = microtime(true);
        $error_result   .= Tester::fiveMinutes();
        $timer_result   .= 'Five minutes: ' . Tester::calculateElapsedTime($time_start) . '\n';

    case Time::sMin:
        $time_start     = microtime(true);
        $error_result   .= Tester::oneMinute();
        $timer_result   .= 'One minute: ' . Tester::calculateElapsedTime($time_start) . '\n';
        break;

    default:

        break;
}

if ($error_result != '') {
    $message = str_replace('\n', '<br/>', $error_result);
    $message .= str_replace('\n', '<br/>', $timer_result);
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .= 'Cc: bodnart@cadline.hu';
    mail("mate.nagy@cadline.hu", "Auto CRM test", $message, $headers);
}

// Update-eli a cron_check tablat, hogy megnezzuk, lefut-e a cron. A cron_check.php file-ba pedig ellenorizzuk
Database::getInstance()->query("UPDATE cl_hlusers.cron_check SET modified = ? WHERE id = ?", array('ii', time(), 1));
