<?php

// $token = bin2hex(random_bytes(32));

// print_r($token);
function res($responce_code, $message, $data)
{
    return array("response_code" => $responce_code, "message" => $message, "data" => $data);
}

function response($response)
{
    // $res_header = "HTTP/1.0 401 Unauthorized";
    $res_header = "HTTP/1.0 {$response['response_code']} {$response['message']}";

    $headers = array("Content-Type: application/json","Access-Control-Allow-Origin: *","Access-Control-Allow-Headers: *", $res_header);
    http_response_code($response['response_code']);
    foreach ($headers as $header) {
        header($header);
    }

    return json_encode($response);
}

function auth_middleware()
{
    $headers = getallheaders();
    $token = isset($headers['Authorization']) ?  $headers['Authorization'] : '';
    

//   foreach ($headers as $header => $value) {
//     echo "$header: $value <br>";
//     }
    
    if ($token == '') {
        $response = response(res(401, "Unauthorized", ""));
        echo $response;
        return false;
    } else {

        $developer = Developer::find_by_query("SELECT * FROM " . Developer::$db_table . " WHERE token='{$token}' LIMIT 1");
        $developer = array_shift($developer);
        if ($developer) {
            $user = User::find_by_id($developer->user_id);
            if (!$user) {
                $response = response(res(401, "User not authorized", ''));
                echo $response;
                return false;
            }
        } else {

            $response = response(res(401, "Invalid Token", ''));
            echo $response;
            return false;
        }

        $response = response(res(200, "user authorized", $user));
        // echo $response;
        return $user->id;
    }
}

function generate_vnin()
{
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $nums = '0123456789';
    $nums_length = strlen($nums);

    $vnin = '';

    for ($i = 0; $i < 2; $i++) {

        $vnin .= $characters[rand(0, $charactersLength - 1)];
    }


    for ($i = 0; $i < 12; $i++) {

        $vnin .= $nums[rand(0, $nums_length - 1)];
    }


    for ($i = 0; $i < 2; $i++) {

        $vnin .= $characters[rand(0, $charactersLength - 1)];
    }

    return $vnin;
}