<?php
// INTERNAL endpoint - called from dashboard when user clicks "Generate New" under a specific key
// Request/response are AES-256-GCM encrypted (see assets/crypto.js).
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();

if (!isLoggedIn()) {
    encryptedJsonResponse(['status' => 'error', 'message' => 'Not logged in'], 401);
}

$user = getUserById($_SESSION['user_id']);
if (!$user) {
    encryptedJsonResponse(['status' => 'error', 'message' => 'User not found'], 404);
}

$body = readEncryptedRequestBody();
$keyIndex = intval($body['key_index'] ?? -1);
if ($keyIndex < 0 || !isset($user['api_keys'][$keyIndex])) {
    encryptedJsonResponse(['status' => 'error', 'message' => 'Invalid key selected']);
}

if ($user['reset_chances'] <= 0) {
    encryptedJsonResponse(['status' => 'limit_reached', 'message' => 'No reset chances left. Unlock 10 more for a small fee.']);
}

// Regenerate just this one key (keep its custom label), spend one shared chance
$oldLabel = $user['api_keys'][$keyIndex]['label'] ?? 'Default';
$isCustom = strpos($oldLabel, 'Default') === false && $oldLabel !== '';
$newKeyValue = $isCustom ? generateCustomApiKey($oldLabel) : generateApiKey();

$user['api_keys'][$keyIndex]['key'] = $newKeyValue;
$user['api_keys'][$keyIndex]['created_at'] = nowIST()->format('Y-m-d H:i:s');
$user['reset_chances'] -= 1;

// Keep legacy single api_key field pointed at the first key, for old integrations
if (isset($user['api_keys'][0])) {
    $user['api_key'] = $user['api_keys'][0]['key'];
}

saveUser($user);

encryptedJsonResponse([
    'status' => 'success',
    'data' => [
        'new_key' => $newKeyValue,
        'reset_chances' => $user['reset_chances']
    ]
]);
