<?php
// INTERNAL endpoint - called from dashboard when user clicks "Generate New" under a specific key
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();

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

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

csrfVerify();

if (($user['reset_chances'] ?? 0) <= 0) {
    jsonResponse(['status' => 'error', 'message' => 'You have 0 reset chances remaining. Please contact admin to unlock more.']);
}

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


// 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'] = max(0, ($user['reset_chances'] ?? 100) - 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);

jsonResponse([
    'status' => 'success',
    'data' => [
        'new_key' => $newKeyValue
    ]
]);
