<?php

namespace App\Http\Controllers;

use App\Jobs\BatchPopChangeJob;
use App\Models\Client;
use App\Models\Pop;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MultipleCustomerPopChangeController extends Controller
{
    public function multipleCustomerPopChange(Request $request)
    {
        if(!Auth::user()->hasAnyRole(['Admin', 'Accounts Executive'])) {
            return response()->json([
                'success' => false,
                'message' => 'You are not authorized to perform this action'
            ], 400);
        }
        if (empty($request->ids) || count($request->ids) <= 0) {
            return response()->json([
                'success' => false,
                'message' => 'Please select at least one customer'
            ], 400);
        }

        if (!$request->pop_id) {
            return response()->json([
                'success' => false,
                'message' => 'Please select a POP'
            ], 400);
        }

        // Validate POP exists and user has access
        $newPop = Pop::find($request->pop_id);
        if (!$newPop) {
            return response()->json([
                'success' => false,
                'message' => 'Selected POP not found'
            ], 400);
        }

        // Check if user has access to the new POP
        $userPops = userPops()->pluck('id')->toArray();
        if (!in_array($request->pop_id, $userPops)) {
            return response()->json([
                'success' => false,
                'message' => 'You do not have permission to assign clients to this POP'
            ], 403);
        }

        $authUserId = Auth::user()->id;
        $count = 0;

        // Process clients in chunks to avoid memory issues
        Client::with('pop', 'pop.nas', 'clientsinfo')
            ->whereIn('id', $request->ids)
            ->chunk(100, function ($clients) use ($request, $authUserId, &$count) {
                BatchPopChangeJob::dispatch($clients, $request->pop_id, $authUserId);
                $count += $clients->count();
            });

        return response()->json([
            'success' => true,
            'message' => $count . ' client(s) POP change request is in processing queue'
        ]);
    }
}

