<?php

namespace App\Traits;

use App\Models\Setting;
use Carbon\Carbon;

trait HasLockCheck
{
    /**
     * Check if the given date is on or before the accounting lock date.
     *
     * @param mixed $date
     * @return bool
     */
    public function isDateLocked($date)
    {
        $settings = Setting::getGroup('general');
        $lockDate = $settings['accounting_lock_date'] ?? null;

        if (!$lockDate) {
            return false;
        }

        $transactionDate = Carbon::parse($date);
        $lockDate = Carbon::parse($lockDate);

        return $transactionDate->lte($lockDate);
    }

    /**
     * Validate lock date and return redirect if locked.
     */
    public function validateLockDate($date)
    {
        if ($this->isDateLocked($date)) {
            return back()->with('error', __('This date is locked due to monthly closing. Please choose a date after ') . config('app.settings.general.accounting_lock_date'))->withInput();
        }
        return null;
    }
}
