<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreUserRequest;              // Step 1
use App\Http\Requests\StoreUserPasswordRequest;      // Step 2
use App\Http\Requests\StoreUserPinRequest;           // Step 3
use App\Http\Requests\OtpVerifyRequest;              // Step 4
use App\Mail\LoginOtpMail;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;

class RegisterController extends Controller
{
    /**
     * STEP 1: basic info (name, phone, email, avatar)
     */
     
          public function redirectDash()
{
    $redirect = '';

    if (Auth::check() && Auth::user()->role == 'user') {
        $redirect = '/dashboard';
    }
    else if (Auth::check() && Auth::user()->role == 'admin') {
        $redirect = '/admin/dashboard';
    }
    else {
        $redirect = '/';
    }

    return $redirect;
}

    public function create()
    {
        if (Auth::check()) {
    return redirect($this->redirectDash());
}
        return view('frontend.auth.register');
    }

    /**
     * STEP 1: save to session and go to password step
     */
    public function storeStep1(StoreUserRequest $request)
    {
        $data = $request->validated();

        if ($request->hasFile('avatar')) {
            $data['avatar'] = $request->file('avatar')->store('avatars', 'public');
        }

        // আগের register session ক্লিন
        session()->forget(['register.step1', 'register.step2', 'register.pending_user_id']);

        // step1 data session এ রাখি
        session(['register.step1' => $data]);

        return redirect()
            ->route('register.step2.show')
            ->with('success', 'প্রথম ধাপ সম্পন্ন হয়েছে, এখন পাসওয়ার্ড নির্ধারণ করুন।');
    }

    /**
     * STEP 2: show password form
     */
    public function showStep2()
    {
        if (Auth::check()) {
    return redirect($this->redirectDash());
}
        if (! session()->has('register.step1')) {
            return redirect()
                ->route('register.create')
                ->withErrors(['name' => 'প্রথমে মৌলিক তথ্য (Step 1) পূরণ করুন।']);
        }

        return view('frontend.auth.register-password');
    }

    /**
     * STEP 2: validate password and save to session, then go to PIN step
     */
    public function storeStep2(StoreUserPasswordRequest $request)
    {
        if (! session()->has('register.step1')) {
            return redirect()
                ->route('register.create')
                ->withErrors(['name' => 'সেশন শেষ হয়ে গেছে, আবার থেকে শুরু করুন।']);
        }

        $creds = $request->validated(); // ['password' => '......']

        // password session এ রাখি
        session(['register.step2' => [
            'password' => $creds['password'],
        ]]);

        return redirect()
            ->route('register.step3.show')
            ->with('success', 'পাসওয়ার্ড সেট হয়েছে, এখন PIN নির্ধারণ করুন।');
    }

    /**
     * STEP 3: show PIN form
     */
    public function showStep3()
    {
        if (Auth::check()) {
    return redirect($this->redirectDash());
}
        if (! session()->has('register.step1') || ! session()->has('register.step2')) {
            return redirect()
                ->route('register.create')
                ->withErrors(['name' => 'সেশন শেষ হয়ে গেছে, আবার থেকে শুরু করুন।']);
        }

        return view('frontend.auth.register-pin');
    }

    /**
     * STEP 3: validate PIN, create user, send OTP
     */
    public function storeStep3(StoreUserPinRequest $request)
    {
        $step1 = session('register.step1');
        $step2 = session('register.step2');

        if (! $step1 || ! $step2) {
            return redirect()
                ->route('register.create')
                ->withErrors(['name' => 'সেশন শেষ হয়ে গেছে, আবার থেকে শুরু করুন।']);
        }

        $pinData = $request->validated(); // ['pin' => '....']

        // ইউজার তৈরি (password & pin দুইটাই এখন পাওয়া যাবে)
        $user = User::create([
            'name'       => $step1['name'],
            'phone'      => $step1['phone'],
            'email'      => $step1['email'],
            'avatar'     => $step1['avatar'] ?? null,
            'password'   => $step2['password'],   // User model mutator হ্যাশ করে নেবে
            'login_pin'  => $pinData['pin'],      // User model mutator হ্যাশ করবে
            'role'       => 'user',
            'status'     => 'active',
        ]);

        // Step1 + Step2 data আর লাগবে না
        session()->forget(['register.step1', 'register.step2']);

        // OTP তৈরি ও পাঠানো
        $plain = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
        $hash  = Hash::make($plain);
        $ttl   = 10; // মিনিট

        DB::table('login_otps')->insert([
            'user_id'    => $user->id,
            'code_hash'  => $hash,
            'sent_to'    => $user->email,
            'expires_at' => now()->addMinutes($ttl),
            'ip'         => request()->ip(),
            'user_agent' => substr((string) request()->userAgent(), 0, 255),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        if ($user->email) {
            Mail::to($user->email)->send(new LoginOtpMail($plain, $ttl));
        }

        if (auth()->check()) {
            auth()->logout();
        }

        session()->invalidate();
        session()->regenerateToken();

        // নতুন সেশন নিয়ে pending user ID রাখি
        session([
            'register.pending_user_id' => $user->id,
        ]);

        return redirect()
            ->route('register.otp.form')
            ->with('status', 'নিবন্ধন সম্পন্ন হয়েছে। ইমেইলে পাঠানো OTP যাচাই করুন।');
    }

    /**
     * STEP 4: show registration OTP form
     */
    public function showOtpForm()
    {
        if (Auth::check()) {
    return redirect($this->redirectDash());
}
        if (! session()->has('register.pending_user_id')) {
            return redirect()
                ->route('register.create')
                ->withErrors(['email' => 'প্রথমে নিবন্ধন সম্পন্ন করুন।']);
        }

        return view('frontend.auth.register-verify-otp');
    }

    /**
     * STEP 4: verify OTP and login
     */
    public function verifyOtp(OtpVerifyRequest $request)
    {
        $pendingUserId = session('register.pending_user_id');

        if (! $pendingUserId) {
            return redirect()
                ->route('register.create')
                ->withErrors(['email' => 'সেশনটির মেয়াদ শেষ হয়েছে। আবার নিবন্ধন করুন।']);
        }

        $otpRow = DB::table('login_otps')
            ->where('user_id', $pendingUserId)
            ->whereNull('consumed_at')
            ->where('expires_at', '>', now())
            ->latest('id')
            ->first();

        if (! $otpRow) {
            return back()->withErrors([
                'otp' => 'OTP পাওয়া যায়নি বা মেয়াদ শেষ। নতুন OTP পাঠিয়ে আবার চেষ্টা করুন।',
            ]);
        }

        DB::table('login_otps')->where('id', $otpRow->id)->increment('attempts');

        if (! Hash::check($request->otp, $otpRow->code_hash)) {
            return back()->withErrors([
                'otp' => 'OTP সঠিক নয়।',
            ]);
        }

        DB::table('login_otps')
            ->where('id', $otpRow->id)
            ->update([
                'consumed_at' => now(),
                'updated_at'  => now(),
            ]);

        // ইউজারকে লগইন করাই – remember = true
        Auth::loginUsingId($pendingUserId, true);

        /** @var \App\Models\User $user */
        $user = Auth::user();

        // email verified মার্ক করে দাও
        if (! $user->email_verified_at) {
            $user->forceFill([
                'email_verified_at' => now(),
            ])->save();
        }

        // register pending session ক্লিন
        session()->forget('register.pending_user_id');

        // প্রথমবারের জন্য PIN already set আছে, তাই এই সেশনে verified true
        session(['pin.verified' => true]);

        return redirect()
            ->route($user->isAdmin() ? 'admin.dashboard' : 'dashboard')
            ->with('success', 'নিবন্ধন ও OTP যাচাই সফল হয়েছে!');
    }
}
