<?php
require("lib/config.php");

// =============== Get referral code api ===================================
$data  = $_REQUEST;
$sql = "SELECT * FROM customers where email = '".$_REQUEST['username']."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) 
{
    while($row = $result->fetch_assoc()) 
	{
        $customer[] = $row;
        $cid = $row["id"];
		
    }
    
    $seed = str_split('abcdefghijklmnopqrstuvwxyz'
                 .'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                 .'0123456789!@'); 
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 6) as $k) $rand .= $seed[$k];

$sql = "SELECT * FROM `referrals` WHERE `customer_id` = '".$cid."'";
$exist = $conn->query($sql);

if ($exist->num_rows >0) {
	$cell = $exist->fetch_assoc();
	$code = $cell["code"];
	$value = $cell["value"];
	$sql = "SELECT * FROM `referal_claim` WHERE `customer_id` = '".$cid."'";
	$claims = $conn->query($sql);
	if($claims->num_rows >0) {
	$claimsRow = $claims->fetch_assoc();
	$ref_created = $claimsRow["referrals_generated"];
	$ref_claimed = $claimsRow["referrals_claimed"];
	$value = $claimsRow["value"];
	
	} else {
	$ref_created = 0;
	$ref_claimed = 0;
	$value = 0;
	
	}
	
	
	$Res["message"] = "Referral Code Already Exists"; 
	$Res["status"] = "OK";
	$Res["code"] = $code;
	$Res["value"] = $value;
	$Res["ref_created"] = $ref_created;
	$Res["ref_claimed"] = $ref_claimed;
	$Res["value"] = $value;
	
	

} else {

   
  $code = "RF".$rand;
  $value = "0.8";
		
    
    			$sql = "INSERT INTO `referrals` (`id`, `customer_id`, `code`, `value`, `date_created`, `date_modified`) VALUES (NULL, '".$cid."', '".$code."', '".$value."', NOW() ,NOW() )";
    		$success = $conn->query($sql);
    		
    		
			
			
			
			
    	if($success) {
	$Res["message"] = "Referral Code Generated"; 
	$Res["status"] = "OK";
	$Res["code"] = $code;
	$Res["ref_created"] = 0;
	$Res["ref_claimed"] = 0;
	$Res["value"] = 0;
	 
	
	
	
	} else {
	$Res["message"] = "Error Generating Referral Code"; 
	$Res["status"] = "error"; 
	echo $conn->error;
	}
	}
	
	$sql = "SELECT * FROM credits where customer_id = '".$cid."' and is_used = 0";
	$result = $conn->query($sql);
	$credit_value = 0;
		if ($result->num_rows > 0) 
		{
		    	while($row = $result->fetch_assoc()) 
			{
		        $credit_value = $credit_value + $row['value'];
				
		    	}
		    	$Res["credit_value"] = $credit_value;
		    } else {
		    	$Res["credit_value"] = 0;
		    }
	
	
		
} else {
$Res["message"] = "Customer not found"; 
$Res["status"] = "error"; 
error_log("add to customers error: ".$conn->error);
}

	

	
	
	

	
	
echo json_encode(new ArrayObject($Res)); 
/*echo "<pre>";
print_r($Res);
//print_r($response);
echo "</pre>";*/
$conn->close();



?>