<?php

require_once '../resources/base_path_include.php';

require_once "../resources/includes/config.php"; // use require for mandatory files
 require_once '../resources/lib/function.php';

require_once "../vendor/autoload.php";
require_once '../resources/jwt/jwt_config.php';

require_once 'authenticate.php';
require_once "resources/lib/cron_jobs/firebase_notification/remove_fcm_token_function.php";

$postdata = json_decode(file_get_contents("php://input"), true);
if(!isset($postdata['function_type']) or $postdata['function_type']!="logout_function" or $postdata['jwt_token'] == "" ) {
    errorreturn("Invalid parameters.");
}


$jwttoken = $postdata['jwt_token'] ?? null;
if (!$jwttoken) {
    errorreturn("JWT token is required.");
}

$jwt_validate = authenticate_jwt($jwttoken);
if ($jwt_validate === false) {
    errorreturn("Session expired. Kindly sign in again.");
}

$userid       = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username     = $jwt_validate->data->username;
$role         = $jwt_validate->data->role;

// Update user log status
$sql  = "UPDATE user_log SET status = ? WHERE jwttoken = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([0, $jwttoken]);

// Remove FCM Token
$fcmToken = isset($postdata['fcm_token']) ? trim($postdata['fcm_token']) : '';
if ($fcmToken === '') {
    errorreturn("FCM token is required.");
}
removeFCMToken($conn_rjllearning, $fcmToken, $userid);

// If needed, print JWT data
print_r($jwt_validate);


?>