<?php

namespace App\Modules\Academic\Models;

use App\Modules\Academic\Entities\Student;
use CodeIgniter\Model;

/**
 * Student Model
 * 
 * Handles database operations for students.
 */
class StudentModel extends Model
{
    protected $table            = 'students';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = Student::class;
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'dapodik_id',
        'face_external_id',
        'face_hash',
        'nisn',
        'name',
        'gender',
        'class_id',
        'is_active',
        'parent_link_code',
    ];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation (class_id nullable for unmapped/Dapodik)
    protected $validationRules = [
        'dapodik_id'       => 'permit_empty|max_length[64]|is_unique[students.dapodik_id,id,{id}]',
        'face_external_id' => 'permit_empty|max_length[100]|is_unique[students.face_external_id,id,{id}]',
        'face_hash'        => 'permit_empty|max_length[32]',
        'nisn'             => 'required|max_length[50]|is_unique[students.nisn,id,{id}]',
        'name'             => 'required|max_length[255]',
        'gender'           => 'permit_empty|in_list[L,P]',
        'class_id'         => 'permit_empty|integer|is_not_unique[classes.id]',
        'is_active'        => 'permit_empty|in_list[0,1]',
    ];

    protected $validationMessages = [];
    protected $skipValidation     = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];

    /**
     * Find student by NISN
     *
     * @param string $nisn
     * @return Student|null
     */
    public function findByNisn(string $nisn): ?Student
    {
        return $this->where('nisn', $nisn)->first();
    }
}
