<?php

namespace App\Models;

use CodeIgniter\Model;

class StudentViolationModel extends Model
{
    protected $table            = 'student_violations';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $allowedFields    = ['student_id', 'rule_id', 'date', 'notes', 'recorded_by', 'academic_period_id'];
    protected $useTimestamps    = true;

    // Hitung total poin akumulasi siswa di semester tertentu
    public function getAccumulatedPoints($studentId, $periodId)
    {
        $result = $this->selectSum('violation_rules.points')
            ->join('violation_rules', 'violation_rules.id = student_violations.rule_id')
            ->where('student_violations.student_id', $studentId)
            ->where('student_violations.academic_period_id', $periodId)
            ->first();

        return (int) ($result['points'] ?? 0);
    }

    // Ambil semua log pelanggaran siswa dengan detail rules & categories
    public function getLogsByStudent($studentId, $periodId)
    {
        return $this->select('student_violations.*, violation_rules.code, violation_rules.description, violation_rules.points, violation_rules.severity, violation_categories.name as category_name, users.name as recorder_name')
            ->join('violation_rules', 'violation_rules.id = student_violations.rule_id')
            ->join('violation_categories', 'violation_categories.id = violation_rules.category_id')
            ->join('users', 'users.id = student_violations.recorded_by', 'left')
            ->where('student_violations.student_id', $studentId)
            ->where('student_violations.academic_period_id', $periodId)
            ->orderBy('student_violations.date', 'DESC')
            ->findAll();
    }
}
