<?php
include "library.php";
$obj=new Library();

$fcode=@$_POST['device_id'];
$registration_key=@$_POST['company_code'];


/*$fcode="M186258360823";
$registration_key="1q2w3e4r5t6y";*/



$query2="select f_id ,DATE_FORMAT(expiry_date,'%Y-%m-%d %T.000000') expiry_date from fingerprint where registration_key='$registration_key' AND f_code='$fcode' ";
$sql2=$obj->generalquery($query2);
$arr2=mysqli_fetch_array($sql2);
$count=mysqli_num_rows($sql2);


$query="select UID , BranchName, DATE_FORMAT(expiry_date,'%Y-%m-%d %T.000000') expiry_date, total_apk,subscription_days  from company_master where registration_key='$registration_key'";
$sql=$obj->generalquery($query);
$arr=mysqli_fetch_array($sql);
$company_count=mysqli_num_rows($sql);
$total_apk=$arr['total_apk'];

$device_count=$obj->select_count("fingerprint"," registration_key='$registration_key' ");
$reponce_arr=array();

if($count==1)
{
		$f_id=$arr2['f_id'];
		$reponce_arr['err_status']=1;
		$reponce_arr['msg']="Device Already Exist";
		$reponce_arr['CompanyId']=$arr['UID'];
		$reponce_arr['CompanyName']=$arr['BranchName'];
		$reponce_arr['ExpiryDate']=$arr2['expiry_date'];
		$reponce_arr['UserId']=$f_id;
}
else
{

if($company_count==1)
{
	if($device_count<=$total_apk)
	{
		$subscription_days=$arr['subscription_days'];
		
		$expiry_date=Date('Y-m-d', strtotime('+'.$subscription_days.' days'));
		
		$data=array("f_code"=>$fcode,"registration_key"=>$registration_key,"expiry_date"=>$expiry_date,"UID"=>$arr['UID']);
		$ret=$obj->insert("fingerprint",$data);		
		$f_id=$obj->last_insert_id("fingerprint","f_id");
		
		$reponce_arr['err_status']=1;
		$reponce_arr['msg']="Device Registered Successfull";
		$reponce_arr['CompanyId']=$arr['UID'];
		$reponce_arr['CompanyName']=$arr['BranchName'];
		$reponce_arr['ExpiryDate']=$expiry_date." 00:00:00.000000";
		$reponce_arr['UserId']=$f_id;
	}
	else
	{
	$reponce_arr['err_status']=0;
	$reponce_arr['msg']="Device limit exceed";
	}
}
else
{
$reponce_arr['err_status']=0;
$reponce_arr['msg']="Invalid Registration Key";	
}
}
echo json_encode($reponce_arr);
?>