<?php

namespace App\Http\Controllers;

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

class AuthController extends Controller
{
    /**
     * LOGIN API
     * Menerima username/email + password.
     * Mengembalikan token untuk dipakai frontend KP-ASOY.
     */
    public function login(Request $request)
    {
        $request->validate([
            'username' => 'nullable|string',
            'login' => 'nullable|string',
            'password' => 'required|string',
        ]);

        // Frontend KP-ASOY mengirim field "username".
        // Tapi tetap kita dukung field "login" agar fleksibel.
        $login = trim($request->username ?? $request->login);

        if (!$login) {
            return response()->json([
                'message' => 'Username atau email wajib diisi.'
            ], 422);
        }

        // Cek apakah input berupa email atau username
        $field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        $user = User::where($field, $login)->first();
        
        \Illuminate\Support\Facades\Log::info('Login Attempt', ['login' => $login, 'password' => $request->password, 'user_found' => $user ? true : false, 'hash_check' => $user ? Hash::check($request->password, $user->password) : false]);

        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'message' => 'Login gagal. Username/email atau password salah.'
            ], 401);
        }

        // Hapus token lama agar tidak menumpuk terlalu banyak
        $user->tokens()->delete();

        // Buat token Sanctum
        $token = $user->createToken('kp-asoy-token')->plainTextToken;

        return response()->json([
            'message' => 'Login berhasil',
            'token' => $token,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'username' => $user->username,
                'email' => $user->email,
                'role' => strtolower($user->role),
                'jabatan' => $user->jabatan,
            ]
        ], 200);
    }

    /**
     * REGISTER USER
     * Dipakai admin/superadmin untuk membuat akun user/pegawai.
     */
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'username' => 'required|string|max:255|unique:users,username',
            'password' => 'required|string|min:6',
            'role' => [
                'required',
                Rule::in(['user', 'admin', 'superadmin', 'User', 'Admin', 'Superadmin', 'Super Admin'])
            ],
            'jabatan' => 'nullable|string|max:255',
        ]);

        $role = strtolower($request->role);

        if ($role === 'super admin') {
            $role = 'superadmin';
        }

        // Generate email if not provided to satisfy DB unique constraint
        $email = $request->email ?? ($request->username . '@mail.com');

        $user = User::create([
            'name' => $request->name,
            'username' => $request->username,
            'email' => $email,
            'password' => bcrypt($request->password),
            'role' => $role,
            'jabatan' => $request->jabatan,
        ]);

        return response()->json([
            'message' => 'Register berhasil',
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'username' => $user->username,
                'email' => $user->email,
                'role' => $user->role,
                'jabatan' => $user->jabatan,
            ]
        ], 201);
    }

    /**
     * DATA USER YANG SEDANG LOGIN
     */
    public function me(Request $request)
    {
        $user = $request->user();

        return response()->json([
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'username' => $user->username,
                'email' => $user->email,
                'role' => strtolower($user->role),
                'jabatan' => $user->jabatan,
            ]
        ]);
    }

    /**
     * LOGOUT API
     */
    public function logout(Request $request)
    {
        if ($request->user()) {
            $request->user()->currentAccessToken()->delete();
        }

        return response()->json([
            'message' => 'Logout berhasil'
        ]);
    }

    /**
     * UPDATE AKUN
     * Untuk fitur pengaturan akun: ubah email dan password.
     */
    public function updateProfile(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'username' => [
                'required',
                'string',
                Rule::unique('users', 'username')->ignore($user->id),
            ],
            'password' => 'nullable|string|min:6',
            'current_password' => 'nullable|string',
        ]);

        $user->username = $request->username;
        // Jika tidak ada email, tidak perlu diupdate. 
        // Backend tetap aman karena saat register kita yang men-generate email.

        if ($request->filled('password')) {
            if ($user->role === 'user') {
                return response()->json([
                    'message' => 'Pegawai tidak diizinkan mengubah kata sandi.'
                ], 403);
            }
            if (!Hash::check($request->current_password, $user->password)) {
                return response()->json([
                    'message' => 'Kata sandi saat ini tidak cocok.'
                ], 400);
            }
            $user->password = bcrypt($request->password);
        }

        $user->save();

        return response()->json([
            'message' => 'Profil berhasil diperbarui',
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'username' => $user->username,
                'email' => $user->email,
                'role' => strtolower($user->role),
                'jabatan' => $user->jabatan,
            ]
        ]);
    }
}
