<?php

namespace App\Models;

use CodeIgniter\Model;

class LearningDeviceModulModel extends Model
{
    protected $table            = 'learning_device_moduls';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = [
        'learning_device_id', 'tp_id', 'topic',
        'identity', 'core_components', 'differentiation',
        'assessment', 'follow_up', 'reflection', 'character_integration',
        'chapter_index',
        // --- Kolom baru field-by-field ---
        'kompetensi_awal', 'sarana_prasarana', 'target_peserta_didik',
        'model_pembelajaran', 'pemahaman_bermakna', 'pertanyaan_pemantik',
        'materi_esensial', 'skenario_pembelajaran',
        'asesmen_diagnostik', 'asesmen_formatif', 'asesmen_sumatif',
        'pengayaan', 'remedial', 'lkpd', 'glosarium', 'daftar_pustaka',
        'jumlah_pertemuan', 'field_status',
    ];

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

    // Decode JSON fields otomatis (untuk field JSON lama)
    protected $afterFind = ['decodeJsonFields'];

    protected function decodeJsonFields(array $data)
    {
        if (empty($data['data'])) {
            return $data;
        }

        $fields = ['identity', 'core_components', 'differentiation', 'assessment', 'follow_up', 'reflection', 'character_integration'];

        // Jika single result (first())
        if (isset($data['data']['id'])) {
            foreach ($fields as $field) {
                if (isset($data['data'][$field]) && is_string($data['data'][$field])) {
                    $data['data'][$field] = json_decode($data['data'][$field], true) ?? [];
                }
            }
        } else {
            // Jika multi result (findAll())
            foreach ($data['data'] as &$row) {
                foreach ($fields as $field) {
                    if (isset($row[$field]) && is_string($row[$field])) {
                        $row[$field] = json_decode($row[$field], true) ?? [];
                    }
                }
            }
        }

        return $data;
    }

    /**
     * Ambil atau buat record modul untuk TP tertentu
     */
    public function firstOrCreate(int $deviceId, int $tpId): array
    {
        $existing = $this->where('learning_device_id', $deviceId)
                         ->where('tp_id', $tpId)
                         ->first();
        if ($existing) {
            return $existing;
        }

        $this->insert([
            'learning_device_id' => $deviceId,
            'tp_id'              => $tpId,
            'topic'              => '',
            'field_status'       => '{}',
        ]);

        return $this->where('learning_device_id', $deviceId)
                    ->where('tp_id', $tpId)
                    ->first();
    }

    /**
     * Ambil atau buat record modul untuk chapter tertentu
     */
    public function firstOrCreateByChapter(int $deviceId, int $chapterIndex): array
    {
        $existing = $this->where('learning_device_id', $deviceId)
                         ->where('chapter_index', $chapterIndex)
                         ->first();
        if ($existing) {
            return $existing;
        }

        $this->insert([
            'learning_device_id' => $deviceId,
            'chapter_index'      => $chapterIndex,
            'topic'              => '',
            'field_status'       => '{}',
            // JSON fields (NOT NULL constraint)
            'identity'              => '{}',
            'core_components'       => '{}',
            'differentiation'       => '{}',
            'assessment'            => '{}',
            'follow_up'             => '{}',
            'reflection'            => '{}',
            'character_integration' => '{}',
        ]);

        return $this->where('learning_device_id', $deviceId)
                    ->where('chapter_index', $chapterIndex)
                    ->first();
    }
}
