<?php

namespace App\Traits;

use App\Models\Application\Guarantees;
use App\Models\Application\RequestEndorsement;
use App\Models\Application\RequestGuarantee;
use App\Models\Application\RequestLoan;
use App\Models\Application\RequestLoanDetails;
use Exception;

trait RequestLoanTrait
{
    use UserLoggedTrait;

    protected function addRequestLoanDetails(RequestLoan $loan, $details)
    {
        try {
            RequestLoanDetails::create([
                'fk_loan_request' => $loan->id,
                'renewpayment' => $details->renewpayment,
                'paperworkpayment' => $details->paperworkpayment,
                'otherpayment' => $details->otherpayment,
                'interesrate' => $details->interesrate ?? 0,
                'fk_usercreator' => $this->user()->id
            ]);

            return true;
        } catch (Exception $ex) {
            return false;
        }
    }

    protected function addRequestLoanEndorsements(RequestLoan $loan, $endorsements)
    {
        try {
            foreach ($endorsements as $endorsement) {
                RequestEndorsement::create([
                    'fk_loan_request' => $loan->id,
                    'fk_endorsement_request' => $endorsement->id,
                    'fk_endrosement' => $endorsement->fk_client,
                    'fk_usercreator' => $this->user()->id
                ]);
            }

            return true;
        } catch (Exception $ex) {
            return false;
        }
    }

    protected function addRequestLoanGuarantees(RequestLoan $loan, $guarantees)
    {
        try {
            foreach ($guarantees as $guarantee) {
                RequestGuarantee::create([
                    'fk_loan_request' => $loan->id,
                    'fk_client_request' => $guarantee->fk_client_request,
                    'fk_client' => $guarantee->fk_client,
                    'fk_model' => $guarantee->fk_model,
                    'description' => trim(mb_strtoupper($guarantee->description, 'UTF-8')),
                    'serialnumber' => trim(mb_strtoupper($guarantee->serialnumber, 'UTF-8')),
                    'fk_usercreator' => $this->user()->id,
                ]);
            }

            return true;
        } catch (Exception $ex) {
            return false;
        }
    }
}
