<?php

namespace App\Models;

use CodeIgniter\Model;

class InspectionTemplateModel extends Model
{
    protected $table = 'inspection_templates';
    protected $primaryKey = 'id';
    protected $returnType = 'array';
    protected $useAutoIncrement = true;
    protected $protectFields = true;
    protected $allowedFields = [
        'code', 'name', 'form_code', 'revision',
        'layout_mode', 'descripcion', 'activo',
    ];
    protected $useTimestamps = true;

    public function findWithItems(int $id): ?array
    {
        $template = $this->find($id);
        if ($template === null) {
            return null;
        }

        $sections = (new InspectionTemplateSectionModel())
            ->where('template_id', $id)
            ->orderBy('orden')->orderBy('id')->findAll();

        $items = (new InspectionTemplateItemModel())
            ->where('template_id', $id)
            ->orderBy('orden')->orderBy('id')->findAll();

        $bySection = ['_unsec' => []];
        foreach ($sections as $s) {
            $bySection[$s['id']] = [];
        }
        foreach ($items as $it) {
            $key = $it['section_id'] ?? '_unsec';
            if (! isset($bySection[$key])) {
                $bySection[$key] = [];
            }
            $bySection[$key][] = $it;
        }

        $template['sections'] = $sections;
        $template['items_by_section'] = $bySection;
        $template['items'] = $items;

        return $template;
    }

    public function filterForPeriodicity(array $template, ?string $periodicity): array
    {
        $periodicity = $this->normalizePeriodicity($periodicity);
        $items = array_values(array_filter($template['items'] ?? [], function (array $item) use ($periodicity): bool {
            return $this->itemAppliesToPeriodicity($item['frecuencia'] ?? null, $periodicity);
        }));

        $bySection = ['_unsec' => []];
        foreach (($template['sections'] ?? []) as $section) {
            $bySection[$section['id']] = [];
        }
        foreach ($items as $item) {
            $key = $item['section_id'] ?? '_unsec';
            if (! isset($bySection[$key])) {
                $bySection[$key] = [];
            }
            $bySection[$key][] = $item;
        }

        $template['items'] = $items;
        $template['items_by_section'] = $bySection;

        return $template;
    }

    public function normalizePeriodicity(?string $periodicity): string
    {
        return in_array($periodicity, ['mensual', 'semestral', 'anual'], true) ? $periodicity : 'mensual';
    }

    public function itemAppliesToPeriodicity(?string $frequency, string $periodicity): bool
    {
        $frequency = strtoupper(trim((string) $frequency));
        if ($frequency === '') {
            return true;
        }
        if ($frequency === 'Q') {
            $frequency = 'S';
        }

        $rank = ['M' => 1, 'S' => 2, 'A' => 3];
        $periodRank = ['mensual' => 1, 'semestral' => 2, 'anual' => 3][$periodicity] ?? 1;

        return isset($rank[$frequency]) && $rank[$frequency] <= $periodRank;
    }

    public function periodicityLabel(?string $periodicity): string
    {
        return [
            'mensual' => 'Mensual',
            'semestral' => 'Semestral',
            'anual' => 'Anual',
        ][$this->normalizePeriodicity($periodicity)] ?? 'Mensual';
    }
}
