<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GuzzleHttp\Client;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Http\RedirectResponse;

class AdminUserController extends Controller
{
    public function index(Request $request)
    {
       
       $client = new Client([
            'base_uri' => config('services.admin_api.base_url'),
            'timeout'  => 5,
        ]);

        try {
            $response = $client->get('/list_user_admin');
            $data     = json_decode($response->getBody(), true);
            $allUsers = $data['users'] ?? [];
            $totalUsers = $data['total_users'] ?? count($allUsers);
        } catch (\Exception $e) {
            $allUsers = [];
            $totalUsers = 0;
        }

        
        $perPage    = 5;
        $page       = $request->get('page', 1);
        $collection = collect($allUsers);

        $currentPageItems = $collection
            ->slice(($page - 1) * $perPage, $perPage)
            ->values();

        $paginator = new LengthAwarePaginator(
            $currentPageItems,                  
            $collection->count(),               
            $perPage,                          
            $page,                              
            [
                'path'  => $request->url(),    
                'query' => $request->query(),   
            ]
        );

        
        return view('awa.pages.users', [
            'users' => $paginator,
            'totalUsers' => $totalUsers,
        ]);
    }


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

        $client = new Client([
            'base_uri' => config('services.admin_api.base_url'),
            'timeout'  => 5,
        ]);

        try {
            $response = $client->post('/block_user_admin', [
                'form_params' => [
                    'email' => $request->email,
                ],
            ]);

            $body = json_decode($response->getBody(), true);

            if (isset($body['status']) && $body['status'] === 0) {
                return redirect()
                    ->route('admin.users')
                    ->with('success', 'User blocked successfully.');
            }

            return redirect()
                ->route('admin.users')
                ->with('error', $body['message'] ?? 'Failed to delete user.');

        } catch (\Exception $e) {
            return redirect()
                ->route('admin.users')
                ->with('error', 'Deletion service unavailable.');
        }
    }


    public function blocked(Request $request)
    {
        $client = new Client([
            'base_uri' => config('services.admin_api.base_url'),
            'timeout'  => 5,
        ]);

        try {
            $response = $client->get('/list_blocked_users_admin');
            $body     = json_decode($response->getBody(), true);
            $emails   = $body['blocked_emails'] ?? [];
        } catch (\Exception $e) {
            return back()->with('error', 'Unable to fetch blocked users.');
        }

        $allUsers = array_map(function (string $email) {
            return [
                'email' => $email,
                'name'  => ucfirst(explode('@', $email)[0]),
            ];
        }, $emails);


        
        
        $perPage = 5;
        $page    = $request->get('page', 1);
        $total   = count($allUsers);

        
        $offset = ($page - 1) * $perPage;
        $items  = array_slice($allUsers, $offset, $perPage);

        $paginator = new LengthAwarePaginator(
            $items,
            $total,
            $perPage,
            $page,
            [
                'path'  => $request->url(),
                'query' => $request->query(),
            ]
        );

        return view('awa.pages.users-blocked', [
            'users' => $paginator,
        ]);
    }



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

        $client = new Client([
            'base_uri' => config('services.admin_api.base_url'),
            'timeout'  => 5,
        ]);

       
     try {
            $response = $client->post('/unblock_user_admin', [
                'form_params' => [
                    'blocked_email' => $data['email'],
                ],
            ]);
            $body = json_decode($response->getBody(), true);

            if (isset($body['status']) && $body['status'] === 0) {
                return redirect()
                    ->route('admin.users.blocked')
                    ->with('success', $body['message']);
            }

            return redirect()
                ->route('admin.users.blocked')
                ->with('error', $body['message'] ?? 'Failed to unblock user.');

        } catch (\Exception $e) {
            return redirect()
                ->route('admin.users.blocked')
                ->with('error', 'Unblock service unavailable.');
        }
    }
    
    
}
