<?php

namespace App\Models;

use CodeIgniter\Model;

class ParticipationModel extends Model
{
    protected $table            = 'participation';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'student_id',
        'school_id',
        'class_section_id',
        'updated_by',
        'score',
        'comment',
        'semester',
        'school_year',
        'created_at',
        'updated_at'
    ];

    protected bool $allowEmptyInserts = false;
    protected bool $updateOnlyChanged = true;

    protected array $casts = [];
    protected array $castHandlers = [];

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

    // Validation
    protected $validationRules      = [];
    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    = [];

    // Function to get the final exam score for a specific student, semester, and school year
    public function getParticipationScore(int $studentId, string $semester, string $schoolYear, ?int $classSectionId = null): ?float
    {
        $builder = $this->select('score')
            ->where('student_id', $studentId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear);

        if ($classSectionId !== null) {
            $builder->where('class_section_id', $classSectionId);
        }

        $result = $builder->first();
        if (!$result) {
            return null;
        }

        $score = $result['score'] ?? null;
        if ($score === null || (is_string($score) && trim($score) === '') || $score === '' || !is_numeric($score)) {
            return null;
        }

        return (float) $score;
    }
}
