<?php

namespace App\Models;

use CodeIgniter\Model;

class ProjectModel extends Model
{
    protected $table            = 'project';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;

    protected $allowedFields = [
        'student_id',
        'school_id',
        'class_section_id',
        'updated_by',
        'project_index',
        'score',
        'comment',
        'semester',
        'school_year',
        'created_at',
        'updated_at'
    ];

    /**
     * Calculate the average project score for a given student, semester, and school year.
     *
     * @param int $studentId The student's ID.
     * @param string $semester The semester (e.g., 'Fall', 'Spring').
     * @param string $schoolYear The school year (e.g., '2024-2025').
     * @param int|null $classSectionId Optional class section filter.
     * @return float|null The average project score, or null if no scores are found.
     */
    public function getAverageProjectScore(int $studentId, string $semester, string $schoolYear, ?int $classSectionId = null): ?float
    {
        // Fetch the project scores for the given student, semester, and school year
        $builder = $this->builder();
        $builder->select('score')
                ->where('student_id', $studentId)
                ->where('semester', $semester)
                ->where('school_year', $schoolYear);
        
        if ($classSectionId !== null) {
            $builder->where('class_section_id', $classSectionId);
        }
        
        // Execute the query and get the results
        $query = $builder->get();
        $results = $query->getResultArray();

        // If there are no scores, return null
        if (empty($results)) {
            return null;
        }

        // Calculate the average score (ignore blank/null/non-numeric)
        $totalScore = 0.0;
        $scoreCount = 0;

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

        if ($scoreCount === 0) {
            return null;
        }

        return $totalScore / $scoreCount;
    }
}
