<?php

namespace App\Http\Controllers\Auth;

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

class PhoneLoginController extends Controller
{
    /**
     * Show the login form.
     */
    public function create(Request $request)
    {
        // If intended URL is passed as parameter, store it in session
        if ($request->has('intended')) {
            session(['url.intended' => $request->intended]);
        }
        
        return view('auth.login');
    }

    /**
     * Handle login request.
     */
    public function store(Request $request)
    {
        $request->validate([
            'phone' => ['required', 'string'],
            'password' => ['required', 'string'],
        ]);

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

        if (!$user || !Hash::check($request->password, $user->password)) {
            return back()->withErrors([
                'phone' => 'আপনার দেওয়া তথ্য সঠিক নয়। দয়া করে আবার চেষ্টা করুন।',
            ])->onlyInput('phone');
        }

        // Check if phone is verified
        if (!$user->phone_verified_at) {
            return redirect()->route('otp.verify.form', [
                'phone' => $request->phone, 
                'type' => 'login'
            ])->with('message', 'Please verify your phone number first.');
        }

        Auth::login($user, $request->boolean('remember'));

        $request->session()->regenerate();

        // Transfer session cart to database cart after login
        $cartController = new CartController();
        $cartController->transferSessionCartToDatabase($user->id, $request->input('source') === 'checkout');

        return redirect()->intended(route('dashboard', absolute: false));
    }

    /**
     * Handle AJAX login request.
     */
    public function ajaxLogin(Request $request)
    {
        $request->validate([
            'phone' => ['required', 'string'],
            'password' => ['required', 'string'],
        ]);

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

        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'success' => false,
                'errors' => ['phone' => ['আপনার দেওয়া তথ্য সঠিক নয়। দয়া করে আবার চেষ্টা করুন।']]
            ], 422);
        }

        // Check if phone is verified
        if (!$user->phone_verified_at) {
            return response()->json([
                'success' => false,
                'errors' => ['phone' => ['Please verify your phone number first.']]
            ], 422);
        }

        Auth::login($user, $request->boolean('remember'));

        $request->session()->regenerate();

        // Transfer session cart to database cart after login
        $cartController = new CartController();
        $cartController->transferSessionCartToDatabase($user->id, $request->input('source') === 'checkout');

        return response()->json([
            'success' => true,
            'message' => 'Login successful!',
            'redirect' => url()->previous() ?: route('dashboard')
        ]);
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request)
    {
        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect('/');
    }
}
