<?php

namespace Modules\MedAccounting\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * An accounting period (SIFA P7-T2). A CLOSED period rejects any journal entry
 * dated inside its range (the backdated-posting lock). Periods are opt-in: when no
 * period covers a date, posting is allowed.
 */
class MedaccPeriod extends Model
{
    protected $table = 'medacc_periods';

    protected $guarded = ['id'];

    protected $casts = [
        'start_date' => 'date',
        'end_date'   => 'date',
        'closed_at'  => 'datetime',
    ];

    public const STATUSES = ['open', 'closed'];

    public function scopeForBusiness($query, $businessId)
    {
        return $query->where('business_id', $businessId);
    }

    /**
     * The (first) period covering a given date for a business, or null when none
     * is defined for that date.
     */
    public static function covering(int $businessId, string $date): ?self
    {
        return static::where('business_id', $businessId)
            ->whereDate('start_date', '<=', $date)
            ->whereDate('end_date', '>=', $date)
            ->orderBy('start_date')
            ->first();
    }

    /**
     * True when posting to $date is blocked by a CLOSED period. Opt-in: no
     * covering period ⇒ not locked.
     */
    public static function isLocked(int $businessId, string $date): bool
    {
        $period = static::covering($businessId, $date);

        return $period !== null && $period->status === 'closed';
    }
}
