<?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',
            'amount' => 'required|numeric|min:0',
        ]);

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

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

        if (!$coupon->is_active) {
            return response()->json(['success' => false, 'message' => 'This coupon is inactive'], 422);
        }

        if ($coupon->expires_at && now()->gt($coupon->expires_at)) {
            return response()->json(['success' => false, 'message' => 'This coupon has expired'], 422);
        }

        if ($coupon->usage_limit && $coupon->used_count >= $coupon->usage_limit) {
            return response()->json(['success' => false, 'message' => 'This coupon has reached its usage limit'], 422);
        }

        if ($coupon->starts_at && now()->lt($coupon->starts_at)) {
            return response()->json(['success' => false, 'message' => 'This coupon is not valid yet'], 422);
        }

        if ($request->amount < $coupon->min_order_amount) {
            return response()->json([
                'success' => false,
                'message' => 'Minimum order amount ₹' . $coupon->min_order_amount . ' required',
            ], 422);
        }

        $discount = $coupon->calculateDiscount($request->amount);

        return response()->json([
            'success' => true,
            'data' => [
                'coupon' => $coupon,
                'discount' => $discount,
                'final_amount' => $request->amount - $discount,
            ],
        ]);
    }

    // Admin CRUD
    public function index(Request $request)
    {
        $coupons = Coupon::orderBy('created_at', 'desc')->paginate(15);
        return response()->json(['success' => true, 'data' => $coupons]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'code' => 'required|string|unique:coupons',
            'type' => 'required|in:percentage,fixed',
            'value' => 'required|numeric|min:0',
        ]);

        $coupon = Coupon::create([...$request->all(), 'code' => strtoupper($request->code)]);
        return response()->json(['success' => true, 'data' => $coupon], 201);
    }

    public function update(Request $request, Coupon $coupon)
    {
        $coupon->update($request->all());
        return response()->json(['success' => true, 'data' => $coupon]);
    }

    public function destroy(Coupon $coupon)
    {
        $coupon->delete();
        return response()->json(['success' => true, 'message' => 'Coupon deleted']);
    }
}
