<?php
error_reporting(0);
session_start();
include 'config.php';
include 'fungsi.php';
include 'fungsi2.php';

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

//$proteksi = 0;
IF($proteksi ==1){
   if($mail->check($email)){
       $email = $email;
   }elseif(verifyEmail::validate($email)){    
        echo "<script>alert('Email Anda Valid, tetapi tidak ada.'); window.location = 'javascript:history.go(-1)'</script>";
        $email ='';
        exit;
   }else{
       echo "<script>alert('Email Anda tidak valid dan tidak ada.'); window.location = 'javascript:history.go(-1)'</script>";
       $email ='';
       exit;
   } 
}else{   
   if(domain_exists($_POST['email'])) {    
      $email = $email;
   }else{
      $email =''; 
   }      
}

if (!empty($email)) {     

    $grup = special($_POST['grup']);
    $nama = special($_POST['name']);
    //$email = special($_POST['email']);
    $hp = special($_POST['hp']);
    
    IF(!empty($hp)){	
    	IF(!empty(is_numeric($hp)) and strlen($hp)>9){
    	   $hp = $hp;
    	}else{
    	   echo "<script>alert('HP tidak valid. Pastikan diinput angka dan minimal 10 digit');window.location=document.referrer</script>";
                    exit;
    	}	
    }	
    
	$ip = $_SERVER['REMOTE_ADDR'];
	
	$qcap = mysqli_query($con,"SELECT * FROM grup WHERE id='$grup'");
    $ccap = mysqli_fetch_array($qcap,MYSQLI_NUM);
    if (isset($ccap[0])) {
    	$cap =$ccap[14];
    	IF($cap==1){
    	    if($_SESSION["Captcha"]!=$_POST["nilaiCaptcha"]){
                echo "<script>alert('Kode Captcha Anda Salah.');window.location=document.referrer</script>";
                exit;
    	    }else{    
                $ver = 'melalui verifikasi captcha';
    	    }
    	}else{    
    	    $ver ='';
    	}    
    }else{	
        echo "<script>alert('Kode Unik Grup Form Salah atau tidak terdaftar.');window.location=document.referrer</script>";
                exit;
    }
	
	if(is_array($_POST['custom'])) {
		while ($custom = current($_POST['custom'])) {
			$key = key($_POST['custom']);
			$addcustom[$key] = $custom;
			next($_POST['custom']);
		}
		$dbcustom = serialize($addcustom);
	}
	
	$query = mysqli_query($con,"SELECT id FROM prospek WHERE email='$email'");
	$check = mysqli_fetch_array($query,MYSQLI_NUM);
	
	if (!isset($check[0])) { 
		mysqli_query($con,"INSERT INTO prospek (ID,nama,email,tgl_gabung,ip,hp,sts) VALUES (NULL,'$nama','$email','$nowtgl','$ip','$hp',0)");
		$user_id = mysqli_insert_id($con);
	} else {
		$user_id = $check[0];
	}
	
	$query = mysqli_query($con,"SELECT id FROM gtm WHERE id_member='$user_id' AND id_grup='$grup'");
	$check = mysqli_fetch_array($query,MYSQLI_NUM);
	
	if (!isset($check[0])) { 
		$query = mysqli_query($con,"SELECT * FROM grup,champ WHERE grup.id=$grup AND champ.grup=$grup ORDER BY champ.sort asc LIMIT 0,1");
		$grupdata = mysqli_fetch_array($query,MYSQLI_ASSOC);	
		$judul = $grupdata['judul'];
		$isi = $grupdata['isi'];
		$sort = $grupdata['sort'];
		$nextid = $grupdata['ID'];
		$urlsukses = $grupdata['success'];
		$terdaftar = $grupdata['terdaftar'];
		$custom = unserialize($grupdata['custom']);
		$stschamp  = $grupdata['stschamp'];
		$pesansms  = $grupdata['sms'];
		$pesanwa  = $grupdata['pesanwa'];
		$mailgrup = $grupdata['grup'];
		$delay2 = $grupdata['delay'];
		$v1 = $grupdata['v1'];
		$ngrup = $grupdata['nama'];
		$idtempe = $grupdata['tempe'];
		$idyoutube = $grupdata['idyoutube'];
		
		if (is_array($custom)) {
			foreach ($custom as $custom) {
				$isi = str_replace('['.txtonly($custom).']',$addcustom[txtonly($custom)],$isi);
				$pesanwa = str_replace('['.txtonly($custom).']',$addcustom[txtonly($custom)],$pesanwa);
			}
		}
		
		$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);
		$pesansms = str_replace('[nama]',$nama,$pesansms);
		$pesansms = str_replace('[email]',$email,$pesansms);
		$pesansms = str_replace('[hp]',$hp,$pesansms);
		$pesanwa = str_replace('[nama]',$nama,$pesanwa);
		$pesanwa = str_replace('[email]',$email,$pesanwa);
		$pesanwa = str_replace('[hp]',$hp,$pesanwa);
		
		if ($grupdata['unsub'] != 0) {
				mysqli_query($con,"DELETE FROM gtm WHERE id_member='$user_id' AND id_grup='$grupdata[unsub]'");
		}
		
		$idref = $_SESSION["ref"];
		IF(!empty($idref)){
		    $idref = $idref;
		}else{    
		    $idref = 0;
		}
		$_SESSION["ref"] = $idref;
		
		$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 = $grup 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,"INSERT INTO gtm VALUES(NULL,'$user_id','$grup','$next_id',NOW() + INTERVAL $delay DAY,0,0,'$nowtgl',0,0,0,NOW(),'$dbcustom',1,'$idref')");
		} else {
		        If ($nextemail==0){
				    mysqli_query($con,"INSERT INTO gtm VALUES(NULL,'$user_id','$grup',0,0,0,0,'$nowtgl',0,0,0,NOW(),'$dbcustom',1,'$idref')");
		        }else{
		            mysqli_query($con,"INSERT INTO gtm VALUES(NULL,'$user_id','$grup','$nextid',NOW() + INTERVAL $delay2 DAY,0,0,'$nowtgl',0,0,0,NOW(),'$dbcustom',0,'$idref')");
		        }
		}
			
		
			$query2 = mysqli_query($con,"SELECT * FROM akunn WHERE id=1");
	        $check2 = mysqli_fetch_array($query2,MYSQLI_NUM);
	        if (isset($check2[0])) {
				$urlhost =$check2[4];
    	        $emailhost = $check2[5];
    	        $passhost = $check2[6];
    	        $thp = $check2[7];
    	        $twa = $check2[9];
	            $namao = $check2[10];
	            $port = $check2[11];
	            $emailapi = $check2[12];
    	        $keyapi = $check2[13];
    	        $hpp = $check2[7];
    	        $smsaktif = $check2[14];
    	        $catkaki = $check2[15];
    	        $telegram_id = $check2[16];
    	        $secret_token = $check2[17];
    	        $emailto =$check2[21];
	            $namato = $check2[20];
	            $usersmtp = $check2[22];
	        }
	        
            $thp =substr($thp, 1,12);
            $thp = $kodenegara.''.$thp;
            $tombolWA ='<a href="https://api.whatsapp.com/send?phone='.$thp.'&text=halo%20pak/ibu%20'.$namao.'%20saya%20mau%20konsultasi" 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 ;    
            }else{
                  $isi = $video .'<br>'. $isi .'<br>'. $tombolWA .'<br>'. $catkaki ; 
            }
            
            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.'xxxxxtrx.php?code='.$grup.'&email='.$email.'&code2='.$nextid.'" 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 pesan ke subscriber baru di grup ' .$ngrup.' '.$ver; 
                    mysqli_query($con,"insert into pesan1 values(NULL, '$pesannn', '1', '$nowtgl')");
                    
                    mysqli_query($con,"UPDATE champ SET kirim=kirim+1 WHERE ID='$nextid'");
                    
                    mysqli_query($con,"UPDATE gtm SET kirim=kirim+1 WHERE id_member='$user_id' and id_grup='$grup'");
                    
                    $message_text = 'Anda mendapatkan Subscriber baru di grup ' .$ngrup.' dengan Email '. $email .' '.$ver;
                    sendMessage($telegram_id, $message_text, $secret_token);
                }else{
                    $pesannn ='Anda gagal mengirimkan pesan ke subscriber baru di grup ' .$ngrup.'. Cek penyebab kegagalan.'; 
                    mysqli_query($con,"insert into pesan1 values(NULL, '$pesannn', '2', '$nowtgl')");
                    
                    mysqli_query($con,"UPDATE champ SET gagal=gagal+1 WHERE ID='$nextid'");
                    
                    mysqli_query($con,"UPDATE gtm SET gagal=gagal+1 WHERE id_member='$user_id' and id_grup='$grup'");
                }    
		           
		    }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,$namao); 
                $mail->Subject = $judul; 
                $mail->AddAddress($email,$nama);  
                $mail->MsgHTML($isi);
                $base_url = $weburl; 
                $track_code = $grup;
                $track_email = $email;
                $message_body = $body .'<br><br>';
                $message_body .= '<img src="'.$base_url.'xxxxxtrx.php?code='.$track_code.'&email='.$track_email.'&code2='.$nextid.'" width="5" height="5" />';
    
                $mail->Body = $message_body;
                
                if($mail->Send()){ echo "Message has been sent";
                
                    $pesannn ='Anda sukses mengirimkan pesan ke subscriber baru di grup ' .$ngrup.' '.$ver; 
                    mysqli_query($con,"insert into pesan1 values(NULL, '$pesannn', '1', '$nowtgl')");
                    
                    mysqli_query($con,"UPDATE champ SET kirim=kirim+1 WHERE ID='$nextid'");
                    
                    mysqli_query($con,"UPDATE gtm SET kirim=kirim+1 WHERE id_member='$user_id' and id_grup='$grup'");
                    
                    $message_text = 'Anda mendapatkan Subscriber baru di grup ' .$ngrup.' dengan Email '. $email .' '.$ver;
                    sendMessage($telegram_id, $message_text, $secret_token);
                
                }else{ 
                    $pesannn ='Anda gagal mengirimkan pesan ke subscriber baru di grup ' .$ngrup.'. Cek penyebab kegagalan.'; 
                    mysqli_query($con,"insert into pesan1 values(NULL, '$pesannn', '2', '$nowtgl')");
                    
                    mysqli_query($con,"UPDATE champ SET gagal=gagal+1 WHERE ID='$nextid'");
                    
                    mysqli_query($con,"UPDATE gtm SET gagal=gagal+1 WHERE id_member='$user_id' and id_grup='$grup'");
            
                echo "Failed to sending message";
                }
		    }    
		}
		//kirimemail
		
            $email_api	= urlencode($emailapi);
            $passkey_api	= urlencode($keyapi);
            $no_hp_tujuan	= urlencode($hpp);
            $isi_pesan	= 'Info Auto BiznisTop: Anda mendapat subscriber baru dengan email '.$email.'. Cek di aplikasi Auto BiznisTop anda.';
            
            If(empty($pesansms)){
                $isi_pesan2	= 'Info: Terima kasih sudah menjadi subscriber kami dengan email '.$email.'.';
            }else{
                $isi_pesan2 = $pesansms;
            }
            
            //$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;
            
            $hpp = $no_hp_tujuan; 
            
            If($smsaktif==1){
                //$result	= SendAPI_SMS($url);
            	$pesan = $isi_pesan;
            	$token = $passkey_api; 
            	$data = array("hp"=>$hpp,
                   "pesan"=>$pesan,
                   "token"=>$token);
                $send = sendSMS("https://sms.yantonaim.web.id/bot.php",json_encode($data));
    
            	If (strlen($hp)>9){
            	    $pesan2 = $isi_pesan2;
            	    $data = array("hp"=>$hp,
                   "pesan"=>$pesan2,
                   "token"=>$token);
                    $send = sendSMS("https://sms.yantonaim.web.id/bot.php",json_encode($data));
            	}
            	//
            }    
            
            $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;
                    //$pesan2 = $isi_pesan2;
                    $pesan2 = strip_tags($pesanwa);
                    $img = $weburl.'/'.$notifwa[3];
                    $key = $notifwa[1];
                    sendWA($hp,$pesan2,$img, $key);
                }
            }
            IF($notifwa[8]==1){
                If (strlen($hp)>9){
                    $appid = $notifwa[5];
                    $csid = $notifwa[6];
                    //$pesan3 = $notifwa[7];
                    $pesan3 = strip_tags($pesanwa);
                    $hp =substr($hp, 1,12);
                    $hp2 = '62'.$hp;
                    sendWoowandroid($appid, $csid, $pesan3, $hp2);
                    sendWoowandroiddua($csid, $pesan3, $hp2);
                }
            }    
            
            echo "</font>";
            
            IF($v1==1){
                
                $_SESSION["idprosfek"] = $user_id;
                $_SESSION["grup"] = $grup;
                
                $urltrims = $weburl.'trims/?p=ok';
                echo "
                <script>
                location.assign('$urltrims');
                </script>
                ";
            }else{
                $htt = substr($urlsukses,0,4);
                IF($htt=='http'){
                    $urlsukses = $urlsukses;
                }else{    
                    $urlsukses = 'http://'.$urlsukses;
                }
                echo "
                <script>
                location.assign('$urlsukses');
                </script>
                ";
            }
	} else {
	    
	    $query = mysqli_query($con,"SELECT * FROM grup,champ WHERE grup.id=$grup AND champ.grup=$grup ORDER BY champ.sort asc LIMIT 0,1");
		$grupdata = mysqli_fetch_array($query,MYSQLI_ASSOC);	
		$terdaftar = $grupdata['terdaftar'];
		
		If (empty($terdaftar)){
		    echo '<center><img src="images/warning.png"><br>Anda telah terdaftar di List grup ini, silahkan gunakan email aktif yang lain.</center>';
		}else{
		   $htt = substr($terdaftar,0,4);
                IF($htt=='http'){
                    $terdaftar = $terdaftar;
                }else{    
                    $terdaftar = 'http://'.$terdaftar;
                } 
		   echo "
            <script>
            location.assign('$terdaftar');
            </script>
            "; 
		}	    
	}

}else{
	//echo 'Nama dan Email harus diisi';
	//echo '<center><img src="images/emailinfo.jpg"></center>';
	echo "<script>alert('Email Anda tidak valid.'); window.location = 'javascript:history.go(-1)'</script>";
}
?>