<?php

namespace App\Http\Controllers;

use App\Models\Deposit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Inertia\Inertia;

class DepositController extends Controller
{
    public function index()
    {
        return Inertia::render('Deposit/Index', [
            'methods' => [
                [
                    'id' => 'bkash',
                    'title' => 'Bkash VIP',
                    'subtitle' => 'Bkash Limits',
                    'logo' => '/images/bkash.png',
                ],
                [
                    'id' => 'nagad',
                    'title' => 'NAGAD VIP',
                    'subtitle' => 'Nagad',
                    'logo' => '/images/nagad.png',
                ],
            ],
            'channelsByMethod' => [
                'bkash' => [
                    [
                        'id' => 1,
                        'name' => 'Bkash VIP',
                        'code' => 'QKP',
                        'wallet_number' => '01736773900',
                        'provider' => 'BKASH Deposit',
                    ],
                ],
                'nagad' => [
                    [
                        'id' => 2,
                        'name' => 'NAGAD VIP',
                        'code' => 'QKP',
                        'wallet_number' => '01800000000',
                        'provider' => 'NAGAD Deposit',
                    ],
                ],
            ],
            'amountOptions' => [100, 200, 300, 400, 500, 1000, 3000, 5000, 10000, 15000, 20000, 25000],
            'promotions' => [
                [
                    'id' => 1,
                    'title' => 'আপনার প্রথম ডিপোজিটে ৫০% বোনাস উপভোগ করুন',
                    'minAmount' => 100,
                    'description' => 'সর্বনিম্ন আমানত ১০০ টাকা।',
                    'bonusMap' => [
                        100 => 50,
                        200 => 100,
                        300 => 110,
                        400 => 110,
                        500 => 120,
                        1000 => 150,
                        3000 => 300,
                        5000 => 500,
                        10000 => 1000,
                        20000 => 2000,
                        25000 => 2500,
                    ],
                ],
            ],
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'method' => ['required', 'string', 'in:bkash,nagad'],
            'channel_id' => ['required', 'integer'],
            'amount' => ['required', 'numeric', 'min:100', 'max:25000'],
            'promotion_id' => ['nullable', 'integer'],
        ]);

        $channelConfig = [
            'bkash' => [
                1 => [
                    'wallet_number' => '01736773900',
                    'provider' => 'BKASH Deposit',
                ],
            ],
            'nagad' => [
                2 => [
                    'wallet_number' => '01800000000',
                    'provider' => 'NAGAD Deposit',
                ],
            ],
        ];

        $promotionTitle = null;
        $bonusAmount = 0;

        if ((int) $validated['promotion_id'] === 1) {
            $bonusMap = [
                100 => 50,
                200 => 100,
                300 => 110,
                400 => 110,
                500 => 120,
                1000 => 150,
                3000 => 300,
                5000 => 500,
                10000 => 1000,
                20000 => 2000,
                25000 => 2500,
            ];

            $promotionTitle = 'আপনার প্রথম ডিপোজিটে ৫০% বোনাস উপভোগ করুন';
            $bonusAmount = $bonusMap[(int) $validated['amount']] ?? 0;
        }

        $wallet = $channelConfig[$validated['method']][$validated['channel_id']] ?? null;

        abort_if(!$wallet, 422, 'Invalid channel selected.');

        $deposit = Deposit::create([
            'user_id' => Auth::id(),
            'method' => $validated['method'],
            'channel_id' => $validated['channel_id'],
            'amount' => $validated['amount'],
            'bonus_amount' => $bonusAmount,
            'wallet_number' => $wallet['wallet_number'],
            'provider' => $wallet['provider'],
            'reference' => 'DEP-' . strtoupper(Str::random(10)),
            'promotion_title' => $promotionTitle,
            'status' => 'pending',
        ]);

        return redirect()->route('deposit.submit.page', $deposit->id);
    }

    public function submitPage(Deposit $deposit)
    {
        abort_unless($deposit->user_id === Auth::id(), 403);

        return Inertia::render('Deposit/Submit', [
            'order' => [
                'id' => $deposit->id,
                'amount' => $deposit->amount,
                'wallet_number' => $deposit->wallet_number,
                'provider' => $deposit->provider,
            ],
        ]);
    }

    public function confirm(Request $request, Deposit $deposit)
    {
        abort_unless($deposit->user_id === Auth::id(), 403);

        $validated = $request->validate([
            'trx_id' => ['required', 'string', 'max:100'],
        ]);

        if ($deposit->trx_id) {
            return back()->withErrors([
                'trx_id' => 'TrxID already submitted.',
            ]);
        }

        $deposit->update([
            'trx_id' => $validated['trx_id'],
            'submitted_at' => now(),
            'status' => 'submitted',
        ]);

        return redirect()->route('deposit.info', $deposit->id);
    }

    public function info(Deposit $deposit)
    {
        abort_unless($deposit->user_id === Auth::id(), 403);

        return Inertia::render('Deposit/Info', [
            'deposit' => [
                'id' => $deposit->id,
                'method_name' => ucfirst($deposit->method) . ' VIP',
                'account' => $deposit->wallet_number,
                'amount' => $deposit->amount,
                'promotion_title' => $deposit->promotion_title,
                'status' => $deposit->status,
                'reference' => $deposit->reference,
            ],
        ]);
    }

    public function records()
    {
        $records = Deposit::query()
            ->where('user_id', Auth::id())
            ->latest()
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'method' => ucfirst($item->method),
                    'created_at' => $item->created_at->format('Y-m-d H:i:s'),
                    'reference' => $item->reference,
                    'postscript' => $item->trx_id,
                    'received_time' => optional($item->approved_at)?->format('Y-m-d H:i:s'),
                    'handling_fee' => '-',
                    'promotion' => $item->promotion_title,
                    'remarks' => $item->admin_note,
                    'request_amount' => number_format((float) $item->amount, 2, '.', ''),
                    'received_amount' => $item->status === 'approved'
                        ? number_format((float) ($item->amount + $item->bonus_amount), 2, '.', '')
                        : '-',
                    'status' => ucfirst($item->status),
                ];
            });

        return Inertia::render('Deposit/Records', [
            'records' => $records,
        ]);
    }
}