<?php
defined("BASEPATH") or exit("No direct access allowed");
?>
        
    <div class="card-header">

		    <nav aria-label="breadcrumb">
                      <ol class="breadcrumb bg-warning text-white-all">
                        <li class="breadcrumb-item"><a href="#"><i class="fas fa-tachometer-alt"></i> Home</a></li>
                        <li class="breadcrumb-item"><a href="#"><i class="far fa-file"></i> Prospek</a></li>
                        <li class="breadcrumb-item active" aria-current="page"><i class="fas fa-list"></i> Import</li>
                      </ol>
                    </nav>
                    
          </div> 
    <div class="row">
    
    <div class="card-body">
            <div class="alert alert-primary alert-has-icon p-4">
            <div class="alert-icon"><i class="far fa-lightbulb"></i></div>
            <div class="alert-body">
            <div class="alert-title">Petunjuk:</div>
            1. Ikuti petunjuk import file database email <a href="https://blog.biznis.top/2018/10/cara-import-dan-buat-file-email-extensi.html" target="_blank">Klik Disini.</a><br>
            2. Pastikan anda tidak mengimport database email dari hasil scrape atau mendapatkan email yang tidak benar.<br>
            3. Perhatikan format file CSVnya. Formatnya: nama,email,hp <br>
            4. Jangan hapus File CSV anda di komputer, untuk mengantisipasi jika ada masalah hosting anda, data email dapat di import kembali.<br>
            5. Agar tidak repot dengan import file, anda dapat mengintegrasikannya google sheet. Petunjuk <a href="https://blog.biznis.top/2019/07/integrasi-dengan-google-sheet-form.html" target="_blank">Klik Disini.</a> <br>
            6. Jika ada data email yang tidak masuk, kemungkinan terkena proteksi email spam sehingga terbaca email tidak valid dan tidak tersimpan. 
            </div>
            </div>
            
                
    <?php 
    
    $mail = new VerifyEmail();
    $mail->setStreamTimeoutWait(10);
    $mail->Debug= FALSE; 
    $mail->Debugoutput= 'html'; 
    $mail->setEmailFrom($emailakun);
   
    if (isset($_POST["import"])) {
    $fileName = $_FILES["file"]["tmp_name"];
    if ($_FILES["file"]["size"] > 0) {
        
        $file = fopen($fileName, "r");
        $ip = $_SERVER['REMOTE_ADDR'];
        
        $grup = $_POST["grup"];
        $stsimport = $_POST["stsimport"];
        
        while (($column = fgetcsv($file, 10000, ",")) !== FALSE) {
                    
            If (!empty($column[1])){
                
                $email = $column[1];
                
                //$proteksi = 0;
                IF($proteksi ==1){
                   if($mail->check($email)){
                       $email = $email;
                   }elseif(verifyEmail::validate($email)){    
                       $email ='';
                       exit;
                   }else{
                       $email ='';
                       exit;
                   } 
                }else{   
                   if(domain_exists($email)) {    
                       $email = $email;
                   }else{
                       $email =''; 
                   }      
                }
                
                if (!empty($email)) {
                    
                    
    				$query1 = mysqli_query($con,"SELECT ID FROM prospek WHERE email='" . $column[1] . "'");
    				$check1 = mysqli_fetch_array($query1,MYSQLI_NUM);
    				
    				if (!isset($check1[0])) { 
    					mysqli_query($con,"INSERT INTO prospek (ID,nama,email,ip,tgl_gabung,sts,hp) VALUES (NULL,'" . $column[0] . "','" . $column[1] . "','$ip','$nowtgl',0,'" . $column[2] . "')");
    					$user_id = mysqli_insert_id($con);
    				} else {
    					$user_id = $check1[0];
    				}
    				
                    $query2 = mysqli_query($con,"SELECT * FROM gtm WHERE id_member ='$user_id' and id_grup='$grup'");
    				$check2 = mysqli_fetch_array($query2,MYSQLI_NUM);
    				if (!isset($check2[0])) {
                
    					// Check item pertama
    					$queryq = 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($queryq,MYSQLI_ASSOC);	
                        		$judul = $grupdata['judul'];
                        		$isi = $grupdata['isi'];
                        		$sort = $grupdata['sort'];
                        		$nextid = $grupdata['ID'];
                        		$delay2 = $grupdata['delay'];
    					
    					$query4 = mysqli_query($con,"SELECT nama,unsub FROM grup WHERE id='$grup' LIMIT 0,1");
    					$check4 = mysqli_fetch_array($query4,MYSQLI_NUM);
    					if ($check4[1]!=0) {
    						mysqli_query($con,"DELETE FROM gtm WHERE id_member='$user_id' AND id_grup='$check4[1]'");
    					} 
    					
    					$cek = mysqli_query($con,"select * from grup where id=$grup");
                		$qcek = mysqli_fetch_array($cek,MYSQLI_ASSOC);
                		$nextemail = $qcek['nextemail'];
    					
    					$n = mysqli_query($con,"SELECT ID,delay FROM champ WHERE sort >= 0 AND grup = '$grup' order by ID 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,'$stsimport','$nowtgl',0,0,0,0,'$dbcustom',1,0)");
    					} else {
    					        If ($nextemail==0){
    							    mysqli_query($con,"INSERT INTO gtm VALUES(NULL,'$user_id','$grup',0,0,0,'$stsimport','$nowtgl',0,0,0,0,'$dbcustom',1,0)");
    					        }else{
                		            mysqli_query($con,"INSERT INTO gtm VALUES(NULL,'$user_id','$grup','$nextid',NOW() + INTERVAL $delay2 DAY,0,'$stsimport','$nowtgl',0,0,0,0,'$dbcustom',0,0)");
                		        }
    					}
            
    				}
                }
				$type = "success";
                $message = "Import File CSV Sukses pada Grup " . $grup;
            }else{    
                      		
            $type = "GAGAL";
            $message = "Import File CSV Gagal pada Grup " . $grup;
            
                
            }
              
        }
        
         echo '
		<div class="alert alert-success alert-dismissable" style="margin-top:20px">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            <h4><i class="icon glyphicon glyphicon-remove"></i> '.$message.'
            </div>
		';
    }
    
}

?>    
        <br>
        <form class="form-horizontal" action="" method="post" name="uploadCSV"
        enctype="multipart/form-data">
        <div class="input-row">
            
            <div class="form-group">
                            <label for="tiga" class="col-sm-2 control-label">Import File CSV Email</label>
                            <div class="col-sm-10">
                                <input
                type="file" name="file" id="file" accept=".csv">
                            </div>
            </div>
            
            <div class="form-group">
                            <label for="tiga" class="col-sm-2 control-label">Pilih Grup</label>
                            <div class="col-sm-10">
                                
                                <select name="grup" id="exampleFormControlSelect1" class="form-control">
                                <?php
                                    $query = mysqli_query($con,"SELECT grup.id as id, grup.nama as nama FROM grup,champ where grup.id=champ.grup group by grup.id");
                                    if (mysqli_num_rows($query) > 0) {
                                    	while ($grup = mysqli_fetch_array($query,MYSQLI_ASSOC)) {
                                    	    
                                    	  $query2 = mysqli_query($con,"SELECT count(id_member) FROM gtm WHERE id_grup = '$grup[id]'");
                                           $status = mysqli_fetch_array($query2,MYSQLI_NUM);
                                           $jml5 = $status[0];  
                                    	    
                                    		echo '<option value="'.$grup['id'].'">'.$grup['nama'].' (Group '. $grup['id'].') '.$jml5.' Prospek</option>';
                                    	}
                                    }
                                ?>
                                </select>
                                <i>Grup tidak tampil berarti belum dibuat pesan auto</i>
                            </div>
            </div>
            
            <div class="form-group">
                <label for="tiga" class="col-sm-6 control-label">Tentukan status prospek saat diimport</label>
                 <div class="col-sm-10">
                <select name="stsimport" id="exampleFormControlSelect1" class="form-control">
                <option value="0">Tidak Aktif</option>
                <option value="1">Aktif</option>
                <option value="2">Buyer</option>
                </select>
                </div>
            </div>
            <div class="col-sm-10">
            <button type="submit" id="submit" name="import"
                class="btn btn-primary">Import</button>
            </div>
            <br />
        
        </div>
        <div id="labelError"></div>
         </form>

        
<script type="text/javascript">
	$(document).ready(
	function() {
		$("#frmCSVImport").on(
		"submit",
		function() {

			$("#response").attr("class", "");
			$("#response").html("");
			var fileType = ".csv";
			var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+("
					+ fileType + ")$");
			if (!regex.test($("#file").val().toLowerCase())) {
				$("#response").addClass("error");
				$("#response").addClass("display-block");
				$("#response").html(
						"Invalid File. Upload : <b>" + fileType
								+ "</b> Files.");
				return false;
			}
			return true;
		});
	});
</script>
    </div>
    
   