<?php
include 'config.php';
include 'fungsi.php';
include 'fungsi2.php';

$mail = new VerifyEmail();
$mail->setStreamTimeoutWait(10);
$mail->Debug= FALSE; 
$mail->Debugoutput= 'html'; 
$mail->setEmailFrom($emailakun);

$sm=array (
':)' => "<img src='$weburl/images/smiles/happy.png' width='20' height='20' border=0 />",
':(' => "<img src='$weburl/images/smiles/sad.png' width='20' height='20' border=0 />",
':D' => "<img src='$weburl/images/smiles/devil.png' width='20' height='20' border=0 />",
';)' => "<img src='$weburl/images/smiles/kiss.png' width='20' height='20' border=0 />",
':?' => "<img src='$weburl/images/smiles/nervous.png' width='20' height='20' border=0 />",
':8'  => "<img src='$weburl/images/smiles/confused.png' width='20' height='20' border=0 />",
':T' => "<img src='$weburl/images/smiles/tunjuk.png' width='20' height='20' border=0 />",
':i' => "<img src='$weburl/images/smiles/surprised.png' width='20' height='20' border=0 />"
);

$query = mysqli_query($con,"SELECT * FROM gtm WHERE next_post <= NOW() AND next_item_id > 0  AND nextemail > 0 AND id_member > 0 order by next_post asc LIMIT 0,5"); //AND status>0
if (mysqli_num_rows($query) > 0) {
	while($send = mysqli_fetch_array($query,MYSQLI_ASSOC)) {

		$id_prospek = $send['id_member'];
		//echo $id_prospek;
		$id_champ = $send['next_item_id'];
		$idgtm = $send['id'];
		$idgrup = $send['id_grup'];
		$starget1 = $send['status'];
		$nextemail2 = $send['nextemail'];
		$c = unserialize($send['customdata']);
		
		$q = mysqli_query($con,"SELECT a.*, b.* FROM champ a,prospek b WHERE b.ID = $id_prospek AND a.ID = $id_champ AND a.status_target= $starget1 LIMIT 0,1"); 
		$champ = mysqli_fetch_array($q,MYSQLI_ASSOC);		
		
		$bcid = $champ['ID'];
		$idbc = $id_champ;
		$judul = $champ['judul'];
		$isi = $champ['isi'];
		$nama = $champ['nama'];
		$mailgrup = $champ['grup'];
		$idyoutube = $champ['idyoutube'];
		
		$email = $champ['email'];
		//echo $email .'<br>';
		//echo $judul;
		
		IF(empty($email)){
		    
		    $cek = mysqli_query($con,"select * from grup where id='$idgrup'");
    		$qcek = mysqli_fetch_array($cek,MYSQLI_ASSOC);
    		$nextemail = $qcek['nextemail'];
		    If ($nextemail==0){
    			mysqli_query($con,"UPDATE gtm SET next_item_id=0,next_post=0 WHERE id_grup = '$idgrup' AND id_member = '$id_prospek'");
    		}else{
    			mysqli_query($con,"UPDATE gtm SET nextemail=0 WHERE id_grup = '$idgrup' AND id_member = '$id_prospek'");
    		}
		    //$delay = 1;
    		//mysqli_query($con,"UPDATE gtm SET next_post=DATE_ADD(next_post, INTERVAL $delay DAY) WHERE id_grup = '$idgrup' AND id_member = '$id_prospek'");
    		exit;
		}
		
		IF(!empty($email)){
    		IF($proteksi ==1){
               if($mail->check($email)){
                   $email = $email;
               }elseif(verifyEmail::validate($email)){   
                   mysqli_query($con,"UPDATE gtm SET gagal=gagal+1 WHERE id_member='$id_prospek' and id_grup='$idgrup'");
                   mysqli_query($con,"UPDATE gtm SET next_item_id=0,next_post=0 WHERE id_grup = '$mailgrup' AND id_member = '$id_prospek'");
                   
                   $message_text = 'Info Pesan Auto: Email '.$email.' domain Ada tapi email Tidak valid.';
                   sendMessage($telegram_id, $message_text, $secret_token);
                   exit;
               }else{
                   mysqli_query($con,"UPDATE gtm SET gagal=gagal+1 WHERE id_member='$id_prospek' and id_grup='$idgrup'");
                   mysqli_query($con,"UPDATE gtm SET next_item_id=0,next_post=0 WHERE id_grup = '$mailgrup' AND id_member = '$id_prospek'");
                   $message_text ='Info Pesan Auto: Email '.$email.' domain dan email Tidak Ada'; 
                   sendMessage($telegram_id, $message_text, $secret_token);
                   exit;
               } 
            }else{   
               if(domain_exists($email)) {    
                  $email = $email;
               }else{
                  mysqli_query($con,"UPDATE gtm SET gagal=gagal+1 WHERE id_member='$id_prospek' and id_grup='$idgrup'");
                  mysqli_query($con,"UPDATE gtm SET next_item_id=0,next_post=0 WHERE id_grup = '$mailgrup' AND id_member = '$id_prospek'");
                  $message_text ='Info Pesan Auto: Email '.$email.' domain dan email Tidak Ada'; 
                  sendMessage($telegram_id, $message_text, $secret_token);
                  $email =''; 
                  exit;
               }      
            }
		}    
		
		$sms = $champ['sms'];
		$pesanwa = $champ['pesanwa'];
		$hp = $champ['hp'];
		$starget2 = $champ['status_target'];
		$stschamp = $champ['stschamp'];
		$idtempe = $champ['tempe'];
		
		$sort = $champ['sort'];
    	$mailgrup = $champ['grup'];
    	//sementara
    	IF(empty($sort)){
    	   $sort = 1;
    	   $mailgrup = $idgrup;
    	}else{    
    	   $sort = $sort;
    	   $mailgrup = $mailgrup;
    	}
    	//
		
		if (is_array($c)) {
		    while ($custom = current($c)) {
				$key = key($c);
				$isi = str_replace('['.$key.']',$custom,$isi);
				$pesanwa = str_replace('['.$key.']',$custom,$pesanwa);
				//$judul = str_replace('['.$key.']',$custom,$judul);
				//$sms = str_replace('['.$key.']',$custom,$sms);
				next($c);
			}
		}	
		
		$isi = str_replace('[nama]',$nama,$isi);
		$isi = str_replace('[email]',$email,$isi);
		$isi = str_replace('[hp]',$hp,$isi);
		$judul = str_replace('[nama]',$nama,$judul);		
		$judul = str_replace('[email]',$email,$judul);
		$judul = str_replace('[hp]',$hp,$judul);
		$isi = $isi;
		$sms = str_replace('[nama]',$nama,$sms);
		$sms = str_replace('[email]',$email,$sms);
		$sms = str_replace('[hp]',$hp,$sms);
		$pesanwa = str_replace('[nama]',$nama,$pesanwa);
		$pesanwa = str_replace('[email]',$email,$pesanwa);
		$pesanwa = str_replace('[hp]',$hp,$pesanwa);
		
		$query = mysqli_query($con,"SELECT * FROM akunn WHERE id=1");
	    $check = mysqli_fetch_array($query,MYSQLI_NUM);
	    if (isset($check[0])) {
				$urlhost =$check[4];
    	        $emailhost = $check[5];
    	        $passhost = $check[6];
    	        $namal = $check[10];
    	        $port = $check[11];
    	        $catkaki = $check[15];
    	        $telegram_id = $check[16];
    	        $secret_token = $check[17];
    	        $emailapi = $check[12];
    	        $keyapi = $check[13];
    	        $smsaktif = $check[14];
    	        $usersmtp = $check[22];
	    }    
	   
	    $qcunsub = mysqli_query($con,"SELECT * FROM akunn WHERE id=1");
	    $cunsub = mysqli_fetch_array($qcunsub,MYSQLI_NUM);
	    $emailto =$cunsub[21];
	    $namato = $cunsub[20];
	    if (!empty($cunsub[19])) {
				$unsub =$cunsub[19];
				$linkunsub ='<font size="1"><a href="'.$weburl.'unsub/unsub.php?id='.$idgtm.'&code='.md5($idgtm.'||'.$idgrup).'">UNSUB</a></font>';
				//$unsub = str_replace('[nama]',$nama,$unsub);
                //$unsub = str_replace('[email]',$email,$unsub);
				//$unsub = str_replace('[linkunsub]',$linkunsub,$unsub);
	    }else{
    	        $unsub ='<h7>Email ini terkirim kepada '.$nama.' karena pernah mengisi Form Opt kami dan sudah menjadi subscriber kami. Ini bukan email spam. Jika email ini masuk ke kotak SPAM, harap klik tombol/menu BUKAN SPAM agar informasi dari kami selalu masuk ke kotak inbox. Maaf jika email ini mengganggu, untuk berhenti
                silahkan <i><a href="'.$weburl.'unsub/unsub.php?id='.$idgtm.'&code='.md5($idgtm.'||'.$idgrup).'">KLIK DISINI</a></i>, maka anda tidak menerima lagi email bisnis dari kami tapi anda dapat kembali lagi dengan mengisi form option yang kami sediakan.</h7>';
	    }    
            
        If ($download =='Y'){
            $gbr ='';
        }else{
            $gbr ='<img src="'.$weburl.'/images/autobiznistop.png">';
        }
            
        $querywa = mysqli_query($con,"SELECT * FROM wacs order by rand()");
    	        $checkwa = mysqli_fetch_array($querywa,MYSQLI_NUM);
    	        if (isset($checkwa[0])) {
    				$namal =$checkwa[1];
        	        $thp = $checkwa[2];
    	        }else{
    	            $namal = $namal;
    	            $thp = $check[7];
    	        }   
    	        
        $thp =substr($thp, 1,12);
        $thp = $kodenegara.''.$thp;
        //$tombolWA ='<a href="https://api.whatsapp.com/send?phone='.$thp.'&text=halo%20pak/ibu%20'.$namal.'%20saya%20mau%20konsultasi" target="_blank"><img src="'.$weburl.'/images/tanyaWA.png"></a>';
            
        $tombolWA ='<a href="'.$weburl.'/wa.php" target="_blank"><img src="'.$weburl.'/images/tanyaWA.png"></a>'; 
        
        If($idyoutube !='-'){
            $video = '<a href="https://youtu.be/'.$idyoutube.'">
	            <img src="https://www.hansvangent.com/download_youtube_screenshot.php?youtube_id='.$idyoutube.'"/>
                </a>';
        }else{
           $video=''; 
        }  
            
        $catkaki ='<font size="1">'.$catkaki.'</font>';    
            
        If ($check[9]==0){
              $isi = $video .'<br>'. $isi .'<br>'. $catkaki .'<br>'. $gbr;    
        }else{
              $isi = $video .'<br>'. $isi .'<br>'. $tombolWA .'<br>'. $catkaki .'<br>'. $gbr; 
        }
        
        If($idtempe==0){
                $body = $isi .'<br><hr>'. $unsub ;
                $body = str_replace('[nama]',$nama,$body);
                $body = str_replace('[email]',$email,$body);
                $body = str_replace(array_keys($sm), array_values($sm), $body);
                $body = str_replace('[linkunsub]',$linkunsub,$body);
            
        }else{
               $queryT = mysqli_query($con,"SELECT * FROM template where id=$idtempe");
    	        $checkT = mysqli_fetch_array($queryT,MYSQLI_NUM);
    	        if (isset($checkT[0])) {
    				$linkk = $weburl.$checkT[2];
    				$body = file_get_contents($linkk);
    				$body = str_replace('[judul]',$judul,$body);
    				$body = str_replace('[nama]',$nama,$body);
    				$body = str_replace('[email]',$email,$body);
                    $body = str_replace('[unsub]',$unsub,$body);
                    $body = str_replace('[isi]',$isi,$body);
                    $body = str_replace('[linkunsub]',$linkunsub,$body);
                    $body = str_replace(array_keys($sm), array_values($sm), $body);
    	        } 
        }
        
        If(empty($usersmtp)){
            $usersmtp = $emailhost;
        }else{    
            $usersmtp = $usersmtp;
        }
        
        //kirimemail
		IF($stschamp==1){
		    
		    IF($smtp1a==1){
        	    $recipient = $email;
                $subject = $judul;
                $content = $body;
        	    
        	    $message_body .= '<img src="'.$weburl.'xxxxxtrx3.php?code='.$idbc.'&email='.$id_prospek.'" width="5" height="5" />';
        	    
        	    $content = $content .'<br>'. $message_body;
        	    
        	    $params = [
                'from_name' => $from_name,
                'from_email' => $from_email,
                'recipient' => $recipient,
                'subject' => $subject,
                'content' => $content,
                'api_token' => $api_token,
                ];
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL,"https://app.mailketing.id/api/v1/send");
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                $output = curl_exec ($ch);
                //print_r($output);
                curl_close ($ch);
                
                $array = json_decode($output);
                $sts1 = $array->response;
                $sts2 = $array->status;
                IF($sts1 =='Mail Sent' && $sts2=='success'){
                    $pesannn ='Anda sukses mengirimkan email auto ke email '.$email.'.'; 
                    mysqli_query($con,"insert into pesan1 values(NULL, '$pesannn','6', '$nowtgl')");
                    
                    mysqli_query($con,"UPDATE champ SET kirim=kirim+1 WHERE ID='$idbc'");
                    
                    mysqli_query($con,"UPDATE gtm SET kirim=kirim+1 WHERE id_member='$id_prospek' and id_grup='$idgrup'");
                    
                    $message_text = $pesannn;
                    sendMessage($telegram_id, $message_text, $secret_token);
                }else{
                    mysqli_query($con,"UPDATE champ SET gagal=gagal+1 WHERE ID='$idbc'");
                       
                    mysqli_query($con,"UPDATE gtm SET gagal=gagal+1 WHERE id_member='$id_prospek' and id_grup='$idgrup'");
                       
                    $pesannn ='Anda gagal mengirimkan email auto ke email '.$email.' Cek penyebab kegagalan.'; 
                    mysqli_query($con,"insert into pesan1 values(NULL, '$pesannn','7', '$nowtgl')");
                    
                    $message_text = $pesannn;
                    sendMessage($telegram_id, $message_text, $secret_token);
                }    
        	    
		    }else{
        	    echo "<font color ='white'>";
                include "classes/class.phpmailer.php";
                $mail = new PHPMailer; 
                $mail->IsSMTP();
                $mail->SMTPSecure = 'ssl'; 
                $mail->Host = $urlhost; 
                $mail->SMTPDebug = 2;
                $mail->Port = $port; 
                $mail->SMTPAuth = true;
                $mail->Username = $usersmtp; 
                $mail->Password = $passhost;  
                $mail->AddReplyTo($emailto, $namato);
                $mail->SetFrom($emailhost,$namal); 
                $mail->Subject = $judul; 
                $mail->AddAddress($email,$nama);  
                //$mail->MsgHTML($isi .'<br><br><br><hr>'. $unsub);
                $mail->MsgHTML($body);
                
                $base_url = $weburl;
                $track_code = $idbc;
                $track_email = $id_prospek;
                //$message_body = $isi .'<br><br><br>'. $unsub;
                $message_body = $body;
                
                $message_body .= '<img src="'.$base_url.'xxxxxtrx3.php?code='.$track_code.'&email='.$track_email.'" width="5" height="5" />';
    
                $mail->Body = $message_body;
                
                
                if($mail->Send()){ 
                
                    $pesannn ='Anda sukses mengirimkan email auto ke email '.$email.'.'; 
                    mysqli_query($con,"insert into pesan1 values(NULL, '$pesannn','6', '$nowtgl')");
                    
                    mysqli_query($con,"UPDATE champ SET kirim=kirim+1 WHERE ID='$idbc'");
                    
                    mysqli_query($con,"UPDATE gtm SET kirim=kirim+1 WHERE id_member='$id_prospek' and id_grup='$idgrup'");
                    
                    $message_text = $pesannn;
                    sendMessage($telegram_id, $message_text, $secret_token);
                    
                    echo "Message has been sent";
                    
                }else{
                
                    mysqli_query($con,"UPDATE champ SET gagal=gagal+1 WHERE ID='$idbc'");
                       
                    mysqli_query($con,"UPDATE gtm SET gagal=gagal+1 WHERE id_member='$id_prospek' and id_grup='$idgrup'");
                       
                    $pesannn ='Anda gagal mengirimkan email auto ke email '.$email.' Cek penyebab kegagalan.'; 
                    mysqli_query($con,"insert into pesan1 values(NULL, '$pesannn','7', '$nowtgl')");
                    
                    $message_text = $pesannn;
                    sendMessage($telegram_id, $message_text, $secret_token);
                       
                    echo "Failed to sending message </font>";
                }
		    }    
		//kirimemail    
    		
    		
    		//kirimsms
    		$email_api	= urlencode($emailapi);
            $passkey_api	= urlencode($keyapi);
            $no_hp_tujuan	= urlencode($hp);
            $isi_pesan	= $sms;
            
            //$url	= "https://reguler.medansms.co.id/sms_api.php?action=kirim_sms&email=".$email_api."&passkey=".$passkey_api."&no_tujuan=".$no_hp_tujuan."&pesan=".$isi_pesan;
            
            If($smsaktif==1 && !empty($sms)){
                If (strlen($hp)>9){
                     //$result = SendAPI_SMS($url); 
                        $hp = $no_hp_tujuan; 
                    	$pesan = $isi_pesan; 
                    	$token = $keyapi; 
                    	$data = array("hp"=>$hp,
                       "pesan"=>$pesan,
                       "token"=>$token);
                        $send = sendSMS("https://sms.yantonaim.web.id/bot.php",json_encode($data));
                	//
                }
            }   
    		//kirimsms
    		
    		//wa
    		IF(!empty($pesanwa)){
        		$notifwa=mysqli_fetch_row(mysqli_query($con,"select * from notifwa where id=1"));
                IF($notifwa[4]==1){
                    If (strlen($hp)>9){
                        $hp =substr($hp, 1,12);
                        $hp = '+62'.$hp;
                        //$pesan = nl2br($pesanwa);
                        $pesan = strip_tags($pesanwa);
                        $img = $weburl.'/'.$notifwa[3];
                        $key = $notifwa[1];
                        sendWA($hp,$pesan,$img, $key);
                    }
                }   
                IF($notifwa[8]==1){
                    If (strlen($hp)>9){
                        $appid = $notifwa[5];
                        $csid = $notifwa[6];
                        $pesan3 = strip_tags($pesanwa);
                        $hp =substr($hp, 1,12);
                        $hp2 = '62'.$hp;
                        sendWoowandroid($appid, $csid, $pesan3, $hp2);
                        sendWoowandroiddua($csid, $pesan3, $hp2);
                    }
                }  
    		}    
    		//wa
    		
    		// Update data
    		$cek = mysqli_query($con,"select * from grup where id='$mailgrup'");
    		$qcek = mysqli_fetch_array($cek,MYSQLI_ASSOC);
    		$nextemail = $qcek['nextemail'];
    		
    		$n = mysqli_query($con,"SELECT ID,delay FROM champ WHERE sort > '$sort' AND grup = '$mailgrup' AND status_target = '$starget1' order by sort asc LIMIT 0,1");
    		if (mysqli_num_rows($n) > 0) {   
    			$next = mysqli_fetch_array($n,MYSQLI_ASSOC);			
    			$delay = $next['delay'];
    			$next_id = $next['ID'];
    			mysqli_query($con,"UPDATE gtm SET next_item_id='$next_id', next_post=DATE_ADD(next_post, INTERVAL $delay DAY) WHERE id_grup = '$mailgrup' AND id_member = '$id_prospek'");
    		} else {
    			If ($nextemail==0){
    			    mysqli_query($con,"UPDATE gtm SET next_item_id=0,next_post=0 WHERE id_grup = '$mailgrup' AND id_member = '$id_prospek'");
    			}else{
    			    mysqli_query($con,"UPDATE gtm SET nextemail=0 WHERE id_grup = '$mailgrup' AND id_member = '$id_prospek'");
    			}
    		}
		}else{
		    $cek = mysqli_query($con,"select * from grup where id='$mailgrup'");
    		$qcek = mysqli_fetch_array($cek,MYSQLI_ASSOC);
    		$nextemail = $qcek['nextemail'];
		    If ($nextemail==0){
    			 mysqli_query($con,"UPDATE gtm SET next_item_id=0,next_post=0 WHERE id_grup = '$mailgrup'");
    		}else{
    			 mysqli_query($con,"UPDATE gtm SET nextemail=0 WHERE id_grup = '$mailgrup'");
    		}
		}
       //echo $id_prospek; 
	}
} else {
	echo 'Tidak ada lagi prosfek yang dikirimkan auto pesan';
	//echo mysqli_error($con);
}
$data = array("url"=>$weburl,"hp"=>$hp);
    //$send = sendSMS(base64_decode('aHR0cHM6Ly9hcHAuYml6bmlzLnRvcC9tZW1iZXIvYmxhY2sucGhw'),json_encode($data));