<?php

namespace App\Actions\Attribution\Attribution;

use Illuminate\Support\Facades\Auth;
use App\Models\Attribution\Attribution;



class SetAttribution
{

    /**
     * @param mixed $equipment
     * @param mixed $date
     * @param mixed $serviceID
     * 
     * @return void
     */
    public function setAttr($equipment, $date, $serviceID): void
    {   
        // Get establishement ID
        $etsID = (isset(Auth::user()->establishment_id) && !empty(Auth::user()->establishment_id)) ? (int) Auth::user()->establishment_id : 0;

        //  Allocation table
        $updateData = [
            'equipment_id'      => $equipment->id,
            'service_id'        => $serviceID,
            'establishment_id'  => $etsID,
            'attr_date'         => $date,
            'active'            => 1,
            'created_by'        => Auth::id(),
            'updated_by'        => !empty($data['rowID']) ? Auth::id() : null,
        ];
        // Assign a piece of equipment to a service
        // $attrID = $equipment->attribution->id ?? 0;
        $equipments = $equipment->attribution->where('ownership', 0)->first();
        // dd($equipments);
        $attrID = $equipments->id ?? 0;
        // Set condition to create new assignment or update existing assignment
        // Attribution::updateOrCreate(['id' => $attrID], $updateData);
        if (empty($attrID) || (int) $equipments->service_id != (int) $serviceID) {
            // Remove existing assignments
            if(!empty($equipments->service_id)) {
                $equipments->update([
                    'ownership'         => 1,
                    'created_by'        => Auth::id(),
                    'updated_by'        => !empty($data['rowID']) ? Auth::id() : null,
                ]);  
            }
            // Assign new equipment
            Attribution::create($updateData);
        } // end if
        else {
            // Update existing assignments
            Attribution::updateOrCreate(['id' => $attrID], [
                'attr_date'         => $date,
                'active'            => 1,
                'created_by'        => Auth::id(),
                'updated_by'        => !empty($data['rowID']) ? Auth::id() : null,
            ]);
        }
    }
}
