<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        \Illuminate\Support\Facades\Log::info('Login attempt', $request->all());

        $request->validate([
            'login' => 'required|string', // Can be email or mobile
            'password' => 'required|string',
        ]);

        // Try to find user by email or mobile
        $user = User::where('email', $request->login)
            ->orWhere('mobile', $request->login)
            ->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'login' => ['The provided credentials are incorrect.'],
            ]);
        }

        // Load relationships
        $user->load(['role', 'head', 'members']);

        // Permissions are now role-based
        $permissions = $user->role->permissions ?? [];

        // Create token
        $token = $user->createToken('auth-token')->plainTextToken;

        return response()->json([
            'message' => 'Login successful',
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'mobile' => $user->mobile,
                'role' => $user->role->name,
                'region' => $user->region,
                'head' => $user->head()->first(),
                'members' => $user->members,
                'permissions' => $permissions,
            ],
            'token' => $token,
        ]);
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json([
            'message' => 'Logged out successfully',
        ]);
    }

    public function me(Request $request)
    {
        $user = $request->user();
        $user->load(['role', 'head', 'members']);

        // Permissions are now role-based
        $permissions = $user->role->permissions ?? [];

        return response()->json([
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'mobile' => $user->mobile,
                'role' => $user->role->name,
                'region' => $user->region,
                'head' => $user->head()->first(),
                'members' => $user->members,
                'permissions' => $permissions,
            ],
        ]);
    }
}
