<?php

namespace App\Modules\Company\Borrow\Billings;

use App\Http\Resources\Company\BorrowBillingSummary as BorrowBillingSummaryResource;
use App\Models\LoanBorrowList;
use App\Traits\SearchTraits;
use App\Traits\SortingTraits;
use App\Traits\UserTraits;
use Illuminate\Support\Facades\DB;

class Summary
{
    use SearchTraits, SortingTraits, UserTraits;

    public function getData($payload)
    {
        // sorting
        $sortField = $this->sortField($payload, 'workers.first_name'); // workers.name = default column to search
        $sortOrder = $this->sortOrder($payload, 'asc');

        // searching
        $nameSearch = $this->searchField($payload->first_name);

        $companyId = $this->getCurrentUser()->company_id;
        return BorrowBillingSummaryResource::collection(
            LoanBorrowList::select(
                'workers.id',
                'workers.first_name',
                'workers.last_name',
                DB::raw("SUM(inbound_billing_requests.outstanding_balance) as total_outstanding_balance"))
                ->with('inbound_billing_requests:loaner_company_id,loan_borrow_lists.loaner_company_id,loan_borrow_lists.id,rate,other_expense,loaner_company_id,days,date_from,date_to')
                ->selectRaw('COUNT(IF(loan_borrow_lists.status = "Request Modification", 1, NULL)) as request_for_modification')
                ->join('workers', 'workers.id', '=', 'loan_borrow_lists.worker_id')
                ->join('inbound_billing_requests', 'inbound_billing_requests.loan_borrow_lists_id', '=', 'loan_borrow_lists.id')
                ->where('loan_borrow_lists.borrower_company_id', $companyId)
                ->when(!empty($nameSearch), function ($query) use ($nameSearch) {
                    return $query->where(function ($query) use ($nameSearch) {
                        $query->where('workers.first_name', 'LIKE', $nameSearch . '%')
                            ->orWhere('workers.last_name', 'LIKE', $nameSearch . '%')
                            ->orWhere(DB::raw('CONCAT(workers.first_name, " ", workers.last_name)'), 'LIKE', $nameSearch . '%');
                    });
                })
                ->groupBy('loan_borrow_lists.worker_id')
                ->orderBy($sortField, $sortOrder)
                ->paginate(20)
        )->response()->setStatusCode(201);
    }
}
