asArray() ->where('class_section_id', $sectionId) ->where('school_year', $year); if ($sem !== '') { if ($allowNullSemester) { $b = $b->groupStart() ->where('semester', $sem) ->orWhere('semester IS NULL', null, false) ->groupEnd(); } else { $b = $b->where('semester', $sem); } } if ($onlyActive) { $b = $b->where('active', 1); } // If you also want to ignore blank links: $b = $b->where('invite_link IS NOT NULL', null, false) ->where('invite_link !=', ''); return $b->orderBy('updated_at', 'DESC') ->orderBy('id', 'DESC') ->first() ?: null; } /** * Get all links for a term. * * @param string $year * @param string $sem * @param bool|null $onlyActive true: active only, false: inactive only, null: both * @param bool $allowNullSemester If true, include rows with semester IS NULL. */ public function getAllForTerm( string $year, string $sem, ?bool $onlyActive = null, bool $allowNullSemester = false ): array { $year = trim($year); $sem = trim($sem); $b = $this->asArray() ->where('school_year', $year); if ($sem !== '') { if ($allowNullSemester) { $b = $b->groupStart() ->where('semester', $sem) ->orWhere('semester IS NULL', null, false) ->groupEnd(); } else { $b = $b->where('semester', $sem); } } if ($onlyActive === true) { $b = $b->where('active', 1); } elseif ($onlyActive === false) { $b = $b->where('active', 0); } return $b->orderBy('updated_at', 'DESC') ->orderBy('id', 'DESC') ->findAll(); } /** * Convenience: upsert a link row for a section/term. * Returns the row (array) after save. */ public function upsertLinkForSection( int $sectionId, string $sectionName, string $year, string $sem, string $inviteLink, bool $active = true ): array { $payload = [ 'class_section_id' => $sectionId, 'class_section_name' => $sectionName, 'school_year' => trim($year), 'semester' => trim($sem), 'invite_link' => trim($inviteLink), 'active' => $active ? 1 : 0, ]; // Try to find existing row (exact term) $existing = $this->asArray() ->where('class_section_id', $sectionId) ->where('school_year', $payload['school_year']) ->where('semester', $payload['semester']) ->first(); if ($existing) { $this->update((int)$existing['id'], $payload); $id = (int) $existing['id']; } else { $id = $this->insert($payload, true); } return $this->find($id) ?? $payload; } }