<?php

namespace App\Models;

use CodeIgniter\Model;

class GradingLockModel extends Model
{
    protected $table = 'grading_locks';
    protected $primaryKey = 'id';
    protected $returnType = 'array';
    protected $useTimestamps = true;
    protected $allowedFields = [
        'class_section_id',
        'semester',
        'school_year',
        'is_locked',
        'locked_by',
        'locked_at',
        'created_at',
        'updated_at',
    ];

    public function getLock(int $classSectionId, string $semester, string $schoolYear): ?array
    {
        if ($classSectionId <= 0 || $semester === '' || $schoolYear === '') {
            return null;
        }

        return $this->where('class_section_id', $classSectionId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear)
            ->orderBy('id', 'DESC')
            ->first();
    }

    public function isLocked(int $classSectionId, string $semester, string $schoolYear): bool
    {
        $row = $this->getLock($classSectionId, $semester, $schoolYear);
        return !empty($row['is_locked']);
    }
}
