<?php

namespace App\Http\Controllers\Web;

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

class AuthController extends Controller
{
    public function showLogin()
    {
        if (Auth::check()) {
            return $this->redirectToDashboard();
        }
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (Auth::attempt($request->only('email', 'password'), $request->boolean('remember'))) {
            $request->session()->regenerate();
            return $this->redirectToDashboard();
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ])->withInput($request->only('email'));
    }

    public function showRegister(Request $request)
    {
        if (Auth::check()) {
            return $this->redirectToDashboard();
        }
        $type = $request->get('type', 'company');
        return view('auth.register', compact('type'));
    }

    public function registerCompany(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:8|confirmed',
            'company_name' => 'required|string|max:255',
            'contact_phone' => 'nullable|string|max:20',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'user_type' => 'company',
        ]);

        Company::create([
            'user_id' => $user->id,
            'company_name' => $request->company_name,
            'contact_email' => $request->email,
            'contact_phone' => $request->contact_phone,
            'country' => 'South Africa',
            'is_verified' => true,
        ]);

        Auth::login($user);

        return redirect()->route('company.dashboard')
            ->with('success', 'Welcome to ProcureHub! Your company account has been created.');
    }

    public function registerSupplier(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:8|confirmed',
            'company_name' => 'required|string|max:255',
            'contact_phone' => 'nullable|string|max:20',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'user_type' => 'supplier',
        ]);

        Supplier::create([
            'user_id' => $user->id,
            'company_name' => $request->company_name,
            'slug' => Str::slug($request->company_name) . '-' . Str::random(5),
            'contact_email' => $request->email,
            'contact_phone' => $request->contact_phone,
            'country' => 'South Africa',
            'registration_fee' => 500.00,
            'commission_rate' => 5.00,
            'delivery_self' => $request->boolean('delivery_self', true),
            'delivery_collection' => $request->boolean('delivery_collection', true),
            'delivery_platform' => $request->boolean('delivery_platform', false),
            'is_verified' => true,
            'is_active' => true,
        ]);

        Auth::login($user);

        return redirect()->route('supplier.dashboard')
            ->with('success', 'Welcome to ProcureHub! Your supplier account has been created.');
    }

    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

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

    protected function redirectToDashboard()
    {
        $user = Auth::user();
        
        if ($user->user_type === 'supplier') {
            return redirect()->route('supplier.dashboard');
        }
        
        return redirect()->route('company.dashboard');
    }
}
