<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use Spatie\Permission\Models\Role;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        // 1. Validasi input, tambahkan 'role'
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|unique:users',
            'password' => 'required|string|min:8|confirmed',
            'role' => 'required|in:customer,contributor', // Pastikan hanya role ini yang boleh masuk
        ]);

        // 2. Jika user memilih 'contributor', cek apakah pendaftaran masih dibuka di tabel settings
        if ($request->role === 'contributor') {
            $isRegistrationOpen = \App\Models\Setting::where('key', 'is_contributor_registration_open')
                                                    ->value('value');

            if ($isRegistrationOpen != '1') {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Maaf, pendaftaran untuk kontributor saat ini sedang ditutup.'
                ], 403);
            }
        }

        // 3. Buat User
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'username' => explode('@', $request->email)[0] . rand(10, 99),
            'password' => Hash::make($request->password),
        ]);

        // 4. Beri role berdasarkan input request (Spatie)
        // Jika input 'contributor' dan lolos pengecekan di atas, maka assign role tersebut
        $user->assignRole($request->role);

        // 5. Generate Token
        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'status' => 'success',
            'token' => $token,
            'user' => $user,
        ], 201);
    }

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

        $user = User::where('email', $request->email)->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'message' => ['Kredensial yang Anda berikan salah.'],
            ]);
        }

        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'token' => $token,
            'user' => $user,
        ]);
    }

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

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

    public function user(Request $request)
    {
        return response()->json($request->user()->load('roles'));
    }
}