<?php
require_once __DIR__ . '/../app/bootstrap.php';

use App\Core\Auth;
use App\Core\Database;
use App\Core\Response;
use App\Core\Security;
use App\Core\WalletService;

Auth::requireLogin('public/login.php');
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !verify_csrf()) {
    Response::json(['ok' => false, 'message' => 'Invalid request.'], 419);
}
if (!Security::rateLimit('reward-redeem:' . Auth::id(), 15, 3600)) {
    Response::json(['ok' => false, 'message' => 'Too many redemption requests. Try again later.'], 429);
}

$data = request_data();
$points = max(0, (int)($data['points'] ?? 0));
$minimum = max(1, (int)setting('minimum_redeem', '0'));
$value = max(0, (float)setting('point_value', '1'));
if ($points < $minimum) {
    Response::json(['ok' => false, 'message' => 'Minimum redeemable points: ' . $minimum . '.'], 422);
}
if ($value <= 0) {
    Response::json(['ok' => false, 'message' => 'Reward conversion is currently unavailable.'], 422);
}

try {
    $amount = Database::transaction(function () use ($points, $value): float {
        $entries = Database::fetchAll(
            'SELECT id,points FROM reward_points WHERE user_id=? AND (expires_at IS NULL OR expires_at>=CURDATE()) ORDER BY id FOR UPDATE',
            [Auth::id()]
        );
        $balance = array_sum(array_map(static fn(array $entry): int => (int)$entry['points'], $entries));
        if ($points > $balance) {
            throw new RuntimeException('Insufficient reward points.');
        }
        $amount = round($points * $value, 2);
        Database::execute(
            'INSERT INTO reward_points (user_id,points,point_type,reference_type,reference_id,created_at) VALUES (?,? ,"redeem","wallet",NULL,NOW())',
            [Auth::id(), -$points]
        );
        if (!WalletService::credit((int)Auth::id(), 'purchase', $amount, 'Reward points conversion')) {
            throw new RuntimeException('Could not credit the purchase wallet.');
        }
        return $amount;
    });
    Security::logActivity(Auth::id(), 'reward_points_redeemed', ['points' => $points, 'wallet_credit' => $amount]);
    Response::json(['ok' => true, 'points_redeemed' => $points, 'wallet_credit' => $amount, 'message' => 'Points converted to purchase wallet.']);
} catch (Throwable $exception) {
    error_log('Reward redemption failed: ' . $exception->getMessage());
    Response::json(['ok' => false, 'message' => $exception instanceof RuntimeException ? $exception->getMessage() : 'Reward redemption failed.'], 422);
}
