<?php
// INTERNAL endpoint - called from the logged-in user's dashboard "Payment Link" tool.
// Builds a pay.php link using the user's own API key, then shortens it.
// 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);
}

if (empty($user['api_keys'])) {
    encryptedJsonResponse(['status' => 'error', 'message' => 'You need at least one API key first.']);
}

if (!$user['gmail_connected']) {
    encryptedJsonResponse(['status' => 'error', 'message' => 'Connect your FamPay Gmail first (see the Connect card above).']);
}

$body = readEncryptedRequestBody();
$amount = floatval($body['amount'] ?? 0);
$redirectUrl = trim($body['redirect_url'] ?? '');
$linkName = trim($body['name'] ?? '');

if ($amount <= 0) {
    encryptedJsonResponse(['status' => 'error', 'message' => 'Please enter a valid amount.']);
}

if ($redirectUrl !== '' && !preg_match('#^https?://#i', $redirectUrl)) {
    encryptedJsonResponse(['status' => 'error', 'message' => 'Redirect URL must start with http:// or https://']);
}

if (strlen($linkName) > 60) {
    $linkName = substr($linkName, 0, 60);
}

// Always use the user's first (default) API key for generated links.
$apiKey = $user['api_keys'][0]['key'];

$params = [
    'api_key' => $apiKey,
    'amount' => $amount,
];
if ($redirectUrl !== '') $params['redirect_url'] = $redirectUrl;
if ($linkName !== '') $params['name'] = $linkName;

$fullUrl = getBaseUrl() . '/pay.php?' . http_build_query($params);

$code = createShortlink($fullUrl, $user['id']);
$shortUrl = getBaseUrl() . '/s.php?c=' . $code;

encryptedJsonResponse([
    'status' => 'success',
    'data' => [
        'short_url' => $shortUrl,
        'full_url' => $fullUrl,
        'amount' => $amount
    ]
]);
