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

$response = array("error" => FALSE);

$nama = mysqli_real_escape_string($con,$_POST['nama']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$hp = mysqli_real_escape_string($con,$_POST['hp']);
$grup = mysqli_real_escape_string($con,$_POST['grup']);

$ip = $_SERVER['REMOTE_ADDR'];
	
	$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 (nama,email,tgl_gabung,ip,hp,sts) VALUES ('$nama','$email',NOW(),'$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])) {
		// Check item pertama
		$query = mysqli_query($con,"SELECT ID,delay 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];
			$delay = $nextitem[1];
			IF($delay==0){
			    $delay = 1;
			}else{    
			    $delay = 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='$user_id' AND id_grup='$check[1]'");
		} 
		
		mysqli_query($con,"INSERT INTO gtm VALUES(NULL,'$user_id','$grup','$item',DATE_ADD(NOW(), INTERVAL -$delay DAY),0,0,'$nowtgl',0,0,0,NOW(),'',1,0)");
		
		
		$response["error"] = FALSE;
        $response["pesan"] = 'Sukses menyimpan data';
        echo json_encode($response);
		
		
	}else{
		$response["error"] = TRUE;
        $response["pesan"] = 'data sudah ada atau ID grup tidak terdaftar';
        echo json_encode($response);
	}
?>	