<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AppSetting;
use App\Models\PartnerWalletTopupRequest;
use App\Models\Restaurant;
use App\Services\PartnerWalletService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

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

        $restaurant = Restaurant::where('user_id', $user->id)->first();
        if (!$restaurant) {
            return response()->json(['success' => false, 'message' => 'المطعم غير موجود'], 404);
        }

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

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

        // رقم زين كاش وتعليمات الشحن من إعدادات التطبيق (لوحة التحكم)
        $appSetting = AppSetting::first();
        $zainCashPhone = $appSetting?->wallet_zain_cash_phone ?? '';
        $topupInstructions = $appSetting?->wallet_topup_instructions ?? 'قم بالتحويل إلى الرقم أعلاه ثم أدخل كود التحويل ورقم المحوّل منه. بعد التأكيد من الإدارة يُضاف المبلغ لمحفظتك.';

        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,
                    'zain_cash_phone' => $zainCashPhone,
                    'topup_instructions' => $topupInstructions,
                ],
            ],
        ], 200, [], JSON_UNESCAPED_UNICODE);
    }

    /**
     * إنشاء طلب شحن (يُفعّل بعد تأكيد الإدارة)
     */
    public function createTopupRequest(Request $request): JsonResponse
    {
        $request->validate([
            'amount' => 'required|numeric|min:1',
            'payment_method' => 'required|in:zain_cash,mastercard',
            'transfer_code' => 'required|string|max:128',
            'transfer_from_phone' => 'required|string|max:32',
            'receipt_image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:5120',
        ], [
            'amount.required' => 'المبلغ مطلوب',
            'payment_method.required' => 'طريقة الدفع مطلوبة',
            'transfer_code.required' => 'كود التحويل مطلوب',
            'transfer_from_phone.required' => 'رقم الذي حولت منه مطلوب',
        ]);

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

        $restaurant = Restaurant::where('user_id', $user->id)->first();
        if (!$restaurant) {
            return response()->json(['success' => false, 'message' => 'المطعم غير موجود'], 404);
        }

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

        $amount = (float) $request->amount;
        if ($settings && (float) $settings->min_topup_amount > 0 && $amount < (float) $settings->min_topup_amount) {
            return response()->json([
                'success' => false,
                'message' => 'المبلغ أقل من الحد الأدنى: ' . $settings->min_topup_amount . ' د.ع',
            ], 422, [], JSON_UNESCAPED_UNICODE);
        }
        if ($settings && $settings->max_topup_amount !== null && $amount > (float) $settings->max_topup_amount) {
            return response()->json([
                'success' => false,
                'message' => 'المبلغ يتجاوز الحد الأقصى',
            ], 422, [], JSON_UNESCAPED_UNICODE);
        }

        $receiptPath = null;
        if ($request->hasFile('receipt_image')) {
            $receiptPath = $request->file('receipt_image')->store('wallet-receipts', 'public');
        }

        $topupRequest = PartnerWalletTopupRequest::create([
            'partner_wallet_id' => $wallet->id,
            'owner_type' => 'restaurant',
            'owner_id' => $restaurant->id,
            'amount' => $amount,
            'payment_method' => $request->payment_method,
            'transfer_code' => $request->transfer_code,
            'transfer_from_phone' => $request->transfer_from_phone,
            'receipt_image_path' => $receiptPath,
            'status' => PartnerWalletTopupRequest::STATUS_PENDING,
        ]);

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

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

        $restaurant = Restaurant::where('user_id', $user->id)->first();
        if (!$restaurant) {
            return response()->json(['success' => false, 'message' => 'المطعم غير موجود'], 404);
        }

        $wallet = PartnerWalletService::getOrCreateWallet('restaurant', (int) $restaurant->id);
        $perPage = min((int) $request->get('per_page', 20), 50);
        $status = $request->get('status'); // pending | approved | rejected
        $query = PartnerWalletTopupRequest::where('partner_wallet_id', $wallet->id)->orderBy('created_at', 'desc');
        if ($status && in_array($status, ['pending', 'approved', 'rejected'])) {
            $query->where('status', $status);
        }
        $requests = $query->paginate($perPage);

        $items = $requests->getCollection()->map(function ($r) {
            return [
                'id' => $r->id,
                'amount' => (float) $r->amount,
                'payment_method' => $r->payment_method,
                'transfer_code' => $r->transfer_code,
                'transfer_from_phone' => $r->transfer_from_phone,
                'receipt_image_url' => $r->receipt_image_path ? asset('storage/' . $r->receipt_image_path) : null,
                'status' => $r->status,
                'admin_notes' => $r->admin_notes,
                'created_at' => $r->created_at->toIso8601String(),
                'reviewed_at' => $r->reviewed_at?->toIso8601String(),
            ];
        });

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

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

        $restaurant = Restaurant::where('user_id', $user->id)->first();
        if (!$restaurant) {
            return response()->json(['success' => false, 'message' => 'المطعم غير موجود'], 404);
        }

        $wallet = PartnerWalletService::getOrCreateWallet('restaurant', (int) $restaurant->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);
    }
}
