<?php
/**
 * Ragreen - Loyalty points helper
 * Every user gets a loyalty_points row at registration (see auth/register.php),
 * so awarding points is always an UPDATE, never an insert-or-update race.
 *
 * The formula itself (points per dollar spent, points per new listing) is
 * admin-configurable via the `settings` table - see api/admin/settings.php
 * and admin.html's Settings tab - rather than hardcoded, so support can
 * tune it without a code deploy.
 */

require_once __DIR__ . '/settings.php';

function points_per_dollar_spent(PDO $pdo): float
{
    return (float) get_setting($pdo, 'points_per_dollar_spent', '1');
}

function points_per_new_listing(PDO $pdo): int
{
    return (int) get_setting($pdo, 'points_per_new_listing', '2');
}

/**
 * Award (or deduct, with a negative $points) loyalty points and log why.
 * Call this INSIDE an existing PDO transaction where relevant (e.g. checkout)
 * so points and the triggering action commit/rollback together.
 */
function award_loyalty_points(PDO $pdo, int $userId, int $points, string $reason): void
{
    if ($points === 0) {
        return;
    }

    $stmt = $pdo->prepare('UPDATE loyalty_points SET points_balance = GREATEST(0, points_balance + ?) WHERE user_id = ?');
    $stmt->execute([$points, $userId]);

    $stmt = $pdo->prepare('INSERT INTO loyalty_transactions (user_id, points, reason) VALUES (?, ?, ?)');
    $stmt->execute([$userId, $points, $reason]);
}
