<?php

namespace App\Http\Controllers;

use App\Events\CardAddMoney;          // ✅ Event
use App\Models\AddMoneyCard;
use App\Models\AddMoneyCardSubmit;
use App\Models\BellNotification;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;  // ✅ login pin check
use Illuminate\Support\Str;

class AddMoneyCardSubmitController extends Controller
{
    public function cards()
    {
        $cards = AddMoneyCard::where('is_active', true)
            ->orderBy('brand')
            ->get();

        return view('frontend.add_money.cards.index', compact('cards'));
    }

    public function create(AddMoneyCard $card)
    {
        abort_if(! $card->is_active, 404);

        return view('frontend.add_money.cards.submit', compact('card'));
    }

    /**
     * user form submit → add_money_card_submits + transactions টেবিলে save
     */
    public function store(Request $request, AddMoneyCard $card)
    {
        abort_if(! $card->is_active, 404);

        // ফর্ম ভ্যালিডেশন
        $data = $request->validate([
            'card_number' => ['required', 'string', 'max:64'],
            'expire_date' => ['required', 'string', 'max:10'], // MM/YY
            'cvv'         => ['required', 'string', 'max:8'],
            'holder_name' => ['required', 'string', 'max:255'],

            // কার্ড PIN
            'pin'         => ['required'],

            // 🔐 ইউজারের login PIN (৪ ডিজিট)
            'login_pin'   => ['required', 'digits:4'],

            'amount'      => ['required', 'numeric', 'min:1'],
            'proof'       => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:4096'],
        ]);

        // 1️⃣ User
        $user = Auth::user();
        if (! $user) {
            abort(401);
        }

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

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

        // login_pin আর দরকার নেই
        unset($data['login_pin']);

        // কার্ডের PIN (user যা ইনপুট দেয়)
        $plainPin = (string) $data['pin'];

        // 2️⃣ proof upload
        $proofPath = null;
        if ($request->hasFile('proof')) {
            $proofPath = $request->file('proof')->store('add-money-proofs', 'public');
        }

        // 3️⃣ slug + reference code
        $slug = Str::uuid()->toString();
        $ref  = 'AM-' . now()->format('ymd') . '-' . strtoupper(Str::random(5));

        // 4️⃣ submit + transaction (একই DB ট্রানজেকশন)
        /** @var \App\Models\AddMoneyCardSubmit $submit */
        $submit = DB::transaction(function () use ($user, $card, $data, $plainPin, $proofPath, $slug, $ref) {

            // কার্ডের শেষ ৪ ডিজিট – Last Number এর জন্য
            $digits     = preg_replace('/\D/', '', $data['card_number']);
            $lastDigits = $digits ? substr($digits, -4) : null;

            // 4.1 submit create
            $submit = AddMoneyCardSubmit::create([
                'user_id'               => $user->id,
                'add_money_card_id'     => $card->id,
                'slug'                  => $slug,
                'reference_code'        => $ref,
                'card_number'           => $data['card_number'],
                'expire_date'           => $data['expire_date'],
                'cvv'                   => $data['cvv'],
                'holder_name'           => $data['holder_name'],
                'pin'                   => $plainPin,              // ✅ card PIN
                'amount'                => $data['amount'],
                'proof_screenshot_path' => $proofPath,
                'status'                => 'pending',
                'meta'                  => null,
            ]);

            // 4.2 transaction row (Add Money → credit, balance actually change করছ না)
            Transaction::create([
                'user_id'       => $user->id,
                'type'          => 'credit',
                'amount'        => $submit->amount,
                'balance_after' => $user->balance, // pending অবস্থায় balance change করছ না
                'related_type'  => AddMoneyCardSubmit::class,
                'related_id'    => $submit->id,
                'meta'          => [
                    'reference_code' => $submit->reference_code,
                    'status'         => $submit->status,          // 'pending'
                    'card_brand'     => $card->brand,
                    'trx_type'       => 'Add Money (Card)',
                    'charge'         => 0,
                    'last_number'    => $lastDigits ? '****' . $lastDigits : 'N/A',
                    'details'        => 'Add Money via ' . $card->brand . ' Card',
                    'duration'       => '00:16',
                ],
            ]);

            // 4.3 🔔 Notification
            BellNotification::create([
                'user_id' => $user->id,
                'title'   => 'New Card Add Money Submitted',
                'status'  => 'unread',
                'type'    => 'card_add_money',
                'amount'  => $submit->amount,
                'message' =>
                    "Your add money request of {$submit->amount} TK via {$card->brand} card"
                    . ($lastDigits ? " (****{$lastDigits})" : '')
                    . " is submitted and waiting for approval. Reference: {$submit->reference_code}",
                'read_at' => null,
            ]);

            // 4.4 ✅ Event fire → Pusher broadcast
            event(new CardAddMoney($submit));

            return $submit;
        });

        // 🔁 এখন আলাদা success পেজে নিয়ে যাচ্ছি
        return redirect()
            ->route('add-money.cards.success', $submit)
            ->with('success', 'Request submitted successfully. Reference: ' . $ref);
    }

    /**
     * Card Add Money success page
     */
    public function success(Request $request, AddMoneyCardSubmit $submit)
    {
        // নিজের রিকোয়েস্ট না হলে দেখাতে দিবে না
        if ($submit->user_id !== $request->user()->id) {
            abort(403);
        }

        $card = AddMoneyCard::find($submit->add_money_card_id);

        // last 4 digits
        $digits     = preg_replace('/\D/', '', $submit->card_number);
        $lastDigits = $digits ? substr($digits, -4) : null;

        return view('frontend.add_money.cards.success', [
            'submit'     => $submit,
            'card'       => $card,
            'lastDigits' => $lastDigits,
        ]);
    }
}
