<?php

namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Support\Facades\DB;

class Homework extends BaseModel
{
    protected $table = 'homework';

    /**
     * CI: useTimestamps = false (even though created_at/updated_at columns exist).
     * Keep it OFF to match behavior. If you want Laravel to auto-manage, tell me.
     */
    public $timestamps = true;

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

    protected $casts = [
        'student_id'       => 'integer',
        'school_id'        => 'integer',
        'class_section_id' => 'integer',
        'updated_by'       => 'integer',
        'homework_index'   => 'integer',

        // keep numeric; change to 'integer' if your scores are whole numbers
        'score'            => 'decimal:2',

        'created_at'       => 'datetime',
        'updated_at'       => 'datetime',
    ];

    /* Optional relationships */
    public function student()
    {
        return $this->belongsTo(Student::class, 'student_id');
    }

    public function classSection()
    {
        return $this->belongsTo(ClassSection::class, 'class_section_id');
    }

    /**
     * Laravel equivalent of CI getAverageHomeworkScore()
     * Computes average based only on non-blank numeric scores.
     */
    public static function getAverageHomeworkScore(
        int $studentId,
        string $semester,
        string $schoolYear,
        ?int $classSectionId = null
    ): ?float {
        $q = DB::table('homework')
            ->select('score')
            ->where('student_id', $studentId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear);

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

        $rows = $q->get();
        if ($rows->isEmpty()) {
            return null;
        }

        $total = 0.0;
        $count = 0;

        foreach ($rows as $r) {
            $score = $r->score ?? null;

            if ($score === null) continue;
            if (is_string($score) && trim($score) === '') continue;
            if ($score === '') continue;
            if (!is_numeric($score)) continue;

            $total += (float) $score;
            $count++;
        }

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

        return round($total / $count, 2);
    }
}