<?php

namespace App\Console\Commands;

use Exception;
use Carbon\Carbon;
use App\Traits\PaymentTrait;
use Illuminate\Console\Command;
use App\Models\Application\Status;
use App\Models\Application\Payment;
use Illuminate\Support\Facades\Log;

class setPaymentsAsOnTime extends Command
{
    use PaymentTrait;

    protected $signature = 'command:set-payments-as-on-time';
    protected $description = 'Set payments as on time';

    private $startDate = null, $endDate = null, $onTimeStatus = null;

    public function handle()
    {
        try {
            $this->startDate = now()->previous(Carbon::SATURDAY)->subDays(2)->format('Y-m-d');
            $this->endDate = now()->previous(Carbon::SATURDAY)->addDays(4)->format('Y-m-d');

            $this->onTimeStatus = Status::where('statusname', 'PUNTUAL')->first();

            $payments = Payment::where([
                ['is_active', true]
            ])->whereBetween('duedate', [$this->startDate, $this->endDate])
                ->whereNull('payment')
                ->whereHas('loan', fn($loans) => $loans->where('is_active', true))
                ->get();

            foreach ($payments as $payment) {
                $payment->payment = $payment->loan->weeklypayment;
                $payment->paymentdate = Carbon::createFromTimestamp($payment->duedate)->format('Y-m-d');
                $payment->fk_status = $this->onTimeStatus->id;
                $payment->update();

                $this->determineLoanStatus($payment);
                $this->determineClientStatus($payment->loan);
                $this->determineEndorsementStatus($payment->loan);
            }
        } catch (Exception $ex) {
            Log::error('message: ' . $ex->getMessage() . ' file: ' . $ex->getFile() . ' line: ' . $ex->getLine());
        }
    }
}
