<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class PhoneLoginController extends Controller
{
    /**
     * STEP 1 - Login form (phone + password)
     */
    public function showLoginForm()
    {
        $user = auth()->user();
        if (Auth::check()) {
            return redirect()->route($user->isAdmin() ? 'admin.dashboard' : 'dashboard');
        }

        return view('auth.phone.login');
    }

    /**
     * STEP 1 - phone + password check
     * এখানে শুধু credential check, সাথে সাথে login না।
     * User ID session এ রেখে OTP page এ পাঠাবো।
     */
    public function login(Request $request)
    {
        $request->validate([
            'phone'    => 'required',
            'password' => 'required',
        ]);

        $user = User::where('phone', $request->phone)->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            return back()
                ->withErrors(['phone' => 'Phone or password is incorrect'])
                ->withInput();
        }

        // Credential ঠিক আছে → OTP step এর জন্য session এ user id store
        session([
            'pending_login_user_id' => $user->id,
        ]);

        return redirect()->route('phone.login.otp');
    }

    /**
     * STEP 2 - OTP form
     */
    public function showOtpForm()
    {
        if (! session()->has('pending_login_user_id')) {
            return redirect()->route('phone.login');
        }

        return view('auth.phone.otp');
    }

    /**
     * STEP 2 - OTP submit
     * এখানে OTP শুধু required + 6 digit কিনা দেখব।
     * ✅ OTP ঠিক থাকলে এখানেই login করবো (PIN আর লাগবে না)
     */
    public function submitOtp(Request $request)
    {
        if (! session()->has('pending_login_user_id')) {
            return redirect()->route('phone.login');
        }

        $request->validate([
            'otp' => 'required|digits:6',
        ]);

        // OTP শুধু basic validation, real verify নাই (যদি fake OTP use করো)
        $userId = session('pending_login_user_id');
        $user   = User::find($userId);

        if (! $user) {
            // safe fallback
            session()->forget('pending_login_user_id');
            return redirect()
                ->route('phone.login')
                ->withErrors(['phone' => 'User not found, please login again.']);
        }

        // ✅ এখানে real login করে ফেলছি
        Auth::login($user);

        // session clean
        session()->forget('pending_login_user_id');
        $request->session()->regenerate();

        // dashboard redirect
        return redirect()->route($user->isAdmin() ? 'admin.dashboard' : 'dashboard');
    }

    // 🔻 নিচের PIN related method গুলা আর দরকার নেই,
    // চাইলে পুরোপুরি delete করতে পারো

    /*
    public function showPinForm() { ... }

    public function verifyPin(Request $request) { ... }
    */
}
