<?php
header('Access-Control-Allow-Origin: *');
header(
    'Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS'
);
header(
    'Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization'
);
header('Content-Type: application/json');
include '../../../../config/db.php';

include_once '../../../../vendor/firebase/php-jwt/src/BeforeValidException.php';
include_once '../../../../vendor/firebase/php-jwt/src/ExpiredException.php';
include_once '../../../../vendor/firebase/php-jwt/src/SignatureInvalidException.php';
include_once '../../../../vendor/firebase/php-jwt/src/JWT.php';

use \Firebase\JWT\JWT;

$postData = file_get_contents('php://input');
if (isset($postData) && !empty($postData)) {
    //Extract the data
    $request = json_decode($postData);

    //Validate data
    if (
        trim($request->username) === '' ||
        trim($request->fname) === '' ||
        trim($request->lname) === '' ||
        trim($request->email) === ''
    ) {
        $responseArray = [
            'message' => 'Required fields are missing.',
            'status' => -2,
        ];
        echo json_encode($responseArray);
        return http_response_code(406);
    }
    // Sanitize input
    $username = mysqli_real_escape_string($con, trim($request->username));
    $fname = mysqli_real_escape_string($con, trim($request->fname));
    $lname = mysqli_real_escape_string($con, trim($request->lname));
    $email = mysqli_real_escape_string($con, trim($request->email));
    $phone = '';
    $password = '';
    $role = 1;
    $behaviour = 0;
    $comments = '';
    $token = '';
    $dateTime = date("Y-m-d H:i:s");

    $isExistsQuery = "SELECT * FROM Users WHERE `email` = '$email' LIMIT 1";
    $isExistsResult = mysqli_query($con, $isExistsQuery);
    if (mysqli_num_rows($isExistsResult) == 0) {
        // Create user
        $query = "INSERT INTO `Users`(`userId`, `username`, `fname`, `lname`, `email`, `phone`, `password`, `role`, `behaviour`, `comments`, `isDeleted`, `token`, `status`, `dateCreated`, `dateModified`)
        VALUES (null,'$username','$fname','$lname','$email','$phone','$password','$role','$behaviour','$comments',0,'$token',1,'$dateTime','$dateTime')";


        $result = mysqli_query($con, $query);
        if ($result) {
            generateResponse($con->insert_id, $fname, $lname, 1);
        } else {
            echo json_encode([
                'status' => 0,
                'message' => mysqli_error($con),
            ]);
            http_response_code(400);
        }
    } else {
        while ($row = mysqli_fetch_assoc($isExistsResult)) {
            $prev_userId = $row['userId'];
            $prev_fname = $row['fname'];
            $prev_lname = $row['lname'];
            $prev_status = $row['status'];
        }
        generateResponse($prev_userId, $prev_fname, $prev_lname, $prev_status);
    }
}

function generateResponse($userId, $fname, $lname, $status)
{
    $secretKey = "sA6HTfF3DVheBwpaXAgC2gDqDteYusWRn73t9AdbggtE9RAXzWhAnr8TPaSQp3CC";
    $issuer_claim = "ayush"; // this can be the servername
    $audience_claim = "THE_AUDIENCE";
    $issuedat_claim = time(); // issued at
    $notbefore_claim = $issuedat_claim + 10; //not before in seconds
    $expire_claim = $issuedat_claim + (3600); // expire time in seconds
    $accessToken = array(
        "iss" => $issuer_claim,
        "aud" => $audience_claim,
        "iat" => $issuedat_claim,
        "nbf" => $notbefore_claim,
        "exp" => $expire_claim,
        "data" => array(
            "userId" => $userId,
            "fname" => $fname,
            "lname" => $lname,
            "status" => $status
        )
    );
    $refreshToken = array(
        "iss" => $issuer_claim,
        "aud" => $audience_claim,
        "iat" => $issuedat_claim,
        "nbf" => $notbefore_claim,
        "exp" => $expire_claim + (3600),
        "data" => array(
            "userId" => $userId,
            "fname" => $fname,
            "lname" => $lname,
        )
    );

    http_response_code(200);

    $accessJwt = JWT::encode($accessToken, $secretKey);
    $refreshJwt = JWT::encode($refreshToken, $secretKey);
    echo json_encode(
        array(
            "status" => 1,
            "message" => "Successful login.",
            "accessToken" => $accessJwt,
            "refreshToken" => $refreshJwt,
            "expireAt" => $expire_claim
        )
    );
}
