<?php

namespace App\Observers;

use App\Models\Loan;
use App\Models\Penalty;
use Carbon\Carbon;

class LoanObserver {

    /**
     * Handle events after all transactions are committed.
     *
     * @var bool
     */
    public $afterCommit = true;

    /**
     * Handle the Loan "updated" event.
     *
     * @param  \App\Models\Loan  $loan
     * @return void
     */
    public function updated(Loan $loan) {
        if ($loan->wasChanged('end') && $loan->end !== null) {
            $days = (Carbon::parse($loan->start))
                    ->diffInDays(Carbon::parse($loan->end));

            if ($days > 15) {
                $lastUserPenalty = $this->getLastUserPenalty($loan->user_id, $loan);
                $extraDays = $days - 15;
                $finalDate = null;
                
                if ($lastUserPenalty) {
                    $finalDate = Carbon::parse($lastUserPenalty->end)
                            ->addDays($extraDays);
                } else {
                    $finalDate = Carbon::parse($loan->end)
                            ->addDays($extraDays);
                }
                
                Penalty::create([
                    'user_id' => $loan->user_id,
                    'end' => $finalDate->format('Y-m-d')
                ]);
                
                return redirect()->route('loans.index')
                        ->with('danger', 'A new penalty has been added.');
            }
        }
    }

    /**
     * Get last pending penalty for the user.
     * 
     * @param number $userId
     * @param \App\Models\Loan $loan
     * @return \App\Models\Penalty
     */
    private function getLastUserPenalty($userId, Loan $loan) {
        return Penalty::where('user_id', $userId)
                        ->where('end', '>', Carbon::parse($loan->end)
                                ->format('Y-m-d'))
                        ->latest()
                        ->first();
    }

}
