<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rules\Password;

class AuthController extends Controller
{
    // ─────────────────────────────────────────
    // REGISTER
    // ─────────────────────────────────────────

    public function showRegister()
    {
        return view('auth.register');
    }

    public function register(Request $request)
    {
        $data = $request->validate([
            'name'          => ['required', 'string', 'max:100'],
            'email'         => ['required', 'email', 'unique:users,email'],
            'password'      => ['required', 'confirmed', Password::min(8)],
            'business_name' => ['required', 'string', 'max:150'],
            'phone'         => ['required', 'string', 'max:20'],
        ]);

        $user = User::create([
            'name'          => $data['name'],
            'email'         => $data['email'],
            'password'      => Hash::make($data['password']),
            'business_name' => $data['business_name'],
            'phone'         => $data['phone'],
            'plan'          => 'free',
            'onboarding_complete' => false,
        ]);

        Auth::login($user);

        return redirect()->route('onboarding')
            ->with('success', 'Welcome! Let\'s set up your business profile.');
    }

    // ─────────────────────────────────────────
    // LOGIN
    // ─────────────────────────────────────────

    public function showLogin()
    {
        return view('auth.login');
    }

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

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

            $user = Auth::user();

            if (! $user->onboarding_complete) {
                return redirect()->route('onboarding');
            }

            return redirect()->intended(route('dashboard'))
                ->with('success', 'Welcome back, ' . $user->name . '!');
        }

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

    // ─────────────────────────────────────────
    // LOGOUT
    // ─────────────────────────────────────────

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

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

    // ─────────────────────────────────────────
    // ONBOARDING
    // ─────────────────────────────────────────

    public function showOnboarding()
    {
        if (Auth::user()->onboarding_complete) {
            return redirect()->route('dashboard');
        }

        return view('auth.onboarding');
    }

    public function completeOnboarding(Request $request)
    {
        $data = $request->validate([
            'address'        => ['required', 'string', 'max:500'],
            'bank_name'      => ['required', 'string', 'max:100'],
            'account_number' => ['required', 'string', 'max:20'],
            'account_name'   => ['required', 'string', 'max:150'],
            'business_type'  => ['nullable', 'string', 'max:50'],
            'logo'           => ['nullable', 'image', 'mimes:jpeg,png,jpg,gif', 'max:2048'],
        ]);

        $user = Auth::user();

        $updateData = [
            'address'            => $data['address'],
            'bank_name'          => $data['bank_name'],
            'account_number'     => $data['account_number'],
            'account_name'       => strtoupper($data['account_name']),
            'business_type'      => $data['business_type'] ?? null,
            'onboarding_complete' => true,
        ];

        // Handle logo upload
        if ($request->hasFile('logo')) {
            $path = $request->file('logo')->store('logos', 'public');
            $updateData['logo_path'] = $path;
        }

        $user->update($updateData);

        return redirect()->route('dashboard')
            ->with('success', 'Your business profile is set up. Welcome to InvoTrack!');
    }
}
