<?php

namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Customer;
use Illuminate\Http\Request;
use App\Models\Users;

class CustomerAssignmentController extends Controller
{
    public function assignCustomersToUsers()
    {
        $users = User::all();
        $customers = Customer::all();
        $users=Users::all();

        $numUsers = $users->count();
        if ($numUsers === 0) {
            return response()->json(['success' => false, 'message' => 'No users found.'], 404);
        }

        $numCustomers = $customers->count();
        $customersPerUser = ceil($numCustomers / $numUsers);

        $userIndex = 0;

        foreach ($customers as $customer) 
        {
            
            $user = $users[$userIndex];

            $customer->user_id = $user->id;
            //$customer->admin_id=$users->id;
            $customer->save();

            $userIndex = ($userIndex + 1) % $numUsers;
        }

        return response()->json(['success' => true, 'message' => 'Customers successfully assigned to users.']);
    }

    // Assign customers to selected users
    public function assignCustomersToSelectedUsers(Request $request)
    {
        
        $selectedUserIds = $request->input('user_ids');

        if (empty($selectedUserIds) || !is_array($selectedUserIds)) {
            return response()->json(['success' => false, 'message' => 'Invalid input. Please provide a list of user IDs.'], 400);
        }

        $users = User::whereIn('id', $selectedUserIds)->get();
        $numUsers = $users->count();

        if ($numUsers === 0) {
            return response()->json(['success' => false, 'message' => 'No users found with the provided IDs.'], 404);
        }

        $customers = Customer::all();
        $numCustomers = $customers->count();

        $customersPerUser = ceil($numCustomers / $numUsers);

        $userIndex = 0;

        foreach ($customers as $customer) 
        {

            $user = $users[$userIndex];

            $customer->user_id = $user->id;
            //$customer->admin_id=$users->id;
            $customer->save();

            $userIndex = ($userIndex + 1) % $numUsers;
        }


        return response()->json(['success' => true, 'message' => 'Customers successfully assigned to selected users.']);
    }

}
