<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\DiscountCode;
use App\Models\SubscriptionPackage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class DiscountController extends Controller
{
    /**
     * POST /api/discount/apply
     * Body: code, package_id (optional)
     * Validates and returns the computed discount amount; does NOT consume.
     * Consumption happens at the checkout step.
     */
    public function apply(Request $request)
    {
        $data = $request->validate([
            'code' => ['required','string','max:64'],
            'package_id' => ['nullable','integer','exists:subscription_packages,id'],
        ]);

        $user = Auth::user();
        $code = strtoupper(trim($data['code']));

        $coupon = DiscountCode::where('code', $code)
            ->where('status', 'active')
            ->where(function ($q) {
                $q->whereNull('valid_from')->orWhere('valid_from', '<=', now());
            })
            ->where(function ($q) {
                $q->whereNull('valid_until')->orWhere('valid_until', '>=', now());
            })
            ->first();

        if (! $coupon) {
            return response()->json(['success' => false, 'message' => 'کد تخفیف معتبر نیست'], 404);
        }

        if ($coupon->usage_limit && $coupon->used_count >= $coupon->usage_limit) {
            return response()->json(['success' => false, 'message' => 'سقف استفاده از این کد به پایان رسیده'], 422);
        }

        if ($coupon->per_user_limit) {
            $userUses = DB::table('discount_code_usage')
                ->where('discount_code_id', $coupon->id)
                ->where('user_id', $user->id)
                ->count();
            if ($userUses >= $coupon->per_user_limit) {
                return response()->json(['success' => false, 'message' => 'سقف استفاده‌ی شخصی از این کد تکمیل شده'], 422);
            }
        }

        $packagePrice = 0;
        if (! empty($data['package_id'])) {
            $pkg = SubscriptionPackage::find($data['package_id']);
            if (! $pkg) {
                return response()->json(['success' => false, 'message' => 'پکیج یافت نشد'], 404);
            }
            $packagePrice = (int) ($pkg->discount_price ?: $pkg->price);

            if ($coupon->applicable_packages) {
                $list = is_array($coupon->applicable_packages)
                    ? $coupon->applicable_packages
                    : json_decode($coupon->applicable_packages, true) ?: [];
                if (! empty($list) && ! in_array($pkg->id, $list)) {
                    return response()->json([
                        'success' => false,
                        'message' => 'این کد تخفیف برای پکیج انتخابی معتبر نیست',
                    ], 422);
                }
            }
        }

        if ($coupon->min_purchase && $packagePrice < $coupon->min_purchase) {
            return response()->json([
                'success' => false,
                'message' => 'حداقل مبلغ خرید برای این کد رعایت نشده',
            ], 422);
        }

        $discountAmount = $coupon->type === 'percentage'
            ? (int) round(($packagePrice * $coupon->value) / 100)
            : (int) $coupon->value;

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

        return response()->json([
            'success' => true,
            'data' => [
                'code' => $coupon->code,
                'type' => $coupon->type,
                'value' => $coupon->value,
                'discount_amount' => $discountAmount,
                'package_price' => $packagePrice,
                'final_price' => max(0, $packagePrice - $discountAmount),
            ],
        ]);
    }
}
