<?php
namespace App\Http\Controllers;
use App\Models\Coupon;
use App\Models\CouponUsage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CouponWebController extends Controller
{
    public function claim(Request $request)
    {
        $request->validate(['code' => 'required|string']);
        $coupon = Coupon::where('code', strtoupper(trim($request->code)))->first();

        if (!$coupon || !$coupon->isValid()) {
            return back()->withErrors(['coupon' => 'Invalid or expired coupon code.']);
        }

        $user = $request->user();
        $alreadyUsed = CouponUsage::where('coupon_id', $coupon->id)->where('user_id', $user->id)->exists();
        if ($alreadyUsed) {
            return back()->withErrors(['coupon' => 'You have already used this coupon.']);
        }

        DB::transaction(function () use ($coupon, $user) {
            $user->increment('bonus_balance', $coupon->amount);
            CouponUsage::create(['coupon_id' => $coupon->id, 'user_id' => $user->id, 'amount_credited' => $coupon->amount, 'used_at' => now()]);
            $coupon->increment('used_count');
        });

        return back()->with('success', 'Coupon applied! $' . number_format($coupon->amount, 2) . ' added to bonus account.');
    }
}
