<?php

namespace App\Models;

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

class AttendanceRecord extends BaseModel
{
    protected $table = 'attendance_record';

    // ✅ CI uses created_at / updated_at
    public $timestamps = true;

    protected $fillable = [
        'class_section_id',
        'student_id',
        'school_id',
        'total_absence',
        'total_late',
        'total_presence',
        'total_attendance',
        'semester',
        'school_year',
        'modified_by',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'class_section_id'   => 'integer',
        'student_id'         => 'integer',
        'school_id'          => 'integer',
        'total_absence'      => 'integer',
        'total_late'         => 'integer',
        'total_presence'     => 'integer',
        'total_attendance'   => 'integer',
        'modified_by'        => 'integer',
    ];

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

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

    /* =========================
     * CI method equivalents
     * ========================= */

    /**
     * Get attendance records by class section, semester, and school year.
     */
    public static function getAttendanceRecordByClass(int $classSectionId, string $semester, string $schoolYear)
    {
        return static::query()
            ->where('class_section_id', $classSectionId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear)
            ->get();
    }

    /**
     * Get attendance record for a specific student in a class section.
     */
    public static function getAttendanceRecord(int $studentId, int $classSectionId, string $semester, string $schoolYear): ?self
    {
        return static::query()
            ->where('student_id', $studentId)
            ->where('class_section_id', $classSectionId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear)
            ->first();
    }

    /**
     * Update an existing attendance record by PK.
     */
    public static function updateAttendanceRecord(int $attendanceId, array $data): bool
    {
        $affected = static::query()->whereKey($attendanceId)->update($data);
        return $affected >= 0;
    }

    /**
     * Increment attendance counters for a student (atomic, avoids race conditions).
     *
     * $increments example: ['total_absence' => 1, 'total_presence' => 0]
     */
    public static function incrementAttendanceCounters(
        int $studentId,
        int $classSectionId,
        string $semester,
        string $schoolYear,
        array $increments
    ): bool {
        $allowed = ['total_absence','total_late','total_presence','total_attendance'];
        $inc = array_intersect_key($increments, array_flip($allowed));

        if (empty($inc)) return true;

        // Build atomic update: field = field + X
        $update = [];
        foreach ($inc as $field => $value) {
            $value = (int) $value;
            if ($value === 0) continue;
            $update[$field] = DB::raw("COALESCE($field,0) + {$value}");
        }

        if (empty($update)) return true;

        $affected = static::query()
            ->where('student_id', $studentId)
            ->where('class_section_id', $classSectionId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear)
            ->update($update);

        // If no record exists, return false (same idea as your CI code)
        return $affected > 0;
    }

    /**
     * Total absences for a student in a term.
     * (Equivalent result, but more efficient than summing in PHP.)
     */
    public static function getTotalAbsences(int $studentId, string $semester, string $schoolYear): int
    {
        return (int) static::query()
            ->where('student_id', $studentId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear)
            ->sum('total_absence');
    }
}