<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class UserLoginController extends Controller
{
    /**
     * Helper URL API Backend
     */
    private function apiUrl($endpoint = '')
    {
        return rtrim(env('BACKEND_API_URL'), '/') . '/' . ltrim($endpoint, '/');
    }

    /**
     * PROSES LOGIN
     * Login tidak lagi membaca database KP-ASOY.
     * Login dikirim ke API Laravel_KP.
     */
    public function login(Request $request)
    {
        $request->validate([
            'username' => 'required',
            'password' => 'required',
        ]);

        try {
            $response = Http::post($this->apiUrl('/login'), [
                'username' => $request->username,
                'password' => $request->password,
            ]);

            if (!$response->successful()) {
                Log::error('Login API gagal', [
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);

                return back()->with('error', 'Username atau password salah.');
            }

            $data = $response->json();

            if (!isset($data['token']) || !isset($data['user'])) {
                Log::error('Format response login API tidak sesuai', [
                    'response' => $data,
                ]);

                return back()->with('error', 'Login gagal. Response backend tidak sesuai.');
            }

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

            session([
                'api_token' => $data['token'],
                'user' => $data['user'],
                'user_id' => $data['user']['id'] ?? null,
                'user_name' => $data['user']['name'] ?? null,
                'username' => $data['user']['username'] ?? null,
                'role' => $data['user']['role'] ?? 'user',
            ]);

            return $this->redirectUser($data['user']);
        } catch (\Exception $e) {
            Log::error('Tidak dapat terhubung ke backend API', [
                'message' => $e->getMessage(),
            ]);

            return back()->with('error', 'Tidak dapat terhubung ke backend. Pastikan Laravel_KP berjalan di port 8001.');
        }
    }

    /**
     * REDIRECT BERDASARKAN ROLE DARI BACKEND
     */
    private function redirectUser($user)
    {
        $role = $user['role'] ?? 'user';

        if ($role === 'admin') {
            return redirect()->route('admin.dashboard');
        }

        if ($role === 'superadmin') {
            return redirect()->route('admin.superadmin.dashboard');
        }

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

    /**
     * PROSES LOGOUT
     * Logout dari frontend dan backend API.
     */
    public function logout(Request $request)
    {
        try {
            if (session('api_token')) {
                Http::withToken(session('api_token'))
                    ->post($this->apiUrl('/logout'));
            }
        } catch (\Exception $e) {
            Log::warning('Logout API gagal atau endpoint logout belum tersedia', [
                'message' => $e->getMessage(),
            ]);
        }

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('login');
    }

    /**
     * USER SETTINGS
     * Update email dan password dikirim ke backend.
     *
     * Catatan:
     * Endpoint backend yang dibutuhkan:
     * PUT /api/profile/update
     */
    public function updateSettings(Request $request)
    {
        $request->validate([
            'username' => 'required|string',
            'current_password' => 'nullable|string',
            'password' => 'nullable|min:6|confirmed',
        ], [
            'password.confirmed' => 'Konfirmasi kata sandi tidak cocok.'
        ]);

        try {
            $payload = [
                'username' => $request->username,
            ];

            if ($request->filled('password')) {
                if (session('role') === 'user' || session('user')['role'] === 'user') {
                    return back()->with('error', 'Pegawai tidak diizinkan mengubah kata sandi.');
                }
                $payload['password'] = $request->password;
                $payload['current_password'] = $request->current_password;
            }

            $response = Http::withToken(session('api_token'))
                ->put($this->apiUrl('/profile/update'), $payload);

            if ($response->status() === 400) {
                return back()->with('error', $response->json('message', 'Terjadi kesalahan pada input kata sandi.'));
            }

            if (!$response->successful()) {
                Log::error('Update akun gagal', [
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);

                return back()->with('error', 'Gagal memperbarui akun: ' . $response->json('message', ''));
            }

            $data = $response->json();

            if (isset($data['user'])) {
                session(['user' => $data['user']]);
                session(['user_name' => $data['user']['name']]);
                session(['username' => $data['user']['username']]);
            }

            return back()->with('success', 'Berhasil update akun!');
        } catch (\Exception $e) {
            Log::error('Update akun gagal terhubung backend', [
                'message' => $e->getMessage(),
            ]);

            return back()->with('error', 'Tidak dapat terhubung ke backend.');
        }
    }

    /*
    |--------------------------------------------------------------------------
    | FITUR MANAJEMEN USER / PEGAWAI
    |--------------------------------------------------------------------------
    | Admin membuat akun melalui backend API Laravel_KP.
    */

    /**
     * ADMIN - LIST SEMUA USER
     *
     * Catatan:
     * Endpoint backend yang dibutuhkan:
     * GET /api/users
     */
    public function userList()
    {
        try {
            $response = Http::withToken(session('api_token'))
                ->acceptJson()
                ->get($this->apiUrl('/users'));

            if (!$response->successful()) {
                Log::error('Gagal mengambil data user dari backend', [
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);

                $users = collect([]);
                return view('admin.users', compact('users'))
                    ->with('error', 'Gagal mengambil data user dari backend.');
            }

            $data = $response->json();
            $rawUsers = $data['data'] ?? $data['users'] ?? $data ?? [];
            // Bungkus sebagai Collection agar metode seperti ->where() dapat digunakan di view
            $users = collect($rawUsers)->map(fn($u) => (object)$u);

            return view('admin.users', compact('users'));
        } catch (\Exception $e) {
            Log::error('Gagal terhubung backend saat mengambil user', [
                'message' => $e->getMessage(),
            ]);

            $users = [];
            return view('admin.users', compact('users'))
                ->with('error', 'Tidak dapat terhubung ke backend.');
        }
    }

    /**
     * ADMIN - FORM TAMBAH USER
     */
    public function createUser()
    {
        return view('admin.create-user');
    }

    /**
     * ADMIN - SIMPAN USER BARU
     *
     * Catatan:
     * Endpoint backend yang dibutuhkan:
     * POST /api/register
     * atau POST /api/users
     */
    public function storeUser(Request $request)
    {
        $request->validate([
            'name'     => 'required',
            'username' => 'required',
            'password' => 'required|min:6',
            'jabatan'  => 'nullable',
            'role'     => 'nullable',
        ]);

        try {
            $response = Http::withToken(session('api_token'))
                ->acceptJson()
                ->post($this->apiUrl('/register'), [
                    'name'     => $request->name,
                    'username' => $request->username,
                    'password' => $request->password,
                    'jabatan'  => $request->jabatan,
                    'role'     => $request->role ?? 'user',
                ]);

            if ($response->status() === 422) {
                $errors = collect($response->json('errors', []))->flatten()->toArray();
                return back()->withInput()->withErrors($errors);
            }

            if (!$response->successful()) {
                Log::error('Gagal membuat user lewat backend', [
                    'status' => $response->status(),
                    'body'   => $response->body(),
                ]);
                return back()->withInput()
                    ->with('error', 'User gagal ditambahkan. ' . ($response->json('message') ?? ''));
            }

            return redirect()->route('admin.users')
                ->with('success', 'User berhasil ditambahkan!');
        } catch (\Exception $e) {
            Log::error('Gagal terhubung backend saat membuat user', ['message' => $e->getMessage()]);
            return back()->withInput()->with('error', 'Tidak dapat terhubung ke backend.');
        }
    }

    /**
     * ADMIN - FORM EDIT USER
     */
    public function editUser($id)
    {
        try {
            $response = Http::withToken(session('api_token'))
                ->acceptJson()
                ->get($this->apiUrl('/users/' . $id));

            if (!$response->successful()) {
                return redirect()->route('admin.users')
                    ->with('error', 'Pengguna tidak ditemukan.');
            }

            $data = $response->json();
            $user = (object)($data['data'] ?? $data['user'] ?? $data);

            if (($user->role ?? '') === 'superadmin' && session('user')['role'] !== 'superadmin') {
                return redirect()->route('admin.users')
                    ->with('error', 'Akses ditolak. Anda tidak dapat mengedit Super Admin.');
            }

            return view('admin.edit-user', compact('user'));
        } catch (\Exception $e) {
            Log::error('Gagal mengambil data user untuk edit', ['message' => $e->getMessage()]);
            return redirect()->route('admin.users')
                ->with('error', 'Tidak dapat terhubung ke backend.');
        }
    }

    /**
     * ADMIN - UPDATE USER
     */
    public function updateUser(Request $request, $id)
    {
        try {
            $checkResponse = Http::withToken(session('api_token'))->acceptJson()->get($this->apiUrl('/users/' . $id));
            if ($checkResponse->successful()) {
                $checkData = $checkResponse->json();
                $checkUser = (object)($checkData['data'] ?? $checkData['user'] ?? $checkData);
                if (($checkUser->role ?? '') === 'superadmin' && session('user')['role'] !== 'superadmin') {
                    return redirect()->route('admin.users')->with('error', 'Akses ditolak. Anda tidak dapat mengubah data Super Admin.');
                }
            }
        } catch (\Exception $e) {
            // Continue if check fails, API might still reject it
        }

        $request->validate([
            'name'     => 'required',
            'username' => 'required',
            'jabatan'  => 'nullable',
            'role'     => 'nullable',
            'password' => 'nullable|min:6',
        ]);

        try {
            $payload = [
                'name'     => $request->name,
                'username' => $request->username,
                'jabatan'  => $request->jabatan,
                'role'     => $request->role,
            ];
            if ($request->filled('password')) {
                $payload['password'] = $request->password;
            }

            $response = Http::withToken(session('api_token'))
                ->acceptJson()
                ->put($this->apiUrl('/users/' . $id), $payload);

            if ($response->status() === 422) {
                $errors = collect($response->json('errors', []))->flatten()->toArray();
                return back()->withInput()->withErrors($errors);
            }

            if (!$response->successful()) {
                return back()->withInput()
                    ->with('error', 'Gagal memperbarui pengguna: ' . ($response->json('message') ?? ''));
            }

            return redirect()->route('admin.users')
                ->with('success', 'Data pengguna berhasil diperbarui!');
        } catch (\Exception $e) {
            Log::error('Gagal update user', ['message' => $e->getMessage()]);
            return back()->withInput()->with('error', 'Tidak dapat terhubung ke backend.');
        }
    }

    /**
     * ADMIN - HAPUS USER
     *
     * Catatan:
     * Untuk revisi KP, admin sebaiknya hanya membuat akun.
     * Hapus user lebih aman hanya untuk superadmin.
     *
     * Endpoint backend yang dibutuhkan:
     * DELETE /api/users/{id}
     */
    public function destroyUser($id)
    {
        try {
            if ((int) $id === (int) session('user_id')) {
                return back()->with('error', 'Anda tidak bisa menghapus akun sendiri!');
            }

            $checkResponse = Http::withToken(session('api_token'))->acceptJson()->get($this->apiUrl('/users/' . $id));
            if ($checkResponse->successful()) {
                $checkData = $checkResponse->json();
                $checkUser = (object)($checkData['data'] ?? $checkData['user'] ?? $checkData);
                if (($checkUser->role ?? '') === 'superadmin' && session('user')['role'] !== 'superadmin') {
                    return back()->with('error', 'Akses ditolak. Anda tidak dapat menghapus Super Admin.');
                }
            }

            $response = Http::withToken(session('api_token'))
                ->acceptJson()
                ->delete($this->apiUrl('/users/' . $id));

            if (!$response->successful()) {
                Log::error('Gagal menghapus user lewat backend', [
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);

                return back()->with('error', 'User gagal dihapus.');
            }

            return back()->with('success', 'User berhasil dihapus!');
        } catch (\Exception $e) {
            Log::error('Gagal terhubung backend saat hapus user', [
                'message' => $e->getMessage(),
            ]);

            return back()->with('error', 'Tidak dapat terhubung ke backend.');
        }
    }
}