<?php

namespace App\Http\Controllers;

use App\Models\Coupon;
use Illuminate\Http\Request;

class CouponController extends Controller
{
    public function validateCoupon(Request $request)
    {
        $code = trim($request->coupon_code);

        $coupon = Coupon::code($code)
            ->active()
            ->validDates()
            ->notUsed()
            ->first();

        if (! $coupon) {
            return response()->json([
                'valid' => false,
                'message' => 'Coupon is invalid, inactive, expired, or already used.',
            ], 422);
        }

        return response()->json([
            'valid' => true,
            'id' => $coupon->id,
            'value' => $coupon->value,
            'type' => $coupon->type,
            'message' => 'Coupon applied successfully.',
        ]);
    }
}
