<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Customer;
use App\Models\AuditLog;
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 Auth::user()->isAdmin() ? redirect()->route('admin.dashboard') : redirect()->route('customer.dashboard');
        }
        return view('auth.login');
    }

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

        $remember = $request->boolean('remember');

        if (Auth::attempt($credentials, $remember)) {
            $request->session()->regenerate();
            $user = Auth::user();

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

            AuditLog::record('user_login', $user, null, ['ip' => $request->ip()]);

            if ($user->isAdmin()) {
                return redirect()->intended(route('admin.dashboard'));
            }

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

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

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

    public function register(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'phone' => 'required|string|max:20|unique:users',
            'password' => 'required|string|min:8|confirmed',
            'city' => 'nullable|string|max:100',
            'address' => 'nullable|string|max:500',
            'preferred_contact' => 'nullable|in:whatsapp,call,email',
            'terms' => 'accepted',
        ]);

        $user = User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'phone' => $validated['phone'],
            'password' => Hash::make($validated['password']),
            'role' => 'customer',
            'status' => 'active',
            'last_login_at' => now(),
        ]);

        $customerCode = 'MS-CUST-' . (1000 + $user->id);

        Customer::create([
            'user_id' => $user->id,
            'customer_code' => $customerCode,
            'full_name' => $validated['name'],
            'phone' => $validated['phone'],
            'email' => $validated['email'],
            'city' => $validated['city'] ?? 'Dhaka',
            'district' => $validated['city'] ?? 'Dhaka',
            'address' => $validated['address'] ?? null,
            'preferred_contact' => $validated['preferred_contact'] ?? 'whatsapp',
            'status' => 'active',
        ]);

        Auth::login($user);

        AuditLog::record('customer_registered', $user);

        return redirect()->route('customer.dashboard')->with('success', 'Welcome to MotoSolution Bangladesh! Your customer portal is now active.');
    }

    public function logout(Request $request)
    {
        AuditLog::record('user_logout', Auth::user());

        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

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

    public function showForgotPassword()
    {
        return view('auth.forgot-password');
    }

    public function forgotPassword(Request $request)
    {
        $request->validate(['email' => 'required|email']);
        return back()->with('status', 'If an account exists with this email, password reset instructions have been dispatched.');
    }
}
