<?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 '../../../../config/mail.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';

require '../../../../mail/libs/Exception.php';
require '../../../../mail/libs/PHPMailer.php';
require '../../../../mail/libs/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
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->token) === '' ||
        trim($request->email) === ''
    ) {
        $responseArray = [
            'message' => 'Required fields are missing.',
            'status' => -2,
        ];
        echo json_encode($responseArray);
        return http_response_code(406);
    }
    // Sanitize input
    $token = mysqli_real_escape_string($con, trim($request->token));
    $email = mysqli_real_escape_string($con, trim($request->email));

    // Create user
    $query = "SELECT * FROM Users WHERE `email` = '$email' LIMIT 1";
    $result = mysqli_query($con, $query);
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $originalToken = $row['token'];
            $userId = $row['userId'];
            $fname = $row['fname'];
            $lname = $row['lname'];
        }
        if ($originalToken == $token) {
            $user_id = mysqli_insert_id($con);

            updateToken($con, $user_id);

            $secretKey = "sA6HTfF3DVheBwpaXAgC2gDqDteYusWRn73t9AdbggtE9RAXzWhAnr8TPaSQp3CC";
            $issuer_claim = "ayush";
            $audience_claim = "THE_AUDIENCE";
            $issuedat_claim = time();
            $notbefore_claim = $issuedat_claim + 10;
            $expire_claim = $issuedat_claim + (3600);
            $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
                )
            );
            $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);
            $response = array(
                'status' => 'success',
                "accessToken" => $accessJwt,
                "refreshToken" => $refreshJwt,
                "expireAt" => $expire_claim
            );
        } else {
            $response = array(
                'status' => 'error',
                'code' => '-2',
                'message' => 'Invalid token.' . $query . ''
            );
        }
    } else {
        $response = array(
            'status' => 'error',
            'code' => '-3',
            'message' => 'Invalid email.'
        );
    }

    // Return response as JSON
    header('Content-Type: application/json');
    echo json_encode($response);
}


function updateToken($con, $userId)
{
    $token = bin2hex(random_bytes(20)); // token generator
    $update_query = "UPDATE Users SET token = '$token' WHERE userId = $userId";

    mysqli_query($con, $update_query);
}
