<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Deposit;
use App\Models\Wallet;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;

class DepositController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $deposits = $user->deposits()->latest()->paginate(20);

        return response()->json([
            'success' => true,
            'deposits' => $deposits
        ]);
    }

    public function show(Request $request, $id)
    {
        $user = $request->user();
        $deposit = $user->deposits()->findOrFail($id);

        return response()->json([
            'success' => true,
            'deposit' => $deposit
        ]);
    }

    public function addresses(Request $request)
    {
        // Get deposit addresses from wallets table (public endpoint - no auth required)
        $addresses = Wallet::where('is_active', true)
            ->get()
            ->map(function ($wallet) {
                return [
                    'id' => $wallet->id,
                    'name' => $wallet->name,
                    'coin_name' => $wallet->coin_name ?? 'USDT',
                    'network' => $wallet->network,
                    'address' => $wallet->address,
                    'qr_code_url' => $wallet->qr_code_path ? ('/storage/' . $wallet->qr_code_path) : null,
                ];
            });

        return response()->json([
            'success' => true,
            'addresses' => $addresses
        ]);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'network' => 'required|string',
            'amount' => 'required|numeric|min:0.00000001',
            'tx_hash' => 'nullable|string',
            'voucher' => 'nullable|file|image|max:5120',
        ]);

        if ($validator->fails()) {
            Log::warning('Deposit validation failed', ['user_id' => $request->user()?->id, 'errors' => $validator->errors()->toArray()]);
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $user = $request->user();

        // Get address for network
        $wallet = Wallet::where('network', $request->network)
            ->where('is_active', true)
            ->first();

        if (!$wallet) {
            Log::warning('Deposit invalid network', ['user_id' => $user->id, 'network' => $request->network]);
            return response()->json([
                'success' => false,
                'message' => 'Invalid network'
            ], 400);
        }

        $voucherPath = null;
        if ($request->hasFile('voucher')) {
            try {
                $voucherPath = $request->file('voucher')->store('deposits/vouchers', 'public');
            } catch (\Exception $e) {
                Log::error('Deposit voucher upload failed', ['user_id' => $user->id, 'error' => $e->getMessage()]);
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to upload screenshot. Please try a smaller image (max 5MB).'
                ], 500);
            }
        }

        try {
                $deposit = Deposit::create([
                'user_id' => $user->id,
                'network' => $request->network,
                'address' => $wallet->address,
                'amount' => $request->amount,
                'tx_hash' => $request->tx_hash,
                'voucher_path' => $voucherPath,
                'status' => 'pending',
            ]);
        } catch (\Exception $e) {
            Log::error('Deposit store failed', ['user_id' => $user->id, 'error' => $e->getMessage()]);
            return response()->json([
                'success' => false,
                'message' => 'Failed to submit deposit request. Please try again.'
            ], 500);
        }

        return response()->json([
            'success' => true,
            'deposit' => $deposit,
            'message' => 'Deposit request submitted'
        ], 201);
    }
}
