<?php
include "../db/dBase.php";
$dbase = new dBase();
$tcon = $dbase->con;
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$dated = date("Y-m-d H:i");

$out_st = 'false';
$out_token = '';
$out_name = '';
$out_msg = 'Access denied';
$out_DP =''; 

// user Details
$ua = $dbase->getBrowser();
$browser=$ua['name'];
$os=$ua['platform'];
$thisip = $dbase->getUserIP();

$data = json_decode(file_get_contents("php://input"));

$username = $data->username;
$password = md5($data->password);
$api_key = uniqid();

if ($api_key != '' and $username != '' and $password != '') {
    $check_user_n = $dbase->CountQuery("SELECT `id` FROM user WHERE `username`='$username' AND `status`=0 AND `type`='SC'  ");
    if ($check_user_n == 1) {

        $check_u = $dbase->queryto_fetch_api("SELECT `id` FROM user WHERE `username`='$username' AND `status`=0 AND `type`='SC'  ");
        $ufound = $check_u['id'];

        $check_pass_n = $dbase->CountQuery("SELECT `id` FROM user WHERE  `id`='$ufound' AND `password`='$password' AND `type`='SC'  ");
        if ($check_pass_n == 1) {
            $check_p = $dbase->queryto_fetch_api("SELECT `id`,`userID`,`name`,`dp` FROM user WHERE `id`='$ufound' AND `password`='$password' AND `type`='SC'  ");
            $userID = $check_p['userID'];
            if ($userID != '') {
                
                $token_repeat_n = $dbase->CountQuery("SELECT  `id` FROM `access_log` WHERE `userID`='$userID' AND `status`=1 AND `ip`='$thisip' AND `browser`='$browser' AND `os`='$os' AND `type`='SC' ");

                $api_key_in=md5($api_key);
                if ($token_repeat_n != 0) {
                    
                    $dbase->execute("DELETE FROM `access_log` WHERE `userID`='$userID' AND `status`=1 AND `ip`='$thisip' AND `browser`='$browser' AND `os`='$os' AND `type`='SC' ");
                }
                $dbase->execute("INSERT INTO `access_log` (`userID`,`token`,`dated`,`ip`,`os`,`browser`,`type`)VALUES('$userID','$api_key_in','$dated','$thisip','$os','$browser','SC') ");

                $out_st = 'true';
                $out_token = $api_key;
                $out_name = $check_p['name'];
                $out_DP = $check_p['dp'];
                $out_msg = 'Hi '.$out_name.', welcome back. ';
            } else { $out_msg = 'Access denied, something went wrong';}
        } else { $out_msg = 'Access denied, wrong password';}

    } 

    else { $out_msg = 'Access denied, not authorized';}
} else { $out_msg = 'Access denied, invalid attempt';}

$out = array('status' => $out_st, 'msg' => $out_msg, 'token' => $out_token, 'name' => $out_name,'dp'=>$out_DP);
echo json_encode(array_filter($out));
