<?php

namespace App\Http\Controllers;

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

class UserManagementController extends Controller
{

    protected $apiBaseUrl = 'http://192.168.100.6:8081/api';

    public function index()
    {
        try {
            $user = Session::get('user');
            $accessToken = $user['access_token'] ?? null;

            if (!$accessToken) {
                Log::info('No access token found, redirecting to login from user-management');
                return redirect()->route('login')->with('error', 'Please log in to view user management.');
            }

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->get("{$this->apiBaseUrl}/cms/admin");

            $json = $response->json();

            Log::info('User Management API Response: ', $json);

            if ($response->successful() && isset($json['data']) && is_array($json['data'])) {
                $users = array_map(function ($admin) {
                    return [
                        'admin_uuid' => $admin['admin_uuid'],
                        'username' => $admin['username'],
                        'firstName' => $admin['firstname'],
                        'lastName' => $admin['lastname'],
                        'role' => $admin['role'] == '1' ? 'Admin' : 'User',
                        'email' => $admin['email'],
                        'status' => $admin['status'] ? 'Active' : 'Inactive',
                    ];
                }, $json['data']);

                return view('pages.user-management', [
                    'users' => $users,
                ]);
            } else {
                Log::warning('No user data found or invalid API response: ', $json);
                return view('pages.user-management', [
                    'users' => [],
                ]);
            }
        } catch (\Exception $e) {
            Log::error('Error fetching user data: ' . $e->getMessage());
            return view('pages.user-management', [
                'users' => [],
            ]);
        }
    }

    public function create()
    {
        return view('pages.user-management.add-user');
    }

    public function store(Request $request)
    {
        try {
            $user = Session::get('user');
            $accessToken = $user['access_token'] ?? null;

            if (!$accessToken) {
                return redirect()->route('login')->with('error', 'Please log in to add a user.');
            }

            $validated = $request->validate([
                'username' => 'required|string|max:255',
                'firstName' => 'required|string|max:255',
                'lastName' => 'required|string|max:255',
                'role' => 'required|in:0,1',
                'email' => 'required|email|max:255',
                'status' => 'required|in:active,inactive',
            ]);

            // Generate password via API
            $passwordResponse = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->post("{$this->apiBaseUrl}/cms/generatePassword");

            $passwordJson = $passwordResponse->json();

            if (!$passwordResponse->successful() || !isset($passwordJson['data']['password'])) {
                Log::error('Failed to generate password: ', $passwordJson);
                return redirect()->back()->with('error', 'Failed to generate password.');
            }

            $generatedPassword = $passwordJson['data']['password'];

            $payload = [
                'username' => $validated['username'],
                'firstname' => $validated['firstName'],
                'lastname' => $validated['lastName'],
                'role' => $validated['role'],
                'email' => $validated['email'],
                'password' => $generatedPassword,
                'status' => $validated['status'],
            ];

            Log::info('API Payload for creating user: ', $payload);

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->post("{$this->apiBaseUrl}/cms/admin", $payload);

            $json = $response->json();

            if ($response->successful()) {
                Log::info('User created successfully: ', $json);
                return redirect()->route('user.management')
                    ->with('success', "User added successfully. Generated password: {$generatedPassword}");
            } else {
                Log::error('Failed to create user: ', $json);
                return redirect()->back()->with('error', $json['message'] ?? 'Failed to add user.');
            }
        } catch (\Exception $e) {
            Log::error('Error creating user: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while adding the user.');
        }
    }

    public function show($uuid)
    {
        try {
            $user = Session::get('user');
            $accessToken = $user['access_token'] ?? null;

            if (!$accessToken) {
                Log::info('No access token found, redirecting to login from user-management show');
                return redirect()->route('login')->with('error', 'Please log in to view user details.');
            }

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->get("{$this->apiBaseUrl}/cms/admin/{$uuid}");

            $json = $response->json();

            if ($response->successful() && isset($json['data'])) {
                $userData = [
                    'admin_uuid' => $json['data']['admin_uuid'],
                    'username' => $json['data']['username'],
                    'firstName' => $json['data']['firstname'],
                    'lastName' => $json['data']['lastname'],
                    'role' => $json['data']['role'] == '1' ? 'Admin' : 'User',
                    'email' => $json['data']['email'],
                    'status' => $json['data']['status'] ? 'Active' : 'Inactive',
                    'generated_password' => $json['data']['generated_password'] ?? null,
                ];
                return view('pages.user-management.show-user', ['user' => $userData]);
            } else {
                Log::warning('User not found: ', $json);
                return redirect()->route('user.management')->with('error', $json['message'] ?? 'User not found.');
            }
        } catch (\Exception $e) {
            Log::error('Error fetching user: ' . $e->getMessage());
            return redirect()->route('user.management')->with('error', 'An error occurred while fetching the user.');
        }
    }

    public function edit($uuid)
    {
        try {
            $user = Session::get('user');
            $accessToken = $user['access_token'] ?? null;

            if (!$accessToken) {
                Log::info('No access token found, redirecting to login from user-management edit');
                return redirect()->route('login')->with('error', 'Please log in to edit a user.');
            }

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->get("{$this->apiBaseUrl}/cms/admin/{$uuid}");

            $json = $response->json();

            if ($response->successful() && isset($json['data'])) {
                $userData = [
                    'admin_uuid' => $json['data']['admin_uuid'],
                    'username' => $json['data']['username'],
                    'firstName' => $json['data']['firstname'],
                    'lastName' => $json['data']['lastname'],
                    'role' => $json['data']['role'] == '1' ? 'Admin' : 'User',
                    'email' => $json['data']['email'],
                    'status' => $json['data']['status'] ? 'Active' : 'Inactive',
                ];
                return view('pages.user-management.edit-user', ['user' => $userData]);
            } else {
                Log::warning('User not found: ', $json);
                return redirect()->route('user.management')->with('error', $json['message'] ?? 'User not found.');
            }
        } catch (\Exception $e) {
            Log::error('Error fetching user for edit: ' . $e->getMessage());
            return redirect()->route('user.management')->with('error', 'An error occurred while fetching the user.');
        }
    }

    public function update(Request $request, $uuid)
    {
        try {
            $user = Session::get('user');
            $accessToken = $user['access_token'] ?? null;

            if (!$accessToken) {
                return redirect()->route('login')->with('error', 'Please log in to update a user.');
            }

            $validated = $request->validate([
                'username' => 'required|string|max:255',
                'firstName' => 'required|string|max:255',
                'lastName' => 'required|string|max:255',
                'role' => 'required|in:0,1',
                'email' => 'required|email|max:255',
                'password' => 'nullable|string|min:8',
                'status' => 'required|in:active,inactive',
            ]);

            $data = [
                'username' => $validated['username'],
                'firstname' => $validated['firstName'],
                'lastname' => $validated['lastName'],
                'role' => $validated['role'],
                'email' => $validated['email'],
                'status' => $validated['status'],
            ];

            if (!empty($validated['password'])) {
                $data['password'] = $validated['password'];
            }

            Log::info('API Payload for updating user: ', $data);

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->put("{$this->apiBaseUrl}/cms/admin/{$uuid}", $data);

            $json = $response->json();

            if ($response->successful()) {
                Log::info('User updated successfully: ', $json);
                return redirect()->route('user.management')
                    ->with('success', $json['message'] ?? 'User updated successfully');
            } else {
                Log::error('Failed to update user: ', $json);
                return redirect()->back()->with('error', $json['message'] ?? 'Failed to update user.');
            }
        } catch (\Exception $e) {
            Log::error('Error updating user: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while updating the user.');
        }
    }

    public function destroy($uuid)
    {
        try {
            $user = Session::get('user');
            $accessToken = $user['access_token'] ?? null;

            if (!$accessToken) {
                return redirect()->route('login')->with('error', 'Please log in to delete a user.');
            }

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->delete("{$this->apiBaseUrl}/cms/admin/{$uuid}");

            $json = $response->json();

            if ($response->successful()) {
                Log::info('User deleted successfully: ', $json);
                return redirect()->route('user.management')
                    ->with('success', $json['message'] ?? 'User deleted successfully');
            } else {
                Log::error('Failed to delete user: ', $json);
                return redirect()->back()->with('error', $json['message'] ?? 'Failed to delete user.');
            }
        } catch (\Exception $e) {
            Log::error('Error deleting user: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while deleting the user.');
        }
    }

    public function batchDelete(Request $request)
    {
        try {
            $user = Session::get('user');
            $accessToken = $user['access_token'] ?? null;

            if (!$accessToken) {
                return redirect()->route('login')->with('error', 'Please log in to delete users.');
            }

            $uuids = $request->input('admin_uuid', []);

            if (empty($uuids)) {
                return redirect()->back()->with('error', 'No users selected for deletion.');
            }

            Log::info('Batch delete UUIDs: ', $uuids);

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->delete("{$this->apiBaseUrl}/cms/adminBatchDelete", [
                'admin_uuid' => $uuids,
            ]);

            $json = $response->json();

            if ($response->successful()) {
                Log::info('Batch delete successful for UUIDs: ', $uuids);
                return redirect()->route('user.management')
                    ->with('success', $json['message'] ?? 'Users deleted successfully');
            } else {
                Log::error('Failed to batch delete users: ', $json);
                return redirect()->back()->with('error', $json['message'] ?? 'Failed to delete users.');
            }
        } catch (\Exception $e) {
            Log::error('Error in batch delete: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while deleting users.');
        }
    }

    public function changeStatus(Request $request, $uuid)
    {
        try {
            $user = Session::get('user');
            $accessToken = $user['access_token'] ?? null;

            if (!$accessToken) {
                return redirect()->route('login')->with('error', 'Please log in to change user status.');
            }

            $validated = $request->validate([
                'status' => 'required|in:active,inactive',
            ]);

            $payload = [
                'admin_uuid' => $uuid,
                'status' => $validated['status'],
            ];

            Log::info('API Payload for changing status: ', $payload);

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->post("{$this->apiBaseUrl}/cms/adminChangeStatus", $payload);

            $json = $response->json();

            if ($response->successful()) {
                Log::info('Status changed successfully for UUID: ' . $uuid);
                return redirect()->route('user.management')
                    ->with('success', $json['message'] ?? 'Status updated successfully');
            } else {
                Log::error('Failed to change status: ', $json);
                return redirect()->back()->with('error', $json['message'] ?? 'Failed to update status.');
            }
        } catch (\Exception $e) {
            Log::error('Error changing status: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while changing status.');
        }
    }
}