<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Coupon;
use Illuminate\Http\Request;

class CouponController extends Controller
{
    public function validate(Request $request)
    {
        $request->validate(['code'=>'required|string','order_total'=>'required|numeric|min:0']);
        $coupon = Coupon::where('code',strtoupper($request->code))->first();
        if(!$coupon || !$coupon->isValid($request->order_total))
            return response()->json(['success'=>false,'message'=>'Invalid or expired coupon code.'],422);
        return response()->json(['success'=>true,'coupon'=>$coupon,'discount'=>$coupon->calculateDiscount($request->order_total)]);
    }
}
