<?php

namespace App\Modules\Company\Rating;

use App\Models\CompanyRating as Rating;
use App\Traits\ValidatorTraits;
use App\Traits\UserTraits;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\CompanyRating as RatingModel;
use App\Models\CompanyRatingAggregate;
use App\Http\Resources\Company\Search\CompanyReview;
use App\Events\Company\Rating\ProcessAggregateCompanyRatingEvent;


class CompanyRating {

    use ValidatorTraits, UserTraits;

    public function fetchCompanyRatingAsLoaner($id){
        $rating = CompanyRatingAggregate::where('company_id', $id)
        ->where('type', 'loaning')
        ->first();

        if($rating){
            return response($rating);
        }

        return response(['errors' => 'No Company Rating Yet.']);
    }

    public function fetchCompanyReviewsAsLoaner($id){
        return CompanyReview::collection(
            RatingModel::select(
                'company_ratings.id',
                'company_ratings.company_id',
                'company_ratings.message',
                'company_ratings.rate',
                'company_ratings.rated_by',
                'company_ratings.created_at',
                DB::raw('CONCAT(workers.first_name, " ", workers.last_name) as rater_name'),
            )
            ->join('workers', 'workers.id', 'company_ratings.rated_by')
            ->where('type', 'loaning')
            ->where('company_id', $id)
            ->paginate(5)
        )->response()->setStatusCode(201);
    }
    
    public function rateCompany($payload){

        $rules = array(
            'loan_approved_history_id' => 'required',
            'company_id' => 'required',
            'rate' => 'required',
            'type' => 'required|in:borrowing,loaning',
        );

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

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

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

        $createCompanyRateTransaction = Rating::create($wokerRateData);

        event(new ProcessAggregateCompanyRatingEvent((object)$createCompanyRateTransaction)); 

        if ($createCompanyRateTransaction) {
            return response(['success' => 'Company Succesfully Rated.']);
        } else {
            return response(['errors' => 'Something went wrong in rating the company.']);
        }
    }
}
