<?php

namespace App\Models;

use CodeIgniter\Model;

class AscPeriodModel extends Model
{
    protected $table            = 'asc_periods';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = [
        'import_id', 'period_number', 'name', 'start_time', 'end_time'
    ];

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    // Ambil semua periode milik satu import, urut dari jam pertama
    public function getByImport($importId)
    {
        return $this->where('import_id', $importId)
                    ->orderBy('period_number', 'ASC')
                    ->findAll();
    }

    // Ambil sebagai lookup array: period_number => [start_time, end_time]
    // Berguna saat parse XML dan saat render grid
    public function getLookup($importId)
    {
        $rows   = $this->getByImport($importId);
        $lookup = [];

        foreach ($rows as $row) {
            $lookup[$row['period_number']] = [
                'start_time' => $row['start_time'],
                'end_time'   => $row['end_time'],
                'name'       => $row['name'],
            ];
        }

        return $lookup;
    }

    // Hapus semua periode milik satu import (untuk re-import)
    public function deleteByImport($importId)
    {
        return $this->where('import_id', $importId)->delete();
    }
}