<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class IpWhitelistController extends Controller
{
    /**
     * Display the IP whitelist management page
     */
    public function index(): View
    {
        $user = Auth::user();
        
        $whitelistedIPs = collect();
        
        if (!empty($user->whitelist_ip)) {
            $decoded = json_decode($user->whitelist_ip, true);
            
            if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                $whitelistedIPs = collect($decoded);
            } else {
                $whitelistedIPs = collect(explode(',', $user->whitelist_ip))
                    ->map(fn($ip) => trim($ip))
                    ->filter();
            }
        }

        return view('pages.user.api.ip-whitelist', compact('whitelistedIPs'));
    }

    /**
     * Add an IP address to the whitelist
     */
    public function store(Request $request): RedirectResponse
    {
        $validator = Validator::make($request->all(), [
            'ip_address' => [
                'required',
                'ip',
                function ($attribute, $value, $fail) {
                    $user = Auth::user();
                    $existingIPs = $this->getWhitelistedIPs($user);
                    
                    if ($existingIPs->contains($value)) {
                        $fail('This IP address is already whitelisted.');
                    }
                },
            ],
        ]);

        if ($validator->fails()) {
            return redirect()
                ->route('user.ip-whitelist.index')
                ->withErrors($validator)
                ->withInput();
        }

        $user = Auth::user();
        $whitelistedIPs = $this->getWhitelistedIPs($user);
        
        $whitelistedIPs->push($request->ip_address);
        
        $user->update([
            'whitelist_ip' => json_encode($whitelistedIPs->values()->toArray())
        ]);

        return redirect()
            ->route('user.ip-whitelist.index')
            ->with('success', 'IP address added to whitelist successfully!');
    }

    /**
     * Remove an IP address from the whitelist
     */
    public function destroy(Request $request): RedirectResponse
    {
        $request->validate([
            'ip_address' => 'required|ip',
        ]);

        $user = Auth::user();
        $whitelistedIPs = $this->getWhitelistedIPs($user);
        
        $whitelistedIPs = $whitelistedIPs->reject(function ($ip) use ($request) {
            return $ip === $request->ip_address;
        });
        
        $user->update([
            'whitelist_ip' => json_encode($whitelistedIPs->values()->toArray())
        ]);

        return redirect()
            ->route('user.ip-whitelist.index')
            ->with('success', 'IP address removed from whitelist successfully!');
    }

    /**
     * Clear all whitelisted IPs
     */
    public function clear(): RedirectResponse
    {
        $user = Auth::user();
        
        $user->update([
            'whitelist_ip' => json_encode([])
        ]);

        return redirect()
            ->route('user.ip-whitelist.index')
            ->with('success', 'All IP addresses have been removed from whitelist!');
    }

    /**
     * Helper method to get whitelisted IPs as collection
     */
    private function getWhitelistedIPs($user)
    {
        if (empty($user->whitelist_ip)) {
            return collect();
        }

        $decoded = json_decode($user->whitelist_ip, true);
        
        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
            return collect($decoded);
        }

        return collect(explode(',', $user->whitelist_ip))
            ->map(fn($ip) => trim($ip))
            ->filter();
    }
}
