<?php

namespace App\Models;

use CodeIgniter\Model;

class HomeworkModel extends Model
{
    protected $table            = 'homework';
    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',
        'homework_index',
        '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    = [];

/**
 * Calculates the average homework score for a student
 * 
 * @param int $studentId The student ID
 * @param string $semester The semester (e.g., 'Fall', 'Spring')
 * @param string $schoolYear The school year (e.g., '2023-2024')
 * @param int|null $classSectionId Optional class section filter
 * @return float|null The average score (null if no homework found)
 */
public function getAverageHomeworkScore(int $studentId, string $semester, string $schoolYear, ?int $classSectionId = null): ?float
{
    // Pull all scores, then compute based only on non-blank numeric entries
    $builder = $this->db->table('homework');
    $builder->select('score')
        ->where('student_id', $studentId)
        ->where('semester', $semester)
        ->where('school_year', $schoolYear);

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

    $rows = $builder->get()->getResultArray();
    if (empty($rows)) {
        return null;
    }

    $totalScore = 0.0;
    $scoreCount = 0;

    foreach ($rows as $row) {
        $score = $row['score'] ?? null;
        if ($score === null || (is_string($score) && trim($score) === '') || $score === '' || !is_numeric($score)) {
            continue;
        }
        $totalScore += (float) $score;
        $scoreCount++;
    }

    if ($scoreCount === 0) {
        // All entries are blank/null
        return null;
    }

    return round($totalScore / $scoreCount, 2);
}


}
