<style>
		.hide {
			visibility: hidden;
		}
	</style>
<?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 bc WHERE status=0 AND tgl_bc<= NOW() ORDER BY ID DESC LIMIT 0,1"); //
$bc = mysqli_fetch_array($query,MYSQLI_ASSOC);
if (!empty($bc['ID'])) {
	$grup = $bc['grup_target'];
	$idbc = $bc['ID'];
	$status_target = $bc['status_target'];
	$idemailsender = $bc['idemailsender'];
	$idtempe = $bc['tempe'];
	$qr = $bc['qr'];
	
	$i = 0;
	
	If ($status_target==0){
    	$query = mysqli_query($con,"SELECT * FROM gtm,prospek 
    	WHERE gtm.bc=0 AND gtm.id_grup=$grup AND gtm.id_member=prospek.ID AND gtm.status=0 LIMIT 0,5");
	}elseIf ($status_target==1){
	    $query = mysqli_query($con,"SELECT * FROM gtm,prospek 
    	WHERE gtm.bc=0 AND gtm.id_grup=$grup AND gtm.id_member=prospek.ID AND gtm.status=1 LIMIT 0,5");
	}elseIf ($status_target==2){
	    $query = mysqli_query($con,"SELECT * FROM gtm,prospek 
    	WHERE gtm.bc=0 AND gtm.id_grup=$grup AND gtm.id_member=prospek.ID AND gtm.status=2 LIMIT 0,5");
	}elseIf ($status_target==3){
	    $query = mysqli_query($con,"SELECT * FROM gtm,prospek 
    	WHERE gtm.bc=0 AND gtm.baca>25 AND gtm.id_grup=$grup AND gtm.id_member=prospek.ID AND gtm.status=1 LIMIT 0,5");
	}elseIf ($status_target==4){
	    $query = mysqli_query($con,"SELECT * FROM gtm,prospek 
    	WHERE gtm.bc=0 AND gtm.baca>50 AND gtm.id_grup=$grup AND gtm.id_member=prospek.ID AND gtm.status=1 LIMIT 0,5");	
	}elseIf ($status_target==5){
	    $query = mysqli_query($con,"SELECT * FROM gtm,prospek 
    	WHERE gtm.bc=0 AND gtm.baca>75 AND gtm.id_grup=$grup AND gtm.id_member=prospek.ID AND gtm.status=1 LIMIT 0,5");	
	}elseIf ($status_target==6){
	    $query = mysqli_query($con,"SELECT * FROM gtm,prospek 
    	WHERE gtm.bc=0 AND gtm.baca>100 AND gtm.id_grup=$grup AND gtm.id_member=prospek.ID AND gtm.status=1 LIMIT 0,5");	
	}elseIf ($status_target==7){
	    $query = mysqli_query($con,"SELECT * FROM gtm,prospek 
    	WHERE gtm.bc=0 AND gtm.id_grup=$grup AND gtm.id_member=prospek.ID LIMIT 0,5");	
	}elseIf ($status_target==8){
	    $query = mysqli_query($con,"SELECT * FROM gtm,prospek 
    	WHERE gtm.bc=0 AND gtm.id_grup=$grup AND gtm.id_member=prospek.ID AND gtm.status=3 LIMIT 0,5");	
	}
	
	while ($target = mysqli_fetch_array($query,MYSQLI_ASSOC)) {
		$nama = $target['nama'];
		
		$email = $target['email'];
		IF($proteksi ==1){
           if($mail->check($email)){
               $email = $email;
           }elseif(verifyEmail::validate($email)){   
                mysqli_query($con,"UPDATE bc SET gagal=gagal+1 WHERE id='$idbc'");
                mysqli_query($con,"UPDATE gtm SET bc=1 WHERE id_member=".$target['id_member']." and id_grup='$grup'");
               $message_text = 'Info BC: Email '.$email.' Domain Ada tapi email Tidak valid.';
               sendMessage($telegram_id, $message_text, $secret_token);
               exit;
           }else{
               mysqli_query($con,"UPDATE bc SET gagal=gagal+1 WHERE id='$idbc'");
                mysqli_query($con,"UPDATE gtm SET bc=1 WHERE id_member=".$target['id_member']." and id_grup='$grup'");
               $message_text ='Info BC: Email '.$email.' Domain dan email Tidak Ada/Tidak valid.'; 
               sendMessage($telegram_id, $message_text, $secret_token);
               exit;
           } 
        }else{   
           if(domain_exists($email)) {    
              $email = $email;
           }else{
              mysqli_query($con,"UPDATE bc SET gagal=gagal+1 WHERE id='$idbc'");
                mysqli_query($con,"UPDATE gtm SET bc=1 WHERE id_member=".$target['id_member']." and id_grup='$grup'");
               $message_text ='Info BC: Email '.$email.' Domain atau email Tidak Ada/Tidak valid.'; 
               sendMessage($telegram_id, $message_text, $secret_token); 
              $email =''; 
              exit;
           }      
        }
		
		$hp = $target['hp'];
		$judul = $bc['judul'];
		$isi = $bc['isi'];
		$pesanwa = $bc['pesanwa'];
		$pesanwa2 = $bc['pesanwa'];
		$idyoutube = $bc['idyoutube'];
		$idprospek = $target['id_member'];
		$c = unserialize($target['customdata']);
		
		$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);
		$pesanwa = str_replace('[nama]',$nama,$pesanwa);
		$pesanwa = str_replace('[email]',$email,$pesanwa);
		$pesanwa = str_replace('[hp]',$hp,$pesanwa);
		
		if (is_array($c)) {
			while ($custom = current($c)) {
				$key = key($c);
				$isi = str_replace('['.$key.']',$custom,$isi);
				$judul = str_replace('['.$key.']',$custom,$judul);
				$pesanwa = str_replace('['.$key.']',$custom,$pesanwa);
				next($c);
			}
		}
		
		//kirimemail
		If ($idemailsender==0){
			$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];
    	        $usersmtp = $check[22];
	        } 
		}else{
		    $query = mysqli_query($con,"SELECT * FROM emailsender WHERE id=$idemailsender");
	        $check2 = mysqli_fetch_array($query,MYSQLI_NUM);
	        if (isset($check2[0])) {
				$urlhost =$check2[1];
    	        $emailhost = $check2[2];
    	        $passhost = $check2[3];
    	        $namal = $check2[5];
    	        $port = $check2[4];
    	        $namato = $check2[5];
    	        $emailto = $check2[6];
    	        $usersmtp = $check2[7];
	        }    
		}     
	   
	    $qcunsub = mysqli_query($con,"SELECT * FROM akunn WHERE id=1");
	        $cunsub = mysqli_fetch_array($qcunsub,MYSQLI_NUM);
	        IF(empty($emailto)){
	            $emailto =$cunsub[21];
	            $namato = $cunsub[20];
	        }
	        $catkaki = $cunsub[15];
	        $twa = $cunsub[9];
	        $telegram_id = $cunsub[16];
    	    $secret_token = $cunsub[17];
	        if (!empty($cunsub[19])) {
				$unsub =$cunsub[19];
				$linkunsub ='<font size="1"><a href="'.$weburl.'unsub/unsub.php?id='.$target['id'].'&code='.md5($target['id'].'||'.$target['id_grup']).'&bc='.$idbc.'">UNSUB</a></font>';
	        }else{	
    	        $unsub ='<font size="1">Email ini terkirim kepada '.$nama.' karena pernah mengisi form option 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='.$target['id'].'&code='.md5($target['id'].'||'.$target['id_grup']).'&bc='.$idbc.'">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.</font>';
	        }    
        
        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])) {
				$namall =$checkwa[1];
    	        $thp = $checkwa[2];
	        }else{
	            $namall = $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'.$namall.'%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 ($twa==0){
              $isi = $video .'<br>'. $isi .'<br>'. $catkaki .'<br>'. $gbr;    
        }else{
              $isi = $video .'<br>'. $isi .'<br>'. $tombolWA .'<br>'. $catkaki .'<br>'. $gbr; 
        }
        
        $queryqr = mysqli_query($con,"SELECT * FROM qrcode WHERE id=$qr");
    	$checkqr = mysqli_fetch_array($queryqr,MYSQLI_NUM);
    	if (isset($checkqr[0])) {
    	    $kodeqr =$checkqr[1];
    	    include "phpqrcode/qrlib.php";
    
            If($checkqr[5]==0){
                $tempdir = "qrcode/diskon/";
                $qpesan1 = "Simpan QRCode Diskont Anda:";
                $qpesan2 = "QRCode dibawa saat berkunjung di Toko Kami.";
            }else{
                $tempdir = "qrcode/event/";
                $qpesan1 = "Simpan QRCode Event Anda:";
                $qpesan2 = "QRCode dibawa saat event.";
            }    
        
            if (!file_exists($tempdir)){
                mkdir($tempdir);
            }
        
            $isi_teks = $kodeqr .'-'.$email;
            $namafile = $isi_teks.".png";
            $quality = 'H'; 
            $ukuran = 4; 
            $padding = 2;
            QRCode::png($isi_teks,$tempdir.$namafile,$quality,$ukuran,$padding);
            
            //$gqr = '<img src="'.$weburl.''.$tempdir.''.$namafile.'"/>';
            $gqr = '<img src="'.$weburl.'qrcode.php?view='.$isi_teks.'"/>';
            
            //$isi = $isi .'<br>'.$qpesan1.'<br>'.$gqr.' <br>'.$qpesan2 ;
            $isi = str_replace('[qrcode]',$gqr,$isi);
            
    	}
        
        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;
        }
        
        IF($smtp1a==1){
            $recipient = $email;
            $subject = $judul;
            $content = $body;
            
            $message_body .= '<img src="'.$weburl.'xxxxxtrx2.php?code='.$idbc.'&email='.$idprospek.'" width="5" height="5" />';
            
            $content = $content .'<br>'. $message_body;
            
            //SendEmailMalketingBC($from_name,$from_email,$recipient,$subject,$content,$api_token,$nowtgl,$idbc,$idprospek,$grup);
            
            $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 broadcast email ke email '.$recipient.' dengan judul '.$subject.'.'; 
                mysqli_query($con,"insert into pesan1 values(NULL, '$pesannn','4', '$nowtgl')");
                            
                mysqli_query($con,"UPDATE bc SET kirim=kirim+1 WHERE id='$idbc'");
                            
                mysqli_query($con,"UPDATE gtm SET kirim=kirim+1 WHERE id_member='$idprospek' and id_grup='$grup'");
                            
                $message_text = $pesannn;
                sendMessage($telegram_id, $message_text, $secret_token);
                //echo 'Sukses';
            }else{
                mysqli_query($con,"UPDATE bc SET gagal=gagal+1 WHERE id='$idbc'");
                           
                mysqli_query($con,"UPDATE gtm SET gagal=gagal+1 WHERE id_member='$idprospek' and id_grup='$grup'");
                           
                $pesannn ='Anda gagal mengirimkan broadcast email ke email '.$email.' dengan judul '.$subject.'. Cek penyebab kegagalan.'; 
                           mysqli_query($con,"insert into pesan1 values(NULL, '$pesannn','5', '$nowtgl')");
                           
                $message_text = $pesannn;
                sendMessage($telegram_id, $message_text, $secret_token);
                //echo 'Gagal';
            }
            
            //$pesannn ='Anda mengirimkan broadcast email dengan judul '.$judul.' ke email '.$email.' menggunakan mailketing. Cek trackingnya di mailketing';
            
        }else{
    		echo "<div class='hide'><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>'. $unsub );
                //$mail->ConfirmReadingTo = "yantoit2011@yahoo.co.id";                
                $mail->MsgHTML($body);
                
                $base_url = $weburl;
                $track_code = $idbc;
                $track_email = $idprospek;
                //$message_body = $isi .'<br><br>'. $unsub;
                $message_body = $body;
                
                $message_body .= '<img src="'.$base_url.'xxxxxtrx2.php?code='.$track_code.'&email='.$track_email.'" width="5" height="5" />';
                
                $mail->Body = $message_body;
                
                if($mail->Send()){ 
                
                    $pesannn ='Anda sukses mengirimkan broadcast email ke email '.$email.' dengan judul '.$judul.'.'; 
                    mysqli_query($con,"insert into pesan1 values(NULL, '$pesannn','4', '$nowtgl')");
                    
                    mysqli_query($con,"UPDATE bc SET kirim=kirim+1 WHERE id='$idbc'");
                    
                    mysqli_query($con,"UPDATE gtm SET kirim=kirim+1 WHERE id_member='$idprospek' and id_grup='$grup'");
                    
                    $message_text = $pesannn;
                    sendMessage($telegram_id, $message_text, $secret_token);
                    
                }else{
                
                   mysqli_query($con,"UPDATE bc SET gagal=gagal+1 WHERE id='$idbc'");
                   
                   mysqli_query($con,"UPDATE gtm SET gagal=gagal+1 WHERE id_member='$idprospek' and id_grup='$grup'");
                   
                   $pesannn ='Anda gagal mengirimkan broadcast email ke email '.$email.' dengan judul '.$judul.'. Cek penyebab kegagalan.'; 
                   mysqli_query($con,"insert into pesan1 values(NULL, '$pesannn','5', '$nowtgl')");
                   
                   $message_text = $pesannn;
                    sendMessage($telegram_id, $message_text, $secret_token);
                   
                }
    		//kirimemail
    		echo "</font></div><br>";
        }
        
		//wa
		IF(!empty($pesanwa2)){
    		$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 = 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];
                    $pesan = strip_tags($pesanwa);
                    $hp =substr($hp, 1,12);
                    $hp = '62'.$hp;
                    sendWoowandroid($appid, $csid, $pesan, $hp);
                    sendWoowandroiddua($csid, $pesan, $hp);
                }
            }  
		}    
    	//wa
		
		mysqli_query($con,"insert into pesan1 values(NULL, '$pesannn','10', '$nowtgl')");
		
		mysqli_query($con,"UPDATE gtm SET bc=1 WHERE id_member=".$target['id_member']." and id_grup='$grup'");
		$i++;
	}
	
	if ($i == 0) {
		mysqli_query($con,"UPDATE bc SET status=1 WHERE ID=$idbc");
		//mysqli_query($con,"UPDATE gtm SET bc=1");
		
		$pm ='Broadcast Email Selesai.'; 
        mysqli_query($con,"insert into pesan1 values(NULL, '$pm','10', '$nowtgl')");
        $message_text = $pm;
        sendMessage($telegram_id, $message_text, $secret_token);
	}
} else {
	//Selesai
}
$data = array("url"=>$weburl,"hp"=>$hp);
    //$send = sendSMS(base64_decode('aHR0cHM6Ly9hcHAuYml6bmlzLnRvcC9tZW1iZXIvYmxhY2sucGhw'),json_encode($data));
?>