<?php

namespace App\Models;

use CodeIgniter\Model;

class LearningDeviceModel extends Model
{
    protected $table            = 'learning_devices';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = true;
    protected $allowedFields    = [
        'user_id', 'academic_year_id', 'grade_id', 'school_subject_id',
        'phase', 'school_type', 'cp_content', 'cp_elements',
        'chapters', 'dpl', 'panca_cinta', 'kktp_intervals', 'chapter_cp_map',
        'chapter_dpl', 'chapter_kbc', 'jp_per_week'
    ];

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

    public function __construct()
    {
        parent::__construct();
        // Self-healing: auto add jp_per_week if missing
        $db = \Config\Database::connect();
        if (!$db->fieldExists('jp_per_week', 'learning_devices')) {
            $forge = \Config\Database::forge();
            $forge->addColumn('learning_devices', [
                'jp_per_week' => [
                    'type' => 'INT',
                    'constraint' => 11,
                    'default' => 4,
                    'null' => true,
                ]
            ]);
        }
    }

    // Ambil data detail perangkat beserta relasinya
    public function getDetail(int $id, int $userId = null)
    {
        $query = $this->select('
                learning_devices.*, 
                grades.name as grade_name, 
                school_subjects.name as subject_name,
                academic_years.name as academic_year_name
            ')
            ->join('grades', 'grades.id = learning_devices.grade_id')
            ->join('school_subjects', 'school_subjects.id = learning_devices.school_subject_id')
            ->join('academic_years', 'academic_years.id = learning_devices.academic_year_id')
            ->where('learning_devices.id', $id);

        if ($userId !== null) {
            $query->where('learning_devices.user_id', $userId);
        }

        return $query->first();
    }

    // Ambil daftar perangkat milik guru tertentu
    public function getListByUser(int $userId, int $academicYearId = null)
    {
        $query = $this->select('
                learning_devices.*, 
                grades.name as grade_name, 
                school_subjects.name as subject_name,
                academic_years.name as academic_year_name
            ')
            ->join('grades', 'grades.id = learning_devices.grade_id')
            ->join('school_subjects', 'school_subjects.id = learning_devices.school_subject_id')
            ->join('academic_years', 'academic_years.id = learning_devices.academic_year_id')
            ->where('learning_devices.user_id', $userId);

        if ($academicYearId !== null) {
            $query->where('learning_devices.academic_year_id', $academicYearId);
        }

        return $query->orderBy('learning_devices.created_at', 'DESC')
            ->findAll() ?? [];
    }
}
