<?php

namespace App\Modules\Company\Borrow\Requests;

use App\Models\BorrowApproved;
use App\Models\WorkerRating;
use App\Traits\ValidatorTraits;
use App\Traits\UserTraits;
use Illuminate\Support\Facades\Auth;
use App\Events\Company\Borrow\AggregateWorkerRatingEvent;
use App\Http\Resources\Company\WorkerReview as WorkerReviewResource;

class Rating
{
    use ValidatorTraits, UserTraits;

    public function getDetails($id)
    {
        //id = loan approved id / borrow approved id
        return BorrowApproved::select(
            'borrow_approved_histories.id',
            'borrow_approved_histories.worker_id',
            'workers.worker_id as company_worker_id',
        )
        ->with('workerRate')
        ->join('workers', 'workers.id', 'borrow_approved_histories.worker_id')
        ->where('borrow_approved_histories.id', $id)
        ->first();
    }

    public function rateWorker($payload){
        $rules = array(
            'id' => 'required|unique:worker_ratings,loan_approved_history_id',
            'worker_id' => 'required|max:50',
            'rate' => 'required|max:191',
        );

        $validate = $this->validateRequest($payload, $rules);
        if ($validate) {
            return $validate;
        }   

        $companyID = $this->getCurrentUser()->company_id;
        $userID = Auth::user()->id;

        $wokerRateData = array(
            'loan_approved_history_id' => $payload->id,
            'worker_id' => $payload->worker_id,
            'company_id' => $companyID,
            'rated_by' => $userID,
            'rate' => $payload->rate,
            'type' => 'borrowed',
            'message' => $payload->comment,
        );

        $createWorkerRateTransaction = WorkerRating::create($wokerRateData);

        event(new AggregateWorkerRatingEvent((object)$createWorkerRateTransaction)); 


        if ($createWorkerRateTransaction) {
            return response(['success' => 'Worker Succesfully Rated.']);
        } else {
            return response(['error' => 'Something went wrong in rating the worker.']);
        }
    }

    public function getReviews($id){

        return WorkerReviewResource::collection(
            WorkerRating::select(
                'worker_ratings.id',
                'worker_ratings.worker_id',
                'worker_ratings.message',
                'worker_ratings.rate',
                'worker_ratings.created_at',
                'companies.name as company_name',
            )
            ->join('companies', 'companies.id', 'worker_ratings.company_id')
            ->where('worker_id', $id)
            ->paginate(5)
        )->response()->setStatusCode(201);
    }
    
}
