<?php
require 'config.php';
header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents("php://input"), true);
} else {
    $data = $_GET;
}

if (empty($data['refresh_token'])) {
    http_response_code(400);
    exit(json_encode(["error" => "Refresh token required"]));
}

// Fetch all valid refresh tokens
$tokens = findQuery("SELECT * FROM tbl_refresh_tokens WHERE expires_at > " . time());
$matched = false;

foreach ($tokens as $row) {
    if (password_verify($data['refresh_token'], $row['token'])) {
        $matched = $row;
        break;
    }
}

if (!$matched) {
    http_response_code(401);
    exit(json_encode(["error" => "Invalid or expired refresh token"]));
}

// Issue new access token
$payload = [
    "iss" => "jwt_api",
    "iat" => time(),
    "exp" => time() + JWT_EXPIRE,
    "user_id" => $matched['user_id']
];

$new_access_token = \Firebase\JWT\JWT::encode($payload, JWT_SECRET, JWT_ALGO);

echo json_encode([
    "access_token" => $new_access_token,
    "expires_in" => JWT_EXPIRE
]);
