<?php
namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;use App\Models\Concerns\BelongsToCompany;


class BusinessHour extends Model
{
    use BelongsToCompany;
    protected $fillable = ['day_of_week','active','opens_at','closes_at'];
    protected function casts(): array { return ['active' => 'boolean']; }

    public static array $days = [
        0 => 'Domingo', 1 => 'Lunes', 2 => 'Martes',
        3 => 'Miércoles', 4 => 'Jueves', 5 => 'Viernes', 6 => 'Sábado'
    ];

    public function getDayNameAttribute(): string {
        return self::$days[$this->day_of_week] ?? '';
    }

    // ¿Estamos en horario laboral ahora?
    public static function isBusinessHours(?Carbon $time = null): bool
    {
        $time ??= now();
        $dow  = (int) $time->format('w'); // 0=Dom
        $bh   = static::where('day_of_week', $dow)->where('active', true)->first();
        if (!$bh) return false;
        $current = $time->format('H:i:s');
        return $current >= $bh->opens_at && $current <= $bh->closes_at;
    }

    // Próximo momento de horario laboral
    public static function nextBusinessOpen(): Carbon
    {
        $time = now();
        for ($i = 0; $i < 8; $i++) {
            $check = $time->copy()->addDays($i);
            $dow   = (int) $check->format('w');
            $bh    = static::where('day_of_week', $dow)->where('active', true)->first();
            if ($bh) {
                return Carbon::parse($check->format('Y-m-d') . ' ' . $bh->opens_at);
            }
        }
        return $time->addDay(); // fallback
    }
}
