<?php
defined($security_key) or exit;

//------------------------------------------
// Get user_details
//------------------------------------------
$user_credentials = json_decode(decode_payload($input),true);
//Connect to DB
$pdo = dbConnect($dbname);
$username = $user_credentials['username'] ?? '';
//Define Query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = ?');
//Excute Query
$stmt->execute([$username]);

//SETUP SQL FOR LOGIN_COUNT
$sql_login = 'UPDATE users SET login_count = ? WHERE id = ?';

// Check if username exists. Verify user exists then verify
if ($stmt->rowCount() == 1) {
    $user_data = $stmt->fetch();
    $permission = userRights($user_data['view']);
    $profile = getProfile($user_data['settings'],$permission);
    $password = $user_credentials['password'];

    if ($user_data['login_count'] < 5){
        if (array_key_exists('resetkey', $user_credentials)){
                
                if ($user_credentials['resetkey'] == ''){
                    //Reset procedure
                    //STEP 1.A- Create resetkey
                    $headers = array('alg'=>'HS256','typ'=>'JWT');
                    $payload = array('username'=>$user_data['username'], 'exp'=>(time() + 1800));
                    $resetkey = generate_jwt($headers, $payload);
                    //STEP 1.B Store in DB
                    $sql = 'UPDATE users SET resetkey = ? WHERE id = ?';
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([$resetkey,$user_data['id']]);
                    //STEP 2- Send to user
                    $mail_location = (file_exists($_SERVER['DOCUMENT_ROOT'].'/custom/'.$domain.'/mail/email_template_reset.php') ? $_SERVER['DOCUMENT_ROOT'].'/custom/'.$domain.'/mail/email_template_reset.php' : './assets/mail/email_template_reset.php');
                    include_once $mail_location;
                    send_mail($user_data['email'],$subject,$message,'','');
                    //STEP 3- Update Login count
                    $login_attempt = $user_data['login_count'] + 1;
                    $stmt_login = $pdo->prepare($sql_login);
                    $stmt_login->execute([$login_attempt, $user_data['id']]);
                } 

        } else { //STANDARD LOGIN
            if (password_verify($password, $user_data['password'])) { 

                //Check valid userkey
                $valid_key = strtotime('+30 minutes',strtotime($user_data['lastlogin']));
                $valid = ($valid_key <= time())?0:1;

                //REFRESH USERKEY
                if ($user_data['userkey'] != '' && $valid == 0){
                    $user_data['userkey'] = bin2hex(random_bytes(25));
                    $sql_userkey = 'UPDATE users SET userkey = ? WHERE id = ?';
                    $stmt_userkey = $pdo->prepare($sql_userkey);
                    $stmt_userkey->execute([$user_data['userkey'], $user_data['id']]);
                }

                //REFRESH USERKEY
                if ($user_data['service'] != '' && $valid == 0){
                    $user_data['service'] = bin2hex(random_bytes(25));
                    $sql_service = 'UPDATE users SET service = ? WHERE id = ?';
                    $stmt_service = $pdo->prepare($sql_service);
                    $stmt_service->execute([$user_data['service'], $user_data['id']]);
                }

                $token = createCommunicationToken($user_data['userkey']);

                $user = array(
                    'id' => $user_data['id'],
                    'username' => $user_data['username'],
                    'email' => $user_data['email'],
                    'salesID' => $user_data['salesID'],
                    'partnerhierarchy' => $user_data['partnerhierarchy'],
                    'permission' => $permission,
                    'profile_name' => $user_data['settings'],
                    'profile' => $profile,
                    'service' => $user_data['service'],
                    'userkey' => $user_data['userkey'],
                    'language' => $user_data['language'],
                    'token' => $token
                );

                //Reset login count after succesfull attempt
                $login_attempt = 0;
                $stmt_login = $pdo->prepare($sql_login);
                $stmt_login->execute([$login_attempt, $user_data['id']]);

                //Encrypt results
                $messages = generate_payload($user);
                //Send results
                print_r($messages); 
                
            } 
            else {
                    //Update Login count with failed attempt
                    $login_attempt = $user_data['login_count'] + 1;
                    $stmt_login = $pdo->prepare($sql_login);
                    $stmt_login->execute([$login_attempt, $user_data['id']]);
                    //Send Response
                    http_response_code(403); //Not authorized
                }
            }
    } else {
        //User is blocked & send error
        $messages = generate_payload('1');
        //------------------------------------------
        //Send results
        //------------------------------------------
        echo $messages; 
    }
} elseif (array_key_exists('resetkey', $user_credentials)) {
    if ($user_credentials['resetkey'] != ''){

        //check if resetkey is still valid
        $is_resetkey_valid = is_jwt_valid($user_credentials['resetkey']);
    
        if($is_resetkey_valid) {
            $password = $user_credentials['password'];
    
            if (strlen(trim($password)) < 6){
                //Return bad request
                http_response_code(400);    
            } 
            else {
                //UPDATE PASSWORD BASED ON RESETKEY
                $passwordvalid = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare('UPDATE users SET password = ? WHERE resetkey = ? ');
                $stmt->execute([$passwordvalid, $user_credentials['resetkey']]);
            }
    
        } else {
            http_response_code(403);//Not authorized
        }
    
        //
    } else 
    {
        http_response_code(403);//Not authorized
    }

}
else 
{
    http_response_code(403);//Not authorized
}

?>