<?php

namespace App\Services\Referral;

use Illuminate\Support\Facades\DB;

class ReferralService
{
    public function awardIfUnderCap(int $referrerId, int $amountIrr): bool
    {
        $cap = (int) config('growth.referral_daily_cap', 5);
        $start = now()->startOfDay();
        $end = now()->endOfDay();
        $count = DB::table('referral_events')
            ->where('type', 'paid')
            ->whereBetween('created_at', [$start, $end])
            ->join('referral_links','referral_links.id','=','referral_events.link_id')
            ->where('referral_links.user_id', $referrerId)
            ->count();
        if ($count >= $cap) return false;
        DB::table('wallet_ledger')->insert([
            'user_id' => $referrerId,
            'type' => 'credit',
            'amount_irr' => $amountIrr,
            'reason' => 'referral_reward',
            'meta_json' => json_encode([]),
            'created_at' => now(), 'updated_at' => now(),
        ]);
        return true;
    }
}

