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

class CouponController extends Controller
{
    public function index() { return response()->json(['success'=>true,'data'=>Coupon::latest()->get()]); }
    public function store(Request $request)
    {
        $data = $request->validate(['code'=>'required|unique:coupons','type'=>'required|in:percent,flat,shipping','value'=>'required|numeric','min_order'=>'nullable|numeric','max_discount'=>'nullable|numeric','usage_limit'=>'nullable|integer','expires_at'=>'nullable|date','is_active'=>'boolean']);
        $data['code'] = strtoupper($data['code']);
        return response()->json(['success'=>true,'data'=>Coupon::create($data)],201);
    }
    public function update(Request $request, int $id)
    {
        $coupon = Coupon::findOrFail($id);
        $coupon->update($request->validate(['value'=>'numeric','is_active'=>'boolean','expires_at'=>'nullable|date']));
        return response()->json(['success'=>true,'data'=>$coupon]);
    }
    public function destroy(int $id) { Coupon::findOrFail($id)->delete(); return response()->json(['success'=>true]); }
}
