<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AppSetting;
use App\Models\PartnerWallet;
use App\Models\PartnerWalletSetting;
use App\Models\PartnerWalletTransaction;
use App\Models\PartnerWalletTopupRequest;
use App\Services\PartnerWalletService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class DriverWalletController extends Controller
{
    /**
     * عرض المحفظة وإعدادات الشحن (زين كاش، ماستر كارد، بطاقة أمان)
     */
    public function index(): JsonResponse
    {
        $user = Auth::user();
        if (!$user || $user->user_type !== 'driver') {
            return response()->json(['success' => false, 'message' => 'يجب تسجيل الدخول كسائق'], 401);
        }

        $wallet = PartnerWallet::getOrCreateFor(PartnerWallet::OWNER_TYPE_DRIVER, (int) $user->id);
        $wallet->load('settings');
        $settings = $wallet->settings;

        $paymentMethods = $settings && $settings->payment_methods
            ? $settings->payment_methods
            : ['zain_cash', 'mastercard'];

        $appSettings = AppSetting::first();

        return response()->json([
            'success' => true,
            'data' => [
                'wallet' => [
                    'id' => $wallet->id,
                    'balance' => (float) $wallet->balance,
                    'currency' => $wallet->currency ?? 'IQD',
                    'is_active' => $wallet->is_active,
                    'has_negative_balance' => $wallet->hasNegativeBalance(),
                ],
                'settings' => [
                    'payment_methods' => $paymentMethods,
                    'min_topup_amount' => $settings ? (float) $settings->min_topup_amount : 1000,
                    'max_topup_amount' => $settings && $settings->max_topup_amount !== null ? (float) $settings->max_topup_amount : null,
                    'allow_negative_balance' => $settings ? $settings->allow_negative_balance : true,
                ],
                'wallet_instructions' => [
                    'zain_cash_phone' => $appSettings?->wallet_zain_cash_phone ?? null,
                    'zain_cash_instructions' => $appSettings?->wallet_topup_instructions ?? null,
                    'mastercard_instructions' => $appSettings?->wallet_mastercard_instructions ?? null,
                    'aman_card_enabled' => (bool) ($appSettings?->wallet_aman_card_enabled ?? false),
                    'aman_card_instructions' => $appSettings?->wallet_aman_card_instructions ?? null,
                ],
            ],
        ], 200, [], JSON_UNESCAPED_UNICODE);
    }

    /**
     * طلب شحن المحفظة (زين كاش / ماستر كارد) — ينتظر تأكيد الإدارة
     */
    public function createTopupRequest(Request $request): JsonResponse
    {
        $request->validate([
            'amount' => 'required|numeric|min:1000',
            'payment_method' => 'required|in:zain_cash,mastercard',
            'transfer_code' => 'nullable|string|max:100',
            'transfer_from_phone' => 'nullable|string|max:20',
            'notes' => 'nullable|string|max:500',
        ], [
            'amount.required' => 'المبلغ مطلوب',
            'amount.min' => 'الحد الأدنى للتعبئة 1000 دينار',
        ]);

        $user = Auth::user();
        if (!$user || $user->user_type !== 'driver') {
            return response()->json(['success' => false, 'message' => 'يجب تسجيل الدخول كسائق'], 401);
        }

        $wallet = PartnerWallet::getOrCreateFor(PartnerWallet::OWNER_TYPE_DRIVER, (int) $user->id);
        $walletSettings = $wallet->settings;

        if ($walletSettings) {
            $methods = $walletSettings->payment_methods ?? [];
            if (!in_array($request->payment_method, $methods)) {
                return response()->json([
                    'success' => false,
                    'message' => 'طريقة الدفع غير مفعّلة',
                ], 422);
            }
            if ($request->amount < (float) $walletSettings->min_topup_amount) {
                return response()->json([
                    'success' => false,
                    'message' => 'المبلغ أقل من الحد الأدنى: ' . $walletSettings->min_topup_amount . ' د.ع',
                ], 422);
            }
        }

        $topupRequest = PartnerWalletTopupRequest::create([
            'partner_wallet_id' => $wallet->id,
            'owner_type' => PartnerWallet::OWNER_TYPE_DRIVER,
            'owner_id' => $user->id,
            'amount' => (float) $request->amount,
            'payment_method' => $request->payment_method,
            'status' => 'pending',
            'transfer_code' => $request->transfer_code,
            'transfer_from_phone' => $request->transfer_from_phone,
            'admin_notes' => $request->notes,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'تم إرسال طلب الشحن. سيتم تفعيل الرصيد بعد التأكيد من الإدارة.',
            'data' => [
                'id' => $topupRequest->id,
                'amount' => (float) $topupRequest->amount,
                'payment_method' => $topupRequest->payment_method,
                'status' => $topupRequest->status,
            ],
        ], 201, [], JSON_UNESCAPED_UNICODE);
    }

    /**
     * قائمة طلبات الشحن
     */
    public function topupRequests(Request $request): JsonResponse
    {
        $user = Auth::user();
        if (!$user || $user->user_type !== 'driver') {
            return response()->json(['success' => false, 'message' => 'يجب تسجيل الدخول كسائق'], 401);
        }

        $wallet = PartnerWallet::getOrCreateFor(PartnerWallet::OWNER_TYPE_DRIVER, (int) $user->id);
        $perPage = min((int) $request->get('per_page', 20), 50);
        $requests = PartnerWalletTopupRequest::where('partner_wallet_id', $wallet->id)
            ->orderByDesc('created_at')
            ->paginate($perPage);

        $items = $requests->getCollection()->map(fn ($r) => [
            'id' => $r->id,
            'amount' => (float) $r->amount,
            'payment_method' => $r->payment_method,
            'status' => $r->status,
            'created_at' => $r->created_at->toIso8601String(),
        ]);

        return response()->json([
            'success' => true,
            'data' => [
                'requests' => $items,
                'current_page' => $requests->currentPage(),
                'last_page' => $requests->lastPage(),
                'total' => $requests->total(),
            ],
        ], 200, [], JSON_UNESCAPED_UNICODE);
    }

    /**
     * قائمة معاملات المحفظة
     */
    public function transactions(Request $request): JsonResponse
    {
        $user = Auth::user();
        if (!$user || $user->user_type !== 'driver') {
            return response()->json(['success' => false, 'message' => 'يجب تسجيل الدخول كسائق'], 401);
        }

        $wallet = PartnerWallet::getOrCreateFor(PartnerWallet::OWNER_TYPE_DRIVER, (int) $user->id);
        $perPage = min((int) $request->get('per_page', 20), 50);
        $transactions = $wallet->transactions()->paginate($perPage);

        $items = $transactions->getCollection()->map(function ($t) {
            return [
                'id' => $t->id,
                'type' => $t->type,
                'amount' => (float) $t->amount,
                'balance_before' => (float) $t->balance_before,
                'balance_after' => (float) $t->balance_after,
                'payment_method' => $t->payment_method,
                'description' => $t->description,
                'status' => $t->status,
                'created_at' => $t->created_at->toIso8601String(),
            ];
        });

        return response()->json([
            'success' => true,
            'data' => [
                'transactions' => $items,
                'current_page' => $transactions->currentPage(),
                'last_page' => $transactions->lastPage(),
                'total' => $transactions->total(),
            ],
        ], 200, [], JSON_UNESCAPED_UNICODE);
    }

    /**
     * تعبئة مباشرة (بطاقة أمان — عند إدخال كود البطاقة)
     * قريباً: عند إنشاء نظام بطاقات أمان
     */
    public function topUpWithAmanCard(Request $request): JsonResponse
    {
        $request->validate([
            'card_code' => 'required|string|max:50',
        ]);

        $user = Auth::user();
        if (!$user || $user->user_type !== 'driver') {
            return response()->json(['success' => false, 'message' => 'يجب تسجيل الدخول كسائق'], 401);
        }

        $appSettings = AppSetting::first();
        if (!$appSettings || !$appSettings->wallet_aman_card_enabled) {
            return response()->json([
                'success' => false,
                'message' => 'بطاقة أمان غير مفعّلة حالياً. ستتوفر قريباً.',
            ], 422);
        }

        // TODO: التحقق من كود البطاقة في جدول aman_cards (عند إنشائه)
        return response()->json([
            'success' => false,
            'message' => 'نظام بطاقة أمان قيد التطوير. استخدم زين كاش أو ماستر كارد حالياً.',
        ], 501, [], JSON_UNESCAPED_UNICODE);
    }
}
