<?php
date_default_timezone_set('Asia/Kolkata');
error_reporting(E_ALL);
ini_set('display_errors', 1);
@ini_set('session.gc_maxlifetime','28800');
set_time_limit(0);

require 'configuration.php';
require_once 'includes/common.functions.php';
require_once ('classes/database.php');
require_once ('classes/functions.php');
$sqlObj = new mysqlClass;
$funcObj = new funcClass;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/vendor/autoload.php';
$currentDate = date('Y-m-d'); // Current date
$currentDateTime = date('Y-m-d H:i:s'); // Current date and time
// $campaign_query = "SELECT *	FROM ##campaign_send_stats WHERE DATE_SENT IS NULL AND IS_SCHEDULE = 1 AND SCHDULE_TIME = CURDATE() AND SCHDULE_TIME < DATE_ADD(CURDATE(), INTERVAL 1 DAY)";
$campaign_query = "SELECT * FROM ##campaign_send_stats WHERE DATE_SENT IS NULL AND IS_SCHEDULE = 1 AND DATE(SCHDULE_TIME) = '$currentDate' AND SCHDULE_TIME <= '$currentDateTime'";


$result_campaign = array();
$result_campaign = $funcObj->CustomQuery($campaign_query);

if(is_array($result_campaign) && !empty($result_campaign)){
    foreach($result_campaign as $rkey => $campaign){
        $id	= intval(isset($campaign['CAMPAIGN_ID']) ? $campaign['CAMPAIGN_ID'] : '');
        $ADDR_ID = intval(isset($campaign['ADDR_ID']) ? $campaign['ADDR_ID'] : '');
        $startFrom	= intval(isset($campaign['START_FROM']) ? $campaign['START_FROM'] : '');
        $threads	= intval(isset($campaign['THREADS']) ? $campaign['THREADS'] : '');
        $STAT_ID	= intval(isset($campaign['ID']) ? $campaign['ID'] : '');
        $DELAY	= intval(isset($campaign['DELAY']) ? $campaign['DELAY'] : '');
        $dbFailed	= 0;
       

            ##### Check for existing Email Sent log#########################
            $check_existing_stat = "SELECT * FROM ##email_sent_log WHERE `CAMP_STAT_ID` = $STAT_ID ";
            $resultcheck_existing_stat = $funcObj->CustomQuery($check_existing_stat);
           
            if(!empty($resultcheck_existing_stat)){
                $startFrom = $resultcheck_existing_stat[0]['LAST_EMAIL_INDEX'];
            }
            ##### End Check for existing Email Sent log#########################

            $sqlStart	= $startFrom - 1;

            if (empty($startFrom) || empty($id) || empty($threads))
            {
                echo '{';
                echo "'systemerror' : 'Required Parameter Missing'";
                echo '}';
                exit;
            }

            
            #### FETCH DEFAULT SMTP#########

            $query = "SELECT *	FROM ##smtp WHERE `DEFAULT` = '1'";
            $resultSetSMTP = array();
            $resultSetSMTP = $funcObj->CustomQuery($query);

            if (count($resultSetSMTP))
            {
                if ($resultSetSMTP[0]['MAILER_TYPE'] == 'smtp')
                {
                    $mailerType     = $resultSetSMTP[0]['MAILER_TYPE'];
                    $defHOST 		= $resultSetSMTP[0]['HOST'];
                    $defPORT 		= $resultSetSMTP[0]['PORT'];
                    $defUSER 		= $resultSetSMTP[0]['USER'];
                    $defPassword	= base64_decode(base64_decode($resultSetSMTP[0]['PASSWORD']));
                    $defAuth		= ($resultSetSMTP[0]['AUTHENTICATION'] == '1') ? 'true' : 'false';

                    $SENDER_NAME	 = isset($resultSetSMTP[0]['SENDER_NAME']) ? $resultSetSMTP[0]['SENDER_NAME'] : '';
                    $SENDER_EMAIL	 = isset($resultSetSMTP[0]['SENDER_EMAIL']) ? $resultSetSMTP[0]['SENDER_EMAIL'] : '';
                    $SENDER_COMPANY  = isset($resultSetSMTP[0]['SENDER_COMPANY']) ? $resultSetSMTP[0]['SENDER_COMPANY'] : '';
                    $SIGNATURE  	 = isset($resultSetSMTP[0]['SIGNATURE']) ? $resultSetSMTP[0]['SIGNATURE'] : '';
                    $REPLYTO_NAME      = isset($resultSetSMTP[0]['REPLY_NAME']) ? $resultSetSMTP[0]['REPLY_NAME'] : '';
                    $REPLYTO_EMAIL     = isset($resultSetSMTP[0]['REPLY_EMAIL']) ? $resultSetSMTP[0]['REPLY_EMAIL'] : '';
                }
            }
            else
            {
                echo '{';
                echo "'systemerror':'No default SMTP found'";
                echo '}';
                exit;
            }
            ##### END OF SMTP SETUP#########################

                $querytotal = "SELECT COUNT(DISTINCT(EMAIL)) AS TOTAL FROM ##contacts WHERE ADDR_ID IN ($ADDR_ID) AND IS_DELETED = 0";
                $resultCampIdstotal = $funcObj->CustomQuery($querytotal);
                $total = $resultCampIdstotal[0]['TOTAL'];

                $query = "SELECT DISTINCT(EMAIL), FIRSTNAME, LASTNAME, MISC_1, MISC_2, MISC_3 FROM
                ##contacts WHERE ADDR_ID IN ($ADDR_ID) AND IS_DELETED = 0 ORDER BY EMAIL ASC
                LIMIT {$sqlStart}, {$threads}";
                $contactsResultSet = array();
                $contactsResultSet = $funcObj->CustomQueryArray($query);

                $nextStart = intval($startFrom) + intval($threads);
                $percentage = floor((($nextStart-1)/$total) * 100);

                $failedEmails = array();

                $query = "SELECT  SUBJECT, CONTENTS, CONTENTSPLAIN FROM ##campaigns WHERE ID = '$id'";
                $resultSet = array();
                $resultSet = $funcObj->CustomQuery($query);
                /* Update the newsletter content 
                by replacing the MARKERS with the 
                actual values
                */
                $sent 		= 0;
                $success 	= 0;
                $failed 	= 0;
                $iStart 	= 0;
                $resultmultipleSetSMTP = array();
                $smtpIndex = 0;
                if(isset($campaign['SMTP_ID']) && !empty($campaign['SMTP_ID'])){
                    $smtp_ids= $campaign['SMTP_ID'];

                    $querysmtp = "SELECT *	FROM ##smtp WHERE `ID` IN ($smtp_ids)";
                    $resultmultipleSetSMTP = $funcObj->CustomQuery($querysmtp);
                }
                $smtpCount = count($resultmultipleSetSMTP);
                //start
                $i=1;
                foreach ($contactsResultSet as $rowContactsResultSet)
                {
                //for smtp_option = multiple
                    if(!empty($resultmultipleSetSMTP)){

                        $smtpConfig = $resultmultipleSetSMTP[$smtpIndex];
                        $mailerType 	= $smtpConfig['MAILER_TYPE'];
                        $defAuth 		= $smtpConfig['AUTHENTICATION'];
                        $defHOST 		= $smtpConfig['HOST'];
                        $defPORT 		= $smtpConfig['PORT'];
                        $defUSER 		= $smtpConfig['USER'];
                        $defPassword	= base64_decode(base64_decode($smtpConfig['PASSWORD']));
                        $defAuth		= ($smtpConfig['AUTHENTICATION'] == '1') ? 'true' : 'false';
                        $SENDER_NAME	 = isset($smtpConfig['SENDER_NAME']) ? $smtpConfig['SENDER_NAME'] : '';
                        $SENDER_EMAIL	 = isset($smtpConfig['SENDER_EMAIL']) ? $smtpConfig['SENDER_EMAIL'] : '';
                        $SENDER_COMPANY  = isset($smtpConfig['SENDER_COMPANY']) ? $smtpConfig['SENDER_COMPANY'] : '';
                        $SIGNATURE  	 = isset($smtpConfig['SIGNATURE']) ? $smtpConfig['SIGNATURE'] : '';
                        $REPLYTO_NAME      = isset($smtpConfig['REPLY_NAME']) ? $smtpConfig['REPLY_NAME'] : '';
                        $REPLYTO_EMAIL     = isset($smtpConfig['REPLY_EMAIL']) ? $smtpConfig['REPLY_EMAIL'] : '';
                    }


                        $contents = "";
                        $liveContent = "";
                        $contentsPlain = "";
                        $liveContentPlain = "";

                        $contents = $resultSet[0]['CONTENTS'];
                        $code = sha1($id); 
                        $hash = sha1($rowContactsResultSet['EMAIL']);
                        
                        $forwardStr 	= '';
                        $forwardStr 	= $id . ';' . $rowContactsResultSet['FIRSTNAME'] . ' ' . $rowContactsResultSet['LASTNAME'] . ';' . $rowContactsResultSet['EMAIL'];
                        $forwardStr		= base64_encode($forwardStr);
                        
                        $replaceContent = array(
                        '$UNSUB$' 		=> $trackURL . "?email={$rowContactsResultSet['EMAIL']}&camid={$id}&hash={$hash}&action=unsubscribe&friend=0&redirect=",
                        '$CANTREAD$' 	=> $trackURL . "?email={$rowContactsResultSet['EMAIL']}&camid={$id}&code={$code}&action=cantread&friend=0&redirect=",
                        '$LINKTRACK$' 	=> $trackURL . "?email={$rowContactsResultSet['EMAIL']}&camid={$id}&action=track&friend=0&redirect=",	 
                        '$FORWARD$' 	=> $absPath . "/forward.php?id={$forwardStr}",
                        '@EMAIL@' 		=> $rowContactsResultSet['EMAIL'], 
                        '@FIRSTNAME@' 	=> $rowContactsResultSet['FIRSTNAME'],	 
                        '@LASTNAME@'	=> $rowContactsResultSet['LASTNAME'],	 
                        '@MISC_1@' 		=> $rowContactsResultSet['MISC_1'], 
                        '@MISC_2@' 		=> $rowContactsResultSet['MISC_2'], 
                        '@MISC_3@' 		=> $rowContactsResultSet['MISC_3'],
                        '</html>'		=> "</html><div style='display:none'><img src='" . $trackURL . "?email={$rowContactsResultSet['EMAIL']}&camid={$id}&action=view&friend=0&redirect=''/></div>",
                        '@SENDERNAME@'	=> $SENDER_NAME,	 
                        '@SENDERCOMPANYNAME@'	=> $SENDER_COMPANY,	 
                        '@SIGNATURE@'	=> $SIGNATURE 
                        );
                        
                        $liveContent = $funcObj->replaceAll($replaceContent, $contents);


                        $contentsPlain = $resultSet[0]['CONTENTSPLAIN'];
                        
                        $replaceContent2 = array(
                        '$UNSUB$' 		=> $trackURL . "?email={$rowContactsResultSet['EMAIL']}&camid={$id}&hash={$hash}&action=unsubscribe&friend=0&redirect=",
                        '$CANTREAD$' 	=> $trackURL . "?email={$rowContactsResultSet['EMAIL']}&camid={$id}&code={$code}&action=cantread&friend=0&redirect=",
                        '$LINKTRACK$' 	=> $trackURL . "?email={$rowContactsResultSet['EMAIL']}&camid={$id}&action=track&friend=0&redirect=",	 
                        '$FORWARD$' 	=> $absPath . "/forward.php?id={$forwardStr}",
                        '@EMAIL@' 		=> $rowContactsResultSet['EMAIL'], 
                        '@FIRSTNAME@' 	=> $rowContactsResultSet['FIRSTNAME'],	 
                        '@LASTNAME@'	=> $rowContactsResultSet['LASTNAME'],	 
                        '@MISC_1@' 		=> $rowContactsResultSet['MISC_1'], 
                        '@MISC_2@' 		=> $rowContactsResultSet['MISC_2'], 
                        '@MISC_3@' 		=> $rowContactsResultSet['MISC_3'],
                        '@SENDERNAME@'	=> $SENDER_NAME,	 
                        '@SENDERCOMPANYNAME@'	=> $SENDER_COMPANY,	 
                        '@SIGNATURE@'	=> $SIGNATURE 
                        );
                        
                        $liveContentPlain = trim($funcObj->replaceAll($replaceContent2, $contentsPlain));
                        
                        if (empty($liveContentPlain))
                        {
                            $liveContentPlain = 'To view the message, please use an HTML compatible email viewer!';
                        }	
                        
                        ############## SEND EMAIL ##############
                        //require_once('classes/class.phpmailer.php');
                        //$mail             = new PHPMailer(); // defaults to using php "mail()"

                        

                        $mail = new PHPMailer(true);
                        if ($mailerType == 'smtp')
                        {
                            $mail->IsSMTP();  //SMTP IS DOWN SO SEND EMAILS THROUGH SENDMAIL INSTEAD.
                            //$mail->IsSendmail(); // telling the class to use SendMail transport 				
                            $mail->SMTPAuth   = $defAuth; 
                            if($defPORT == 465){
                                $mail->SMTPSecure = 'ssl';
                            }else{
                                $mail->SMTPOptions = array(
                                'ssl' => array(
                                    'verify_peer' => false,
                                    'verify_peer_name' => false,
                                    'allow_self_signed' => true
                                )
                            );
                        
                            }
                            
                            //$mail->SMTPSecure = "ssl"; 
                            if (!empty($bounceEmail))
                            {
                                //$mail->Sender = $bounceEmail; 
                            }	
                            $mail->Host       = $defHOST;   
                            $mail->Port       = $defPORT;   
                            $mail->Username   = $defUSER;  
                            $mail->Password   = $defPassword;
                            
                        }
                        else if ($resultSetSMTP[0]['MAILER_TYPE'] == 'sendmail')
                        {
                            $mail->IsSendmail(); // telling the class to use SendMail transport
                        }
                        else
                        {
                            // no need to do anything.
                            // phpmailer will use the default mail() function.
                        }
                        

                        if (empty($REPLYTO_EMAIL))
                        {
                            //$mail->AddReplyTo($resultSet[0]['FROM_EMAIL'], $resultSet[0]['FROM_NAME']);
                            $mail->AddReplyTo($SENDER_EMAIL, $SENDER_NAME);
                        }
                        else
                        {
                            if (empty($REPLYTO_NAME))
                                $mail->AddReplyTo($REPLYTO_EMAIL);
                            else
                                $mail->AddReplyTo($REPLYTO_EMAIL, $REPLYTO_NAME);
                        }
                        

                        //$mail->SetFrom($resultSet[0]['FROM_EMAIL'], $resultSet[0]['FROM_NAME']);
                        $mail->SetFrom($SENDER_EMAIL, $SENDER_NAME);
                        
                        ## do not add invalid email address otherwise it will error out
                        ## if the address is invalid (invalid format) then add a valid format
                        ## address. This is just a dummy addresses the system won't send email
                        ## at this address.
                        if (!validate_email ($rowContactsResultSet['EMAIL']))
                        {
                            $mail->AddAddress('testaddress@test.com', 'Test User');
                        }	
                        else
                        {
                            $mail->AddAddress($rowContactsResultSet['EMAIL'], $rowContactsResultSet['FIRSTNAME'] . ' ' . $rowContactsResultSet['LASTNAME']);
                        }	

                            
                        /* 23-02-2015 //replace macros with original content
                        
                        $mail->Subject    	= $resultSet[0]->SUBJECT;
                        */
                        $replaceContent3 = array(
                        '$UNSUB$' 		=> $trackURL . "?email={$rowContactsResultSet['EMAIL']}&camid={$id}&hash={$hash}&action=unsubscribe&friend=0&redirect=",
                        '$CANTREAD$' 	=> $trackURL . "?email={$rowContactsResultSet['EMAIL']}&camid={$id}&code={$code}&action=cantread&friend=0&redirect=",
                        '$LINKTRACK$' 	=> $trackURL . "?email={$rowContactsResultSet['EMAIL']}&camid={$id}&action=track&friend=0&redirect=",	 
                        '$FORWARD$' 	=> $absPath . "/forward.php?id={$forwardStr}",
                        '@EMAIL@' 		=> $rowContactsResultSet['EMAIL'], 
                        '@FIRSTNAME@' 	=> $rowContactsResultSet['FIRSTNAME'],	 
                        '@LASTNAME@'	=> $rowContactsResultSet['LASTNAME'],	 
                        '@MISC_1@' 		=> $rowContactsResultSet['MISC_1'], 
                        '@MISC_2@' 		=> $rowContactsResultSet['MISC_2'], 
                        '@MISC_3@' 		=> $rowContactsResultSet['MISC_3'],
                        '@SENDERNAME@'	=> $SENDER_NAME,	 
                        '@SENDERCOMPANYNAME@'	=> $SENDER_COMPANY,	 
                        '@SIGNATURE@'	=> $SIGNATURE 
                        );
                        $mail->Subject    	= trim($funcObj->replaceAll($replaceContent3, $resultSet[0]['SUBJECT']));
                        
                        $mail->AltBody 		= $liveContentPlain;
                        
                        //$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
                        
                        $mail->MsgHTML($liveContent);
                        
                        // Only send email if the email address is valid.
                        if (!validate_email ($rowContactsResultSet['EMAIL']))
                        {
                            $failedEmails[] = $rowContactsResultSet['EMAIL'];
                            
                           
                            $failed++;
                            
                            $query = "INSERT INTO ##report SET CAMPAIGN_ID='$id', EMAIL='".$rowContactsResultSet['EMAIL']."', USER_IP='', BROWSER='', 
                            OS='', PLATFORM='', ACTION='hardbounce', REDIRECT_URL='', IS_FRIEND = '0', DATE_TIME=NOW()";
                            $insertId = $funcObj->insertQuery($query);
                            
                        }
                        else 
                        {
                            
                            if(!$mail->Send()) 
                            {
                                /*
                                If the error is on the very first record probably the error is 
                                in SMTP setup.
                                Return with error message.
                                */
                                if ($iStart == 0)
                                {
                                    echo '{';
                                    echo "'systemerror':'Unable to send emails. Please check your SMTP'";
                                    echo '}';
                                    exit;
                                }
                                else
                                {
                                    $failedEmails[] = $rowContactsResultSet['EMAIL'];
                                    // Insert the failed email address (hard bounce email) into the database.
                                    $query = "INSERT INTO ##report SET CAMPAIGN_ID='$id', EMAIL='".$rowContactsResultSet['EMAIL']."', USER_IP='', BROWSER='', 
                                    OS='', PLATFORM='', ACTION='hardbounce', REDIRECT_URL='', IS_FRIEND = '0', DATE_TIME=NOW()";
                                    $insertId = $funcObj->insertQuery($query);

                                }
                                $failed++;
                            } 
                            else 
                            {
                                $success++;
                            }

                            //  STAT_ID
                            $check_again_existing_stat = "SELECT * FROM ##email_sent_log WHERE `CAMP_STAT_ID` = $STAT_ID ";
                            $resultcheck_again__existing_stat = $funcObj->CustomQuery($check_again_existing_stat);
                            
                            if(!empty($resultcheck_again__existing_stat)){
                                $check_stat_id = $resultcheck_again__existing_stat[0]['id'];
                                $email_id= $rowContactsResultSet['EMAIL'];
                    
                                $result_check_query = "UPDATE ##email_sent_log SET EMAILS= CONCAT(`EMAILS`, ',$email_id'  ) , LAST_EMAIL_INDEX = LAST_EMAIL_INDEX + 1 WHERE ID = '{$check_stat_id}'"; 
                                @$funcObj->updateQuery($result_check_query);
                                //update
                            }else{
                                $result_check_query = "INSERT INTO ##email_sent_log SET CAMP_STAT_ID='$STAT_ID', EMAILS='".$rowContactsResultSet['EMAIL']."', LAST_EMAIL_INDEX='1'";
                                $insertId = $funcObj->insertQuery($result_check_query);
                            }
                        }	
                        if($smtpCount > 0){
                            $smtpIndex = ($smtpIndex + 1) % $smtpCount;
                        }
                        
                        
                        ############ END OF SEND MAIL###############
                        $iStart++;
                    }

                    /* AS SOON AS THE PERCENTAGE IS >= 100)
                    MARKS THE CAMPAIGN AS SENT */

                    if ($percentage >= 100)
                    {
                        /**
                         * Update the Database and mark the campaign as SENT
                         */
                        // $query = "UPDATE ##campaign_send_stats SET DATE_SENT =NOW() WHERE ID = '{$STAT_ID}'"; 
                        // @$funcObj->updateQuery($query);	
                        
                        $query = "UPDATE ##contacts SET IS_USED	= '1' WHERE ADDR_ID IN ($ADDR_ID)"; 
                        @$funcObj->updateQuery($query);
                        
                        
                    }

                //end

                $i++;    
                sleep($DELAY);

    }
    $check_existing_stat = "SELECT * FROM ##email_sent_log WHERE `CAMP_STAT_ID` = $STAT_ID ";
    $resultcheck_existing_stat = $funcObj->CustomQuery($check_existing_stat);
    
    if(!empty($resultcheck_existing_stat)){
        $LAST_EMAIL_INDEX = $resultcheck_existing_stat[0]['LAST_EMAIL_INDEX'];
    }
    print_r($total);
    print_r($LAST_EMAIL_INDEX); 
    if($total == $LAST_EMAIL_INDEX){
        $query = "UPDATE ##campaign_send_stats SET IS_SCHEDULE=0, DATE_SENT =NOW() WHERE ID = '{$STAT_ID}'";
        @$funcObj->updateQuery($query);
        $query = "UPDATE ##campaigns SET IS_SENT='1', FAILED_EMAILS = '".$failed."', DATE_SENT=NOW() WHERE ID = '{$id}'"; 
        @$funcObj->updateQuery($query);
    }
   
}

echo "<pre>";
print_r($result_campaign);



?>