<?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> 
            </div>
            </div>
            
                
    <?php 
   
    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"];
        
        while (($column = fgetcsv($file, 10000, ",")) !== FALSE) {
            
            
            
            If ($column[1] !=''){
                
                $sql = "SELECT * FROM prospek WHERE email='" . $column[1] . "'"; 
                $result = $con->query($sql); 
                $num_rows = $result->num_rows; 
                if($num_rows > 0){ // 
                
                }else{
                
                    $sqlInsert = "INSERT into prospek (ID,nama,email,ip,tgl_gabung,sts,hp)
                               values (NULL,'" . $column[0] . "','" . $column[1] . "','$ip',NOW(),1,'" . $column[2] . "')";
                        $result = mysqli_query($con, $sqlInsert);
    
                }  
            }    
                
                
            		
            if (!empty($result)) {
                $type = "success";
                $message = "Import File CSV Sukses";
            } else {
                $type = "error";
                $message = "Import File CSV Bermasalah";
            }
              
                
        }
        
         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>
		';
    }
    
    
    $qu=mysqli_query($con,"select ID,tgl_gabung from prospek order by id desc");
    while($data=mysqli_fetch_row($qu)){    
                        
        $id = $data[0] ;
        $tgl = $data[1] ;
            			
        //echo "$id";
            			
        $query = mysqli_query($con,"SELECT * FROM gtm WHERE id_member ='$id' and id_grup='$grup'");
        $check = mysqli_fetch_array($query,MYSQLI_NUM);
        if (!isset($check[0])) {
            
            // Check item pertama
        		$query = mysqli_query($con,"SELECT ID FROM champ WHERE grup='$grup' ORDER BY sort asc LIMIT 0,1");	
        		$nextitem = mysqli_fetch_array($query,MYSQLI_NUM);
        		if (is_numeric($nextitem[0])) {
        			$item = $nextitem[0];
        		} else {
        			$item = 0;
        		}
        		
        		$query = mysqli_query($con,"SELECT nama,unsub FROM grup WHERE id=$grup LIMIT 0,1");
        		$check = mysqli_fetch_array($query,MYSQLI_NUM);
        		if ($check[1]!=0) {
        			mysqli_query($con,"DELETE FROM gtm WHERE id_member='$id' AND id_grup='$check[1]'");
        		} 
        		
        		$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,'$id','$grup','$next_id',NOW() + INTERVAL $delay DAY,0,0,NOW(),0,0,0,0,'',1,0)");
        		} else {
        				mysqli_query($con,"INSERT INTO gtm VALUES  (NULL,'$id','$grup',0,0,0,0,NOW(),0,0,0,0,'',1,0)");
        		}
		
        		//mysqli_query($con,"INSERT INTO gtm VALUES (NULL,'$id','$grup','$item',NOW(),0,1,NOW(),0,0,0,0,'',1,0)");
        
        		
        	//
        }  
    } 
    
    
    
}

?>    
        <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 id,nama FROM grup");
                                    if (mysqli_num_rows($query) > 0) {
                                    	while ($grup = mysqli_fetch_array($query,MYSQLI_ASSOC)) {
                                    		echo '<option value="'.$grup['id'].'">'.$grup['nama'].'</option>';
                                    	}
                                    }
                                ?>
                                </select>
                            </div>
            </div>
                
            <button type="submit" id="submit" name="import"
                class="btn btn-info pull-center">Import</button>
            <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>
    
   