<?php
/**
 * Refresh Token Endpoint (Secure Cookie Based)
 */

use App\Core\Database;
use Firebase\JWT\JWT;

// 1. Get Refresh Token from HttpOnly Cookie
$refreshToken = $_COOKIE['refresh_token'] ?? null;

if (!$refreshToken) {
    json_error('Refresh token is required', 401);
}

$db = Database::getInstance();
$refreshTokenHash = hash('sha256', $refreshToken);

// 2. Verify in DB
$stmt = $db->prepare("SELECT * FROM users WHERE refresh_token_hash = ? AND is_active = 1 LIMIT 1");
$stmt->execute([$refreshTokenHash]);
$user = $stmt->fetch();

if (!$user) {
    json_error('Invalid refresh token', 401);
}

// 3. Generate New Access Token
$secret = $_ENV['JWT_SECRET'] ?? null;
if (!$secret) {
    json_error('Server configuration error', 500);
}

$payload = [
    'user_id'   => $user['id'],
    'tenant_id' => $user['tenant_id'], // Now including tenant_id
    'role'      => $user['role'],
    'exp'       => time() + (15 * 60) // 15 minutes
];

$token = JWT::encode($payload, $secret, 'HS256');

json_success([
    'access_token' => $token
]);
