<?php
namespace App\Classes;


use App\Models\Token;
use App\Models\TokenAssign;
use App\Jobs\SendSmsJob;
use App\Models\Employee;
use Illuminate\Http\Request;
use App\Classes\Notification;
use Illuminate\Support\Facades\DB;


class TokenClass{

    public function saveToken(Request $request){
        $token = new Token();
        $token->tokenCategory = $request->tokenCategory;
        $token->tokenCode = $request->tokenCode;
        $token->description = $request->description;
        $token->reportedBy = $request->reportedBy;
        $token->reporterContact = $request->reporterContact;
        $token->clientId = $request->clientId;
        $token->token_type = $request->token_type;
        $token->onu_status = $request->onu_status;
        $token->onu_power = $request->onu_status === 'online' ? ($request->onu_power ?? null) : null;
        $token->createdBy = auth()->user()->id;
        if (checkSettings('token_source') == 'enable'){
            if (auth()->user()->hasPermissionTo('default_source_crm')){
                $token->token_source = 'CRM';
            } else{
                $token->token_source = $request->token_source ?? null;
            }
        }
        $token->save();

        $employeeIds = array_filter((array) $request->employee);
        if (!empty($employeeIds)) {
            $token->assignToken = $employeeIds[0];
            $token->assignUserId = auth()->user()->id;
            $token->assign_time = now();
            $token->save();

            foreach ($employeeIds as $employeeId) {
                TokenAssign::create([
                    'token_id' => $token->id,
                    'employee_id' => $employeeId,
                ]);
            }
        }
        $token->token = $token->id + 1000000;
        $token->save();

        return $token;

    }
}


