<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Models\Coupon;
use App\Models\CouponUsage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CouponController extends Controller
{
    public function claim(Request $request)
    {
        $request->validate(['code' => 'required|string']);

        $coupon = Coupon::where('code', strtoupper(trim($request->code)))->first();

        if (!$coupon) {
            return response()->json(['success' => false, 'message' => 'Invalid coupon code.'], 422);
        }

        if (!$coupon->isValid()) {
            return response()->json(['success' => false, 'message' => 'This coupon is expired or no longer available.'], 422);
        }

        $user = $request->user();

        $alreadyUsed = CouponUsage::where('coupon_id', $coupon->id)
            ->where('user_id', $user->id)
            ->exists();

        if ($alreadyUsed) {
            return response()->json(['success' => false, 'message' => 'You have already used this coupon.'], 422);
        }

        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 response()->json([
            'success' => true,
            'message' => 'Coupon applied! $' . number_format($coupon->amount, 2) . ' added to your bonus account.',
            'amount'  => $coupon->amount,
        ]);
    }
}
