<?php

namespace App\Models;

use CodeIgniter\Model;

class StudentModel extends Model
{
    protected $table            = 'students';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = true;
    protected $allowedFields    = [
        'nis', 'nisn', 'nik', 'kip_no', 'full_name', 'gender',
        'birth_place', 'birth_date', 'religion', 'photo',
        'entry_year', 'entry_date', 'origin_school', 'graduation_certificate_no', 'status',
        'exit_date', 'exit_to', 'exit_reason',
        'address', 'rt', 'rw', 'village', 'district',
        'city', 'province', 'postal_code', 'phone',
        'family_card_no', 'family_head_name',
        'father_name', 'father_nik', 'father_birth_place', 'father_birth', 'father_edu', 'father_job', 'father_phone',
        'mother_name', 'mother_nik', 'mother_birth_place', 'mother_birth', 'mother_edu', 'mother_job', 'mother_phone',
        'graduated_academic_year_id', // untuk fitur kelulusan
    ];

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

    protected $validationRules = [
        'nis'       => 'required|max_length[20]',
        'full_name' => 'required|min_length[3]|max_length[100]',
        'gender'    => 'required|in_list[L,P]',
    ];

    // Ambil NIS terakhir berdasarkan tahun masuk
    public function getLastNis($entryYear)
    {
        $prefix = substr($entryYear, -2); // 2025 → 25
        return $this->select('nis')
                    ->like('nis', $prefix, 'after')
                    ->orderBy('nis', 'DESC')
                    ->first();
    }

    // Saran NIS berikutnya
    public function getSuggestNis($entryYear)
    {
        $prefix = substr($entryYear, -2);
        $last   = $this->getLastNis($entryYear);

        if ($last) {
            $lastNumber = (int) substr($last['nis'], 2);
            $next       = $lastNumber + 1;
        } else {
            $next = 1;
        }

        return $prefix . str_pad($next, 4, '0', STR_PAD_LEFT);
    }
}