<?php

namespace App\Http\Controllers;

use App\Events\AddMoney;
use App\Models\BellNotification;
use App\Models\Deposit;
use App\Models\PaymentMethod;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash; // ✅ PIN check এর জন্য

class AddMoneyController extends Controller
{
    public function methods()
    {
        $methods = PaymentMethod::where('is_active', true)->orderBy('id')->get();

        return view('frontend.add-money.methods', compact('methods'));
    }

    public function create(string $slug)
    {
        $method = PaymentMethod::where('slug', $slug)->firstOrFail();

        return view('frontend.add-money.create', compact('method'));
    }

    public function store(Request $request, string $slug)
    {
        $method = PaymentMethod::where('slug', $slug)->firstOrFail();

        // ✅ validate + PIN field সহ
        $data = $request->validate([
            'payer_phone' => ['required', 'string', 'max:32'],
            'amount'      => ['required', 'numeric', 'min:1'],
            'proof'       => ['nullable', 'file', 'mimes:jpg,jpeg,png,pdf', 'max:2048'],
            'pin'         => ['required', 'digits:4'], // 🔐 4 digit PIN
        ]);

        /** @var \App\Models\User $user */
        $user = $request->user();

        // ✅ user-এর login_pin আছে কি না
        if (empty($user->login_pin)) {
            return back()
                ->withErrors([
                    'pin' => 'আপনি এখনো লগইন PIN সেট করেননি। আগে প্রোফাইল থেকে PIN সেট করে নিন।',
                ])
                ->withInput();
        }

        // ✅ PIN মিলছে কি না
        if (! Hash::check($data['pin'], $user->login_pin)) {
            return back()
                ->withErrors([
                    'pin' => 'ভুল PIN দেওয়া হয়েছে।',
                ])
                ->withInput();
        }

        // PIN আর ব্যবহার করার দরকার নেই, নিরাপত্তার জন্য চাইলে unset করতে পারো
        unset($data['pin']);

        $path = $request->hasFile('proof')
            ? $request->file('proof')->store('deposits', 'public')
            : null;

        // ✅ 1️⃣ Create Deposit
        $deposit = Deposit::create([
            'user_id'           => $user->id,
            'payment_method_id' => $method->id,
            'payer_phone'       => $data['payer_phone'],
            'amount'            => $data['amount'],
            'reference'         => Str::upper(Str::random(10)),
            'proof_path'        => $path,
            'status'            => 'pending',
        ]);

        // ✅ 2️⃣ Create Transaction (linked to this Deposit)
        $currentBalance = $user->balance ?? 0; // ধরে নিচ্ছি 'balance' কলাম আছে

        Transaction::create([
            'user_id'       => $user->id,
            'type'          => 'credit',
            'amount'        => $data['amount'],
            'balance_after' => $currentBalance + $data['amount'],
            'related_type'  => Deposit::class,
            'related_id'    => $deposit->id,
            'meta'          => json_encode([
                'method'    => $method->name,
                'reference' => $deposit->reference,
                'note'      => 'Deposit created, pending approval',
            ]),
        ]);

        // ✅ 3️⃣ Bell notification
        BellNotification::create([
            'user_id' => $user->id,
            'title'   => 'New Deposit Submitted',
            'status'  => 'unread',
            'type'    => 'deposit',
            'amount'  => $data['amount'],
            'message' => "Your deposit of {$data['amount']} TK via {$method->name} is submitted and waiting for approval. Reference: {$deposit->reference}",
            'read_at' => null,
        ]);

        Log::info('AddMoney event fired for deposit ID: '.$deposit->id);
        event(new AddMoney($deposit));

        return redirect()->route('add-money.success', $deposit);
    }

    public function success(Deposit $deposit)
    {
        return view('frontend.add-money.success', compact('deposit'));
    }

    public function transactions()
    {
        $transactions = Transaction::where('user_id', auth()->id())->latest()->paginate(20);

        return view('frontend.add-money.transactions', compact('transactions'));
    }
}
