<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Member;
use App\Models\Role;
use App\Models\District;
use App\Models\Club;
use App\Models\ActivityLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

class AuthController extends Controller
{
    public function showLogin()
    {
        if (Auth::check()) {
            $user = Auth::user();
            if ($user->isAdmin() || $user->isEditor() || $user->isDistrictManager() || $user->isCoach()) {
                return redirect()->route('admin.dashboard');
            }
            return redirect()->route('member.dashboard');
        }
        return view('auth.login');
    }

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

        $loginInput = $request->input('login');

        // 1) If it looks like an email, try the standard attempt first.
        if (filter_var($loginInput, FILTER_VALIDATE_EMAIL)) {
            $attempt = Auth::attempt(['email' => $loginInput, 'password' => $request->password], $request->has('remember'));
        } else {
            $attempt = false;
        }

        // 2) If attempt failed (or input wasn't an email), try to locate a user by several fields and validate password.
        if (empty($attempt)) {
            $userQuery = User::where('email', $loginInput)
                ->orWhere('name', $loginInput)
                ->orWhereRaw("SUBSTRING_INDEX(email, '@', 1) = ?", [$loginInput]);

            $user = $userQuery->first();

            // Allow passwordless admin login only when explicitly enabled or in local env
            $passwordlessEnabled = env('ADMIN_PASSWORDLESS_LOGIN', false) || env('APP_ENV') === 'local';

            if ($user) {
                if ($passwordlessEnabled && $user->isAdmin()) {
                    Auth::login($user, $request->has('remember'));
                    $attempt = true;
                } elseif (Hash::check($request->password, $user->password)) {
                    Auth::login($user, $request->has('remember'));
                    $attempt = true;
                }
            }
        }

        if (! empty($attempt)) {
            $user = Auth::user();
            
            if ($user->status === 'suspended') {
                Auth::logout();
                return back()->withErrors(['email' => 'Your account has been suspended. Please contact the administrator.']);
            }

            // Log activity
            ActivityLog::create([
                'user_id' => $user->id,
                'action' => 'login',
                'details' => 'User logged in successfully.',
                'ip_address' => $request->ip()
            ]);

            $request->session()->regenerate();

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

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

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

    public function showRegister()
    {
        if (Auth::check()) {
            $user = Auth::user();
            if ($user->isAdmin() || $user->isEditor() || $user->isDistrictManager() || $user->isCoach()) {
                return redirect()->route('admin.dashboard');
            }
            return redirect()->route('member.dashboard');
        }
        $districts = District::all();
        $clubs = Club::all();
        return view('auth.register', compact('districts', 'clubs'));
    }

    public function register(Request $request)
    {
        $request->validate([
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
            'phone' => 'required|string|max:15',
            'gender' => 'required|string',
            'dob' => 'required|date',
            'address' => 'required|string|max:255',
            'district_id' => 'required|exists:districts,id',
            'club_id' => 'nullable|exists:clubs,id',
            'photo' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        try {
            DB::beginTransaction();

            // 1. Get Member Role
            $memberRole = Role::where('name', 'member')->first();

            // 2. Create User
            $user = User::create([
                'name' => $request->first_name . ' ' . $request->last_name,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'role_id' => $memberRole ? $memberRole->id : null,
                'status' => 'active'
            ]);

            // 3. Handle Photo Upload
            $photoPath = null;
            if ($request->hasFile('photo')) {
                $file = $request->file('photo');
                $filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
                $file->move(public_path('uploads/members'), $filename);
                $photoPath = 'uploads/members/' . $filename;
            }

            // 4. Generate Membership ID (e.g. LPTA-00123)
            $count = Member::count() + 1;
            $memberId = sprintf('LPTA-%05d', $count);

            // 5. Create Member Profile
            Member::create([
                'user_id' => $user->id,
                'member_id' => $memberId,
                'first_name' => $request->first_name,
                'last_name' => $request->last_name,
                'email' => $request->email,
                'phone' => $request->phone,
                'gender' => $request->gender,
                'dob' => $request->dob,
                'address' => $request->address,
                'belt_rank' => 'White', // Default belt rank for new register
                'district_id' => $request->district_id,
                'club_id' => $request->club_id,
                'photo' => $photoPath,
                'status' => 'pending', // Pending approval
                'expiry_date' => now()->addYear() // Initial 1 year registration
            ]);

            // Log activity
            ActivityLog::create([
                'user_id' => $user->id,
                'action' => 'register',
                'details' => 'New member registered: ' . $memberId,
                'ip_address' => $request->ip()
            ]);

            DB::commit();

            Auth::login($user);

            return redirect()->route('member.dashboard')->with('success', 'Registration successful! Your membership application is pending administrative approval.');

        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Registration failed. Please try again. Error: ' . $e->getMessage())->withInput();
        }
    }

    public function logout(Request $request)
    {
        if (Auth::check()) {
            ActivityLog::create([
                'user_id' => Auth::id(),
                'action' => 'logout',
                'details' => 'User logged out.',
                'ip_address' => $request->ip()
            ]);
        }

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

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