<?php

namespace App\Http\Controllers\Api;

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

class CouponController extends Controller
{
    /**
     * Validate a coupon code and return discount info.
     */
    public function validate(Request $request)
    {
        $request->validate([
            'code' => 'required|string|max:50',
            'subtotal' => 'nullable|numeric|min:0',
        ]);

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

        if (!$coupon) {
            return response()->json([
                'valid' => false,
                'message' => 'كود الخصم غير صالح',
            ], 422);
        }

        // Check date validity
        if ($coupon->start_date && $coupon->start_date > now()) {
            return response()->json([
                'valid' => false,
                'message' => 'كود الخصم غير نشط بعد',
            ], 422);
        }

        if ($coupon->end_date && $coupon->end_date < now()) {
            return response()->json([
                'valid' => false,
                'message' => 'انتهت صلاحية كود الخصم',
            ], 422);
        }

        // Check usage limit
        if ($coupon->max_uses && $coupon->used_count >= $coupon->max_uses) {
            return response()->json([
                'valid' => false,
                'message' => 'تم استنفاد كود الخصم',
            ], 422);
        }

        // Check minimum order amount
        if ($coupon->min_order_amount && $request->subtotal && $request->subtotal < $coupon->min_order_amount) {
            return response()->json([
                'valid' => false,
                'message' => "الحد الأدنى للطلب هو {$coupon->min_order_amount}",
            ], 422);
        }

        // Calculate discount
        $discount = 0;
        if ($request->filled('subtotal')) {
            $discount = $coupon->type === 'percentage'
                ? $request->subtotal * ($coupon->value / 100)
                : $coupon->value;

            if ($coupon->max_discount && $discount > $coupon->max_discount) {
                $discount = $coupon->max_discount;
            }
        }

        return response()->json([
            'valid' => true,
            'message' => 'كود الخصم صالح',
            'data' => [
                'code' => $coupon->code,
                'type' => $coupon->type,
                'value' => $coupon->value,
                'max_discount' => $coupon->max_discount,
                'min_order_amount' => $coupon->min_order_amount,
                'calculated_discount' => round($discount, 3),
            ],
        ]);
    }
}
