<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\GasOffice;
use App\Services\PartnerWalletService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class GasOfficeWalletController extends Controller
{
    /**
     * عرض المحفظة والإعدادات
     */
    public function index(): JsonResponse
    {
        $user = Auth::user();
        if (!$user) {
            return response()->json(['success' => false, 'message' => 'يجب تسجيل الدخول'], 401);
        }

        $gasOffice = GasOffice::where('owner_id', $user->id)->first();
        if (!$gasOffice) {
            return response()->json(['success' => false, 'message' => 'مكتب الغاز غير موجود'], 404);
        }

        $wallet = PartnerWalletService::getOrCreateWallet('gas_office', (int) $gasOffice->id);
        $wallet->load('settings');

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

        return response()->json([
            'success' => true,
            'data' => [
                'wallet' => [
                    'id' => $wallet->id,
                    'balance' => (float) $wallet->balance,
                    'currency' => $wallet->currency,
                    '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,
                ],
            ],
        ], 200, [], JSON_UNESCAPED_UNICODE);
    }

    /**
     * تعبئة المحفظة (زين كاش / ماستر كارد)
     */
    public function topUp(Request $request): JsonResponse
    {
        $request->validate([
            'amount' => 'required|numeric|min:1',
            'payment_method' => 'required|in:zain_cash,mastercard',
            'external_id' => 'nullable|string|max:255',
        ], [
            'amount.required' => 'المبلغ مطلوب',
            'payment_method.required' => 'طريقة الدفع مطلوبة',
            'payment_method.in' => 'طريقة الدفع غير مدعومة',
        ]);

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

        $gasOffice = GasOffice::where('owner_id', $user->id)->first();
        if (!$gasOffice) {
            return response()->json(['success' => false, 'message' => 'مكتب الغاز غير موجود'], 404);
        }

        $wallet = PartnerWalletService::getOrCreateWallet('gas_office', (int) $gasOffice->id);

        try {
            $amount = (float) $request->amount;
            $transaction = PartnerWalletService::topUp(
                $wallet->id,
                $amount,
                $request->payment_method,
                $request->input('external_id'),
                'تعبئة رصيد - مكتب غاز'
            );

            return response()->json([
                'success' => true,
                'message' => 'تم تعبئة المحفظة بنجاح',
                'data' => [
                    'transaction' => [
                        'id' => $transaction->id,
                        'type' => $transaction->type,
                        'amount' => (float) $transaction->amount,
                        'balance_after' => (float) $transaction->balance_after,
                        'payment_method' => $transaction->payment_method,
                        'status' => $transaction->status,
                        'created_at' => $transaction->created_at->toIso8601String(),
                    ],
                    'wallet_balance' => (float) $transaction->balance_after,
                ],
            ], 200, [], JSON_UNESCAPED_UNICODE);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 422, [], JSON_UNESCAPED_UNICODE);
        }
    }

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

        $gasOffice = GasOffice::where('owner_id', $user->id)->first();
        if (!$gasOffice) {
            return response()->json(['success' => false, 'message' => 'مكتب الغاز غير موجود'], 404);
        }

        $wallet = PartnerWalletService::getOrCreateWallet('gas_office', (int) $gasOffice->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,
                'reference_type' => $t->reference_type,
                'reference_id' => $t->reference_id,
                '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(),
                'per_page' => $transactions->perPage(),
                'total' => $transactions->total(),
            ],
        ], 200, [], JSON_UNESCAPED_UNICODE);
    }
}
