<?php

namespace App\Modules\Company\Loan\Billings;

use App\Http\Resources\Company\LoanBillingClientInvoiceDetails as LoanBillingClientInvoiceDetailsResource;
use App\Http\Resources\Company\LoanBillingClientInvoiceHistory as LoanBillingClientInvoiceHistoryResource;
use App\Models\InboundHistories;
use App\Models\LoanBorrowList;
use App\Traits\SortingTraits;
use App\Traits\UserTraits;

class InvoiceDetails
{
    use SortingTraits, UserTraits;

    public function getInvoiceDetailsData($id)
    {
        $company_id = $this->getCurrentUser()->company_id;
        return LoanBillingClientInvoiceDetailsResource::collection(
            LoanBorrowList::select(
                'loan_borrow_lists.id',
                'loan_borrow_lists.invoice_no',
                'loan_borrow_lists.rate',
                'loan_borrow_lists.original_rate',
                'loan_borrow_lists.date_from',
                'loan_borrow_lists.date_to',
                'loan_borrow_lists.loaner_company_id',
                'loan_borrow_lists.borrower_company_id',
                'workers.id as worker_id',
                'workers.first_name',
                'workers.last_name',
                'workers.worker_id as worker_company_id',
                'IBR.days',
                'IBR.other_expense',
                'IBR.notes',
                'IBR.client_request')
                ->join('inbound_billing_requests AS IBR', 'IBR.loan_borrow_lists_id', '=', 'loan_borrow_lists.id')
                ->join('workers', 'workers.id', '=', 'loan_borrow_lists.worker_id')
                ->where('loan_borrow_lists.status', '!=', 'Approved')
                ->where('loan_borrow_lists.loaner_company_id', $company_id)
                ->where('loan_borrow_lists.id', $id)
                ->limit(1)->get()
        )->response()->setStatusCode(201);
    }

    public function getInvoiceHistoryData($payload, $id)
    {
        // sorting
        $sortField = $this->sortField($payload, 'created_at'); // created_at = default column to search
        $sortOrder = $this->sortOrder($payload, 'desc');

        return LoanBillingClientInvoiceHistoryResource::collection(
            InboundHistories::select(
                'inbound_histories.id',
                'inbound_histories.days',
                'inbound_histories.other_expense',
                'inbound_histories.notes',
                'inbound_histories.client_request',
                'inbound_histories.created_at')
                ->where('inbound_histories.inbound_billing_requests_id', $id)
                ->orderBy($sortField, $sortOrder)
                ->paginate(2)
        )->response()->setStatusCode(201);
    }
}
