<?php

namespace App\Http\Controllers\Business;

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

class AuthController extends Controller
{
    /**
     * Show login form
     */
    public function showLoginForm()
    {
        return view('business.auth.login');
    }

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

        // Determine if identifier is email or phone
        $user = filter_var($credentials['identifier'], FILTER_VALIDATE_EMAIL)
            ? User::where('email', $credentials['identifier'])->first()
            : User::where('phone', $credentials['identifier'])->first();

        if (!$user || !Hash::check($credentials['password'], $user->password)) {
            return back()->withErrors([
                'identifier' => 'The provided credentials do not match our records.',
            ])->withInput();
        }

        // Check if user has business account or business_owner role
        if ($user->account_type !== 'business' && !$user->hasRole('business_owner')) {
            return back()->withErrors([
                'identifier' => 'This account is not a business account.',
            ])->withInput();
        }

        // Check if account is active
        if ($user->status !== 'active') {
            return back()->withErrors([
                'identifier' => 'Your account is not active. Please contact support.',
            ])->withInput();
        }

        // Log the user in
        Auth::login($user, $request->boolean('remember'));

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

        return redirect()->intended(route('business.dashboard'));
    }

    /**
     * Handle logout
     */
    public function logout(Request $request)
    {
        Auth::logout();

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

        return redirect()->route('business.login')
            ->with('success', 'You have been logged out successfully.');
    }

    /**
     * Show password reset request form
     */
    public function showPasswordResetForm()
    {
        return view('business.auth.forgot-password');
    }

    /**
     * Handle password reset request
     */
    public function sendPasswordResetLink(Request $request)
    {
        $request->validate([
            'email' => 'required|email|exists:users,email',
        ]);

        // Here you would send the password reset email
        // For now, just return success

        return back()->with('success', 'Password reset link sent to your email!');
    }
}
