<?php

namespace App\Models\Mobiangra;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class MobiangraHorarioGrade extends Model
{
    protected $table = 'mobiangra_horarios_grades';

    protected $fillable = ['secao_id', 'periodo', 'label', 'horarios', 'ordem'];

    protected $casts = ['horarios' => 'array'];

    public const PERIODOS = [
        'seg_sex'     => 'SEGUNDA A SEXTA',
        'sabado'      => 'SÁBADO',
        'dom_feriado' => 'DOMINGO / FERIADO',
    ];

    /** @return BelongsTo<MobiangraHorarioSecao, MobiangraHorarioGrade> */
    public function secao(): BelongsTo
    {
        return $this->belongsTo(MobiangraHorarioSecao::class, 'secao_id');
    }

    public function getLabelPeriodoAttribute(): string
    {
        return self::PERIODOS[$this->periodo] ?? $this->label;
    }

    /**
     * Normaliza horários armazenados (string legada ou {h, c}).
     *
     * @return list<array{h: string, c: string|null}>
     */
    public function horariosItens(): array
    {
        return collect($this->horarios ?? [])
            ->map(fn ($item) => self::normalizarHorarioItem($item))
            ->filter(fn (array $item) => $item['h'] !== '')
            ->values()
            ->all();
    }

    /**
     * @return array{h: string, c: string|null}
     */
    public static function normalizarHorarioItem(mixed $item): array
    {
        if (is_string($item)) {
            return ['h' => self::formatarHora($item), 'c' => null];
        }

        if (is_array($item)) {
            $hora = (string) ($item['h'] ?? $item['hora'] ?? '');
            $cor  = $item['c'] ?? $item['cor'] ?? null;

            return [
                'h' => self::formatarHora($hora),
                'c' => $cor ? (string) $cor : null,
            ];
        }

        return ['h' => '', 'c' => null];
    }

    public static function formatarHora(string $hora): string
    {
        if (preg_match('/^(\d{1,2}):(\d{2})$/', trim($hora), $matches)) {
            return sprintf('%02d:%s', (int) $matches[1], $matches[2]);
        }

        return trim($hora);
    }

    public function horariosComoTexto(): string
    {
        return collect($this->horariosItens())->pluck('h')->implode(', ');
    }

    /** Retorna horários em linhas (4 por linha, como na grade da planilha) */
    public function emLinhas(int $cols = 4): array
    {
        return array_chunk($this->horariosItens(), $cols);
    }

    /** @deprecated Use emLinhas() */
    public function emColunas(int $cols = 4): array
    {
        return $this->emLinhas($cols);
    }
}
