<?php

namespace App\Http\Controllers;

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

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

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

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

        $shopUser->assignTrialSubscription();

        Auth::guard('shop')->login($shopUser);

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

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

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

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

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

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

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