<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class AuthController extends Controller
{
    public function showLogin()
    {
        if (Auth::guard('client')->check()) {
            return redirect()->route('client.dashboard');
        }
        return view('client.auth.login');
    }

    public function showRegister()
    {
        if (Auth::guard('client')->check()) {
            return redirect()->route('client.dashboard');
        }
        return view('client.auth.register');
    }

    public function login(Request $request)
    {
        $data = $request->validate([
            'email'    => 'required|email',
            'password' => 'required|string|min:6',
        ], [
            'email.required'    => 'И-мэйлээ оруулна уу.',
            'password.required' => 'Нууц үгээ оруулна уу.',
        ]);

        if (Auth::guard('client')->attempt($data, $request->boolean('remember'))) {
            $request->session()->regenerate();

            $client = Auth::guard('client')->user();
            if (! $client->is_active) {
                Auth::guard('client')->logout();
                return back()->withErrors(['email' => 'Таны бүртгэл идэвхгүй байна.']);
            }

            $client->update(['last_login_at' => now()]);

            // AJAX тохиолдолд JSON response
            if ($request->wantsJson() || $request->ajax()) {
                return response()->json([
                    'success'  => true,
                    'redirect' => route('client.dashboard'),
                    'message'  => 'Амжилттай нэвтэрлээ.',
                ]);
            }

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

        if ($request->wantsJson() || $request->ajax()) {
            return response()->json([
                'success' => false,
                'message' => 'И-мэйл эсвэл нууц үг буруу байна.',
            ], 422);
        }

        return back()
            ->withErrors(['email' => 'И-мэйл эсвэл нууц үг буруу байна.'])
            ->onlyInput('email');
    }

    public function register(Request $request)
    {
        $data = $request->validate([
            'name'         => 'required|string|max:255',
            'company_name' => 'nullable|string|max:255',
            'email'        => ['required', 'email', 'max:255', Rule::unique('clients', 'email')],
            'phone'        => 'required|string|max:30',
            'position'     => 'nullable|string|max:120',
            'industry'     => 'nullable|string|max:120',
            'password'     => 'required|string|min:6|confirmed',
        ], [
            'name.required'      => 'Нэрээ оруулна уу.',
            'email.required'     => 'И-мэйлээ оруулна уу.',
            'email.unique'       => 'Энэ и-мэйлээр аль хэдийн бүртгэгдсэн байна.',
            'phone.required'     => 'Утасны дугаараа оруулна уу.',
            'password.required'  => 'Нууц үгээ оруулна уу.',
            'password.min'       => 'Нууц үг доод тал нь 6 тэмдэгт байна.',
            'password.confirmed' => 'Нууц үг таарахгүй байна.',
        ]);

        $client = Client::create([
            'name'         => $data['name'],
            'company_name' => $data['company_name'] ?? null,
            'email'        => $data['email'],
            'phone'        => $data['phone'],
            'position'     => $data['position'] ?? null,
            'industry'     => $data['industry'] ?? null,
            'password'     => $data['password'],
            'status'       => 'lead',
            'source'       => 'website',
            'is_active'    => true,
        ]);

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

        if ($request->wantsJson() || $request->ajax()) {
            return response()->json([
                'success'  => true,
                'redirect' => route('client.dashboard'),
                'message'  => 'Бүртгэл амжилттай үүслээ.',
            ]);
        }

        return redirect()->route('client.dashboard')->with('success', 'Тавтай морилно уу!');
    }

    public function logout(Request $request)
    {
        Auth::guard('client')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('home');
    }
}
