<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class CustomerAuthController extends Controller
{
    // Show Login Page
    public function showLogin()
    {
        return view('frontend.auth.login');
    }

    // Handle Phone/OTP Login
    public function verifyOtpLogin(Request $request)
    {
        $request->validate([
            'phone' => 'required|string|min:10',
            'otp'   => 'required|string',
        ]);

        $phone = $request->input('phone');
        $otp = $request->input('otp');

        // Testing Condition: Accept '1234' as valid OTP
        if ($otp === '1234') {
            // Find or create customer
            $customer = Customer::firstOrCreate(
                ['phone' => $phone],
                ['name' => 'User ' . substr($phone, -4)] // Default name fallback
            );

            // Log the customer in (assuming you created a 'customer' guard)
            // If you are just using default web auth for now, use Auth::login($customer)
            Auth::guard('customer')->login($customer, true);

            return redirect()->intended('/')->with('success', 'Logged in successfully!');
        }

        // If real OTP logic is added later, it goes here...

        return back()->withErrors(['otp' => 'Invalid OTP entered. Please try again.']);
    }

    // Redirect to Google
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }

    // Handle Google Callback
    public function handleGoogleCallback()
    {
        try {
            $googleUser = Socialite::driver('google')->user();
            
            $customer = Customer::updateOrCreate(
                ['google_id' => $googleUser->id],
                [
                    'name' => $googleUser->name,
                    'email' => $googleUser->email,
                    'avatar' => $googleUser->avatar,
                ]
            );

            Auth::guard('customer')->login($customer, true);

            return redirect()->intended('/')->with('success', 'Logged in via Google!');
            
        } catch (\Exception $e) {
            return redirect()->route('login')->withErrors(['error' => 'Something went wrong with Google Login.']);
        }
    }

    // Logout
    public function logout(Request $request)
    {
        Auth::guard('customer')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/')->with('success', 'Logged out successfully.');
    }
}
