<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\CompanyUser;
use App\Models\WorkAreaLists;
use App\Models\CompanyRating;
use App\Models\LoanBorrowList as LoanBorrowListModel;
use Illuminate\Support\Facades\Auth;

class LoanBorrowList extends Model
{
    use HasFactory;
    protected $table = 'loan_borrow_lists';
    protected $fillable = [
        'invoice_no',
        'loaner_company_id',
        'borrower_company_id',
        'worker_id',
        'original_rate',
        'rate',
        'tax',
        'duration',
        'date_from',
        'date_to',
        'status',
    ];

    public function work_area_lists()
    {
        return $this->hasMany(WorkAreaLists::class, 'worker_id', 'worker_id')
            ->join('work_areas', 'work_areas.id', '=', 'work_area_lists.work_area_id')
            ->where('work_area_lists.worker_type', 'worker');
    }

    public function inbound_billing_requests()
    {
        $id = Auth::user()->id;
        $company_user = CompanyUser::where('worker_id', $id)->get();
        $company_id = $company_user[0]->company_id;

        return $this->hasMany(LoanBorrowListModel::class, 'loaner_company_id', 'id')
            ->join('inbound_billing_requests AS IBR', 'IBR.loan_borrow_lists_id','=', 'loan_borrow_lists.id')
            ->where('borrower_company_id', $company_id)
            ->where('loan_borrow_lists.status', 'Approved');
    }

    public function ratingAsBorrower(){
        return $this->hasOne(CompanyRating::class, 'loan_approved_history_id', 'id')
            ->where('type', '=', 'borrowing');
    }

    public function ratingAsLoaner(){
        return $this->hasOne(CompanyRating::class, 'loan_approved_history_id', 'id')
            ->where('type', '=', 'loaning');
    }

}
