<?php

namespace App\Models;

use App\Models\BaseModel;

class GradingLock extends BaseModel
{
    protected $table = 'grading_locks';

    // ✅ CI: useTimestamps = true
    public $timestamps = true;

    protected $fillable = [
        'class_section_id',
        'semester',
        'school_year',
        'is_locked',
        'locked_by',
        'locked_at',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'class_section_id' => 'integer',
        'is_locked'        => 'boolean',
        'locked_by'        => 'integer',
        'locked_at'        => 'datetime',
    ];

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

    public function lockedByUser()
    {
        return $this->belongsTo(User::class, 'locked_by');
    }

    /**
     * Equivalent of CI getLock()
     */
    public static function getLock(int $classSectionId, string $semester, string $schoolYear): ?self
    {
        if ($classSectionId <= 0 || $semester === '' || $schoolYear === '') {
            return null;
        }

        return static::query()
            ->where('class_section_id', $classSectionId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear)
            ->orderByDesc('id')
            ->first();
    }

    /**
     * Equivalent of CI isLocked()
     */
    public static function isLocked(int $classSectionId, string $semester, string $schoolYear): bool
    {
        $row = static::getLock($classSectionId, $semester, $schoolYear);
        return (bool) ($row?->is_locked ?? false);
    }
}