<?php

$r = array();
require_once __DIR__ . '/db_config.php';
require_once __DIR__ . '/encrypt.php';

if (isset($_POST["email"]) && isset($_POST["imei"]) && $_POST["pass"]) {
        
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD,DB_DATABASE) or die(mysql_error());

$email = $_POST['email'];
$IMEI = $_POST['imei'];
$password = $_POST['pass'];

$pass=new encryptdecrypt;
$decoded_password=$pass->encrypt($password);

$query="SELECT s.emailid,s.companyname,s.employeename,s.mobilenumber,empcompanytype,s.companytype,designation,IMEI,a.attendenceteam as team,
a.attendancesubgroup as subgroup, a.attendancegroup as `group`,f.latitude,f.longitude,b.geofencing,b.geo_distance,profilepic  
FROM signupdetails s 
LEFT JOIN attendanceuser a ON a.emailid=s.emailid AND a.companyname=s.companyname
INNER JOIN emp_facility emp ON emp.emp_id=s.emp_id AND a.emailid=emp.emp_emailid
INNER JOIN atmdetails f ON f.id = emp.atmdetail_id
INNER JOIN b2lcustomers b ON f.companyname=b.companyname
WHERE  s.password ='$decoded_password' AND s.deleted = 'no' AND s.emailid='$email' AND empcompanytype NOT LIKE '%sales%'";

/*rupha code*/
$query="SELECT s.emailid,s.companyname,s.employeename,s.mobilenumber,empcompanytype,s.companytype,s.designation,s.IMEI,a.attendenceteam as team,
a.attendancesubgroup as subgroup, a.attendancegroup as `group`,f.latitude,f.longitude,b.geofencing,b.geo_distance,s.profilepic  
FROM signupdetails s 
LEFT JOIN attendanceuser a ON a.emailid=s.emailid AND a.companyname=s.companyname
LEFT JOIN emp_facility emp ON emp.emp_id=s.emp_id AND s.emailid=emp.emp_emailid
LEFT JOIN atmdetails f ON f.id = emp.atmdetail_id
LEFT JOIN b2lcustomers b ON f.companyname=b.companyname
WHERE  s.password ='$decoded_password' AND s.deleted = 'no' AND s.emailid='$email' AND s.empcompanytype NOT LIKE '%sales%'";

    $result = mysqli_query($con,$query);
    
    if(!empty($result) && mysqli_num_rows($result) > 0){
        
        $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
        $row["profilepic"]=base64_encode($row["profilepic"]);
        
        if($row["IMEI"]=="no data available"){
            $r= $row;
            $r["s"] = 1;
            $imeiCheckResult= mysqli_query($con,"SELECT IMEI from  signupdetails WHERE IMEI='$IMEI'");
            if(mysqli_num_rows($imeiCheckResult) == 0){
                mysqli_query($con,"UPDATE signupdetails SET IMEI='$IMEI' WHERE emailid='$email'");
            }else{
                $r["s"] = 3;
                $r["m"]="This account already registered with another mobile";
            }
        }elseif($row["IMEI"]==$IMEI){
	        $r = $row;
            $r["s"] = 1;        
        }else{
            $r["s"] = 2;
            $r["m"]="This account is not registered with this mobile";
        }
    }else{
        $r["s"] = 0;
        $r["m"] ="Check your email and password";
    }
    
mysqli_close($con);               
echo json_encode($r);
}
?>