<?php
/**
 * static_paylink_lib.php
 * Shared logic between the dashboard UI (auth/static_paylink.php) and the
 * public API (payment/create_static_paylink.php), so both stay in sync.
 */

function sp_generate_link_id($conn) {
    do {
        $id = strtoupper(substr(bin2hex(random_bytes(5)), 0, 8));
        $checkRes = $conn->query("SELECT id FROM static_paylinks WHERE link_id = '$id'");
        $exists = $checkRes ? ($checkRes->num_rows > 0) : false;
    } while ($exists);
    return $id;
}

function sp_expiry_from_validity($validity) {
    if ($validity === 'lifetime') return null;
    $map = [
        '1d' => '+1 day', '3d' => '+3 days', '7d' => '+7 days',
        '1m' => '+1 month', '6m' => '+6 months', '12m' => '+12 months',
        '24m' => '+24 months', '48m' => '+48 months',
    ];
    $mod = $map[$validity] ?? '+7 days';
    return date('Y-m-d H:i:s', strtotime($mod));
}

/**
 * Creates a static paylink for a user. Returns:
 *   ['ok' => true,  'link_id' => 'ABCD1234']
 *   ['ok' => false, 'message' => '...']
 * Enforces the same plan-based static-paylink limit as the dashboard UI.
 */
function sp_create_link($conn, $userId, $userToken, $params) {
    $title = trim($params['title'] ?? '');
    $description = trim($params['description'] ?? '');
    $amount = (float)($params['amount'] ?? 0);
    $validity = in_array($params['validity'] ?? '7d', ['1d','3d','7d','1m','6m','12m','24m','48m','lifetime'], true)
        ? $params['validity'] : '7d';
    $paylinkType = (($params['paylink_type'] ?? 'normal') === 'redirect') ? 'redirect' : 'normal';
    $redirectUrl = trim($params['redirect_url'] ?? '');
    $collectName = !empty($params['collect_name']) ? 1 : 0;
    $collectMobile = !empty($params['collect_mobile']) ? 1 : 0;
    $collectEmail = !empty($params['collect_email']) ? 1 : 0;

    if ($title === '') return ['ok' => false, 'message' => 'Title is required.'];
    if ($amount < 1 || $amount > 100000) return ['ok' => false, 'message' => 'Amount must be between 1 and 100000.'];
    if ($paylinkType === 'redirect' && $redirectUrl === '') return ['ok' => false, 'message' => 'redirect_url is required when paylink_type is "redirect".'];

    $splLimit = getStaticPaylinkLimit($conn, $userId);
    $countRes = $conn->query("SELECT COUNT(*) AS c FROM static_paylinks WHERE user_token = '" . mysqli_real_escape_string($conn, $userToken) . "'");
    if (!$countRes) {
        return ['ok' => false, 'message' => 'Setup incomplete - static_paylinks table missing. Run sql/RUN_THIS_ALL_IN_ONE.sql.'];
    }
    $existingCount = (int)$countRes->fetch_assoc()['c'];

    if ($splLimit === -1) return ['ok' => false, 'message' => 'A subscription plan is required before creating Static Paylinks.'];
    if ($splLimit !== 0 && $existingCount >= $splLimit) return ['ok' => false, 'message' => "Static Paylink limit reached ({$splLimit} allowed on your current plan)."];

    $linkId = sp_generate_link_id($conn);
    $expiresAt = sp_expiry_from_validity($validity);

    $stmt = $conn->prepare("INSERT INTO static_paylinks (link_id, user_token, title, description, amount, paylink_type, redirect_url, collect_name, collect_mobile, collect_email, validity, expires_at, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Active')");
    if (!$stmt) return ['ok' => false, 'message' => 'Setup incomplete - static_paylinks table missing. Run sql/RUN_THIS_ALL_IN_ONE.sql.'];

    $stmt->bind_param("ssssdssiiiss", $linkId, $userToken, $title, $description, $amount, $paylinkType, $redirectUrl, $collectName, $collectMobile, $collectEmail, $validity, $expiresAt);
    $ok = $stmt->execute();
    $stmt->close();

    if (!$ok) return ['ok' => false, 'message' => 'Could not create paylink. Please try again.'];
    return ['ok' => true, 'link_id' => $linkId];
}
