<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Wallet;
use App\Models\WithdrawalRequest;
use App\Services\ReferralWithdrawalGate;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class WalletController extends Controller
{
    /**
     * عرض رصيد المحفظة
     */
    public function balance(Request $request): JsonResponse
    {
        try {
            $user = Auth::user();
            $wallet = Wallet::getOrCreateForUser($user->id);

            $available = max(0.0, (float) $wallet->balance - (float) $wallet->pending_withdrawal);
            $lockedReferral = ReferralWithdrawalGate::lockedReferralBalance((int) $user->id, $available);
            $maxWithdrawable = ReferralWithdrawalGate::maxWithdrawable(
                (float) $wallet->balance,
                (float) $wallet->pending_withdrawal,
                (int) $user->id
            );

            return response()->json([
                'success' => true,
                'data' => [
                    'balance' => (float) $wallet->balance,
                    'total_earned' => (float) $wallet->total_earned,
                    'total_withdrawn' => (float) $wallet->total_withdrawn,
                    'pending_withdrawal' => (float) $wallet->pending_withdrawal,
                    'available_for_withdrawal' => (float) $wallet->getAvailableBalanceForWithdrawal(),
                    'referral_locked_balance' => round($lockedReferral, 2),
                    'max_withdrawable_after_referral_rules' => round($maxWithdrawable, 2),
                    'referral_qualified_invitees' => ReferralWithdrawalGate::qualifiedInviteeCount((int) $user->id),
                    'referral_required_invitees' => ReferralWithdrawalGate::requiredInviteeCount(),
                    'can_withdraw' => $wallet->canWithdraw() && $maxWithdrawable >= Wallet::MIN_WITHDRAWAL_AMOUNT,
                    'min_withdrawal_amount' => Wallet::MIN_WITHDRAWAL_AMOUNT,
                ],
                'message' => 'تم جلب بيانات المحفظة بنجاح'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => 'خطأ في جلب بيانات المحفظة: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * عرض معاملات المحفظة
     */
    public function transactions(Request $request): JsonResponse
    {
        try {
            $user = Auth::user();
            $wallet = Wallet::getOrCreateForUser($user->id);

            $transactions = $wallet->transactions()
                ->orderBy('created_at', 'desc')
                ->paginate(20);

            return response()->json([
                'success' => true,
                'data' => $transactions,
                'message' => 'تم جلب المعاملات بنجاح'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => 'خطأ في جلب المعاملات: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * طلب سحب مبلغ
     */
    public function requestWithdrawal(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'amount' => 'required|numeric|min:1',
                'payment_method' => 'required|string|in:bank_transfer,cash_deposit,other',
                'account_details' => 'required|string|max:1000',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'data' => null,
                    'message' => 'بيانات غير صحيحة',
                    'errors' => $validator->errors()
                ], 400);
            }

            $user = Auth::user();
            $wallet = Wallet::getOrCreateForUser($user->id);
            $amount = (float) $request->amount;

            $availableBalance = (float) $wallet->balance - (float) $wallet->pending_withdrawal;
            $maxWithdrawable = ReferralWithdrawalGate::maxWithdrawable(
                (float) $wallet->balance,
                (float) $wallet->pending_withdrawal,
                (int) $user->id
            );

            if ($amount > $maxWithdrawable + 0.0001) {
                $required = ReferralWithdrawalGate::requiredInviteeCount();
                $qualified = ReferralWithdrawalGate::qualifiedInviteeCount((int) $user->id);

                return response()->json([
                    'success' => false,
                    'data' => null,
                    'message' => "لا يمكن سحب هذا المبلغ. الحد الأقصى المتاح حالياً: ".round($maxWithdrawable, 2)." دينار (أرباح الدعوات مقفلة حتى يصل عدد المدعوين المؤهلين إلى {$required}، الحالي: {$qualified}).",
                ], 400);
            }

            // التحقق من الحد الأدنى للسحب (450,000 دينار)
            if (! $wallet->canWithdraw($amount)) {
                $available = $wallet->getAvailableBalanceForWithdrawal();
                $minAmount = Wallet::MIN_WITHDRAWAL_AMOUNT;

                return response()->json([
                    'success' => false,
                    'data' => null,
                    'message' => "لا يمكن سحب المبلغ. الحد الأدنى للسحب هو {$minAmount} دينار والرصيد المتاح: {$available} دينار",
                ], 400);
            }

            // التحقق من أن المبلغ لا يتجاوز الرصيد المتاح
            if ($amount > $availableBalance) {
                return response()->json([
                    'success' => false,
                    'data' => null,
                    'message' => "المبلغ المطلوب ({$amount} دينار) يتجاوز الرصيد المتاح ({$availableBalance} دينار)",
                ], 400);
            }

            DB::beginTransaction();

            // إنشاء طلب سحب
            $withdrawalRequest = WithdrawalRequest::create([
                'user_id' => $user->id,
                'wallet_id' => $wallet->id,
                'amount' => $amount,
                'status' => 'pending',
                'payment_method' => $request->payment_method,
                'account_details' => $request->account_details,
            ]);

            // تحديث المبلغ المعلق في المحفظة
            $wallet->increment('pending_withdrawal', $amount);

            DB::commit();

            return response()->json([
                'success' => true,
                'data' => [
                    'withdrawal_request_id' => $withdrawalRequest->id,
                    'amount' => $withdrawalRequest->amount,
                    'status' => $withdrawalRequest->status,
                    'remaining_balance' => (float) ($wallet->balance - $amount),
                ],
                'message' => 'تم إنشاء طلب السحب بنجاح. سيتم مراجعته من قبل المدير'
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => 'خطأ في إنشاء طلب السحب: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * عرض طلبات السحب للمستخدم
     */
    public function withdrawalRequests(Request $request): JsonResponse
    {
        try {
            $user = Auth::user();
            $requests = WithdrawalRequest::where('user_id', $user->id)
                ->orderBy('created_at', 'desc')
                ->paginate(20);

            return response()->json([
                'success' => true,
                'data' => $requests,
                'message' => 'تم جلب طلبات السحب بنجاح'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => 'خطأ في جلب طلبات السحب: ' . $e->getMessage()
            ], 500);
        }
    }
}
