<?php
namespace App\Http\Controllers\API\Vendor;

use App\Http\Controllers\Controller;
use App\Models\Coupon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class VendorCouponController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $coupons = Coupon::where('vendor_id', $request->user()->vendor->id)->latest()->paginate(15);
        return response()->json($coupons);
    }
    public function store(Request $request): JsonResponse
    {
        $vendorId = $request->user()->vendor->id;
        $data = $request->validate([
            'code'             => 'required|string|unique:coupons|max:50',
            'type'             => 'required|in:fixed,percentage',
            'value'            => 'required|numeric|min:0',
            'min_order_amount' => 'nullable|numeric|min:0',
            'max_discount'     => 'nullable|numeric|min:0',
            'usage_limit'      => 'nullable|integer|min:1',
            'per_user_limit'   => 'integer|min:1',
            'starts_at'        => 'nullable|date',
            'expires_at'       => 'nullable|date',
            'is_active'        => 'boolean',
        ]);
        $data['vendor_id'] = $vendorId;
        $coupon = Coupon::create($data);
        return response()->json(['message' => 'Coupon created.', 'coupon' => $coupon], 201);
    }
    public function show(Request $request, int $id): JsonResponse
    {
        $coupon = Coupon::where('vendor_id', $request->user()->vendor->id)->withCount('usages')->findOrFail($id);
        return response()->json(['coupon' => $coupon]);
    }
    public function update(Request $request, int $id): JsonResponse
    {
        $coupon = Coupon::where('vendor_id', $request->user()->vendor->id)->findOrFail($id);
        $coupon->update($request->only(['is_active', 'expires_at', 'usage_limit']));
        return response()->json(['message' => 'Coupon updated.', 'coupon' => $coupon]);
    }
    public function destroy(Request $request, int $id): JsonResponse
    {
        Coupon::where('vendor_id', $request->user()->vendor->id)->findOrFail($id)->delete();
        return response()->json(['message' => 'Coupon deleted.']);
    }
}
