<?php

namespace App\Http\Controllers;

use App\Models\Business;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;

class BusinessAuthController extends Controller
{
    public function showRegister()
    {
        return Inertia::render('Business/Auth/Register');
    }

    public function register(Request $request)
    {
        $request->validate([
            'shop_name' => 'required|string|max:255',
            'phone_number' => 'required|string|max:20|unique:businesses',
            'password' => 'required|string|min:6|confirmed',
        ]);

        $business = Business::create([
            'shop_name' => $request->shop_name,
            'phone_number' => $request->phone_number,
            'password' => $request->password,
        ]);

        $business->assignTrial();

        Auth::guard('business')->login($business);

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

    public function showLogin()
    {
        return Inertia::render('Business/Auth/Login');
    }

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

        if (Auth::guard('business')->attempt(['phone_number' => $request->phone_number, 'password' => $request->password])) {
            return redirect()->route('business.dashboard');
        }

        return back()->withErrors(['phone_number' => 'Invalid credentials.']);
    }

    public function logout()
    {
        Auth::guard('business')->logout();

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