328 lines
12 KiB
PHP
Executable File
328 lines
12 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Http\Controllers\Api;
|
|
|
|
use App\Models\Configuration;
|
|
use App\Models\Participation;
|
|
use App\Models\StudentClass;
|
|
use App\Models\Student;
|
|
use App\Models\TeacherClass;
|
|
use App\Services\SemesterScoreService;
|
|
use Illuminate\Support\Facades\DB;
|
|
use RuntimeException;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class ParticipationController extends BaseApiController
|
|
{
|
|
protected Configuration $config;
|
|
protected Student $student;
|
|
protected TeacherClass $teacherClass;
|
|
protected Participation $participation;
|
|
protected SemesterScoreService $semesterScoreService;
|
|
protected string $schoolYear;
|
|
protected string $semester;
|
|
|
|
public function __construct()
|
|
{
|
|
parent::__construct();
|
|
$this->config = model(Configuration::class);
|
|
$this->student = model(Student::class);
|
|
$this->teacherClass = model(TeacherClass::class);
|
|
$this->participation = model(Participation::class);
|
|
$this->semesterScoreService = app(SemesterScoreService::class);
|
|
|
|
$this->schoolYear = (string) ($this->config->getConfig('school_year') ?? '');
|
|
$this->semester = (string) ($this->config->getConfig('semester') ?? '');
|
|
}
|
|
|
|
/**
|
|
* GET /api/v1/participation
|
|
* Get participation scores for a class section
|
|
*/
|
|
public function index()
|
|
{
|
|
// Get class_section_id from POST -> GET -> session
|
|
$incoming = $this->request->getPost('class_section_id')
|
|
?? $this->request->getGet('class_section_id')
|
|
?? session()->get('class_section_id');
|
|
|
|
$classSectionId = (int) ($incoming ?: 0);
|
|
|
|
if ($classSectionId <= 0) {
|
|
return $this->respondError('Missing class section.', Response::HTTP_BAD_REQUEST);
|
|
}
|
|
|
|
// Persist for downstream use
|
|
session()->put('class_section_id', $classSectionId);
|
|
|
|
try {
|
|
$result = $this->getSavedScores($classSectionId, $this->semester, $this->schoolYear);
|
|
|
|
return $this->success([
|
|
'students' => $result['students'],
|
|
'semester' => $result['semester'],
|
|
'school_year' => $result['schoolYear'],
|
|
'class_section_id' => $classSectionId,
|
|
], 'Participation scores retrieved successfully');
|
|
} catch (\Throwable $e) {
|
|
log_message('error', 'Participation index error: ' . $e->getMessage());
|
|
return $this->respondError($e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* POST /api/v1/participation
|
|
* Update participation scores (teacher endpoint)
|
|
*/
|
|
public function update()
|
|
{
|
|
$updatedBy = $this->getCurrentUserId();
|
|
if (!$updatedBy) {
|
|
return $this->respondError('Authentication required', Response::HTTP_UNAUTHORIZED);
|
|
}
|
|
|
|
$payload = $this->payloadData();
|
|
$scores = $payload['final_score'] ?? null;
|
|
$classSectionId = (int) ($payload['class_section_id'] ?? session()->get('class_section_id') ?? 0);
|
|
|
|
if (!is_array($scores)) {
|
|
return $this->respondError('No scores submitted.', Response::HTTP_BAD_REQUEST);
|
|
}
|
|
|
|
if ($classSectionId <= 0) {
|
|
return $this->respondError('Missing class section.', Response::HTTP_BAD_REQUEST);
|
|
}
|
|
|
|
try {
|
|
$this->saveParticipationScores('participation', $scores, $updatedBy, $classSectionId, $this->semester, $this->schoolYear);
|
|
|
|
$studentTeacherInfo = $this->student->getStudentInfoByClassSectionId($classSectionId, $this->semester, $this->schoolYear);
|
|
|
|
// Add semester and school_year to each student info for the service
|
|
foreach ($studentTeacherInfo as &$student) {
|
|
$student['semester'] = $this->semester;
|
|
$student['school_year'] = $this->schoolYear;
|
|
}
|
|
unset($student);
|
|
|
|
// Call the updateScoresForStudents method
|
|
try {
|
|
$this->semesterScoreService->updateScoresForStudents($studentTeacherInfo);
|
|
} catch (RuntimeException $e) {
|
|
log_message('error', 'SemesterScoreService error: ' . $e->getMessage());
|
|
}
|
|
|
|
return $this->success([
|
|
'class_section_id' => $classSectionId,
|
|
'updated_count' => count($scores),
|
|
], 'Participation scores updated successfully');
|
|
} catch (\Throwable $e) {
|
|
log_message('error', 'Participation update error: ' . $e->getMessage());
|
|
return $this->respondError('Failed to update participation scores: ' . $e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* POST /api/v1/participation/management
|
|
* Update participation scores (management endpoint)
|
|
*/
|
|
public function updateManagement()
|
|
{
|
|
$payload = $this->payloadData();
|
|
$scores = $payload['final_score'] ?? null;
|
|
$updatedBy = (int) ($payload['teacher_id'] ?? $this->getCurrentUserId() ?? 0);
|
|
$classSectionId = (int) ($payload['class_section_id'] ?? session()->get('class_section_id') ?? 0);
|
|
|
|
if (!is_array($scores)) {
|
|
return $this->respondError('No scores submitted.', Response::HTTP_BAD_REQUEST);
|
|
}
|
|
|
|
if ($classSectionId <= 0) {
|
|
return $this->respondError('Missing class section.', Response::HTTP_BAD_REQUEST);
|
|
}
|
|
|
|
if ($updatedBy <= 0) {
|
|
return $this->respondError('Missing teacher ID.', Response::HTTP_BAD_REQUEST);
|
|
}
|
|
|
|
try {
|
|
$this->saveParticipationScores('participation', $scores, $updatedBy, $classSectionId, $this->semester, $this->schoolYear);
|
|
|
|
$studentTeacherInfo = $this->student->getStudentInfoByClassSectionId($classSectionId, $this->semester, $this->schoolYear);
|
|
|
|
// Add semester and school_year to each student info for the service
|
|
foreach ($studentTeacherInfo as &$student) {
|
|
$student['semester'] = $this->semester;
|
|
$student['school_year'] = $this->schoolYear;
|
|
}
|
|
unset($student);
|
|
|
|
// Call the updateScoresForStudents method
|
|
try {
|
|
$this->semesterScoreService->updateScoresForStudents($studentTeacherInfo);
|
|
} catch (RuntimeException $e) {
|
|
log_message('error', 'SemesterScoreService error: ' . $e->getMessage());
|
|
}
|
|
|
|
// Return the same data structure as index for consistency
|
|
$result = $this->getSavedScores($classSectionId, $this->semester, $this->schoolYear);
|
|
|
|
return $this->success([
|
|
'students' => $result['students'],
|
|
'semester' => $result['semester'],
|
|
'school_year' => $result['schoolYear'],
|
|
'class_section_id' => $classSectionId,
|
|
'updated_count' => count($scores),
|
|
], 'Participation scores updated successfully');
|
|
} catch (\Throwable $e) {
|
|
log_message('error', 'Participation updateManagement error: ' . $e->getMessage());
|
|
return $this->respondError('Failed to update participation scores: ' . $e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* GET /api/v1/participation/management
|
|
* Get participation scores for management view
|
|
*/
|
|
public function showManagement()
|
|
{
|
|
// Get class_section_id from POST -> GET -> session
|
|
$incoming = $this->request->getPost('class_section_id')
|
|
?? $this->request->getGet('class_section_id')
|
|
?? session()->get('class_section_id');
|
|
|
|
$classSectionId = (int) ($incoming ?: 0);
|
|
|
|
if ($classSectionId <= 0) {
|
|
return $this->respondError('Missing class section.', Response::HTTP_BAD_REQUEST);
|
|
}
|
|
|
|
try {
|
|
// Load roster + saved scores for this class/term
|
|
$result = $this->getSavedScores($classSectionId, $this->semester, $this->schoolYear);
|
|
|
|
return $this->success([
|
|
'students' => $result['students'],
|
|
'semester' => $result['semester'],
|
|
'school_year' => $result['schoolYear'],
|
|
'class_section_id' => $classSectionId,
|
|
], 'Participation management data retrieved successfully');
|
|
} catch (\Throwable $e) {
|
|
log_message('error', 'Participation showManagement error: ' . $e->getMessage());
|
|
return $this->respondError($e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* GET /api/v1/participation/student/{id}
|
|
* Get participation score for a specific student
|
|
*/
|
|
public function getByStudent($id = null)
|
|
{
|
|
$participation = $this->participation->newQuery()
|
|
->where('student_id', $id)
|
|
->where('school_year', $this->schoolYear)
|
|
->where('semester', $this->semester)
|
|
->first();
|
|
|
|
return $this->success($participation ?: null, 'Participation retrieved successfully');
|
|
}
|
|
|
|
/**
|
|
* Save participation scores to the database
|
|
*/
|
|
private function saveParticipationScores(string $table, array $scores, int $updatedBy, int $classSectionId, string $semester, string $schoolYear): void
|
|
{
|
|
$now = utc_now();
|
|
|
|
foreach ($scores as $studentId => $data) {
|
|
if (!is_numeric($studentId) || !isset($data['score'])) {
|
|
continue;
|
|
}
|
|
|
|
$score = $data['score'];
|
|
|
|
$existing = DB::table($table)
|
|
->where('student_id', $studentId)
|
|
->where('class_section_id', $classSectionId)
|
|
->where('semester', $semester)
|
|
->where('school_year', $schoolYear)
|
|
->first();
|
|
|
|
$dataToSave = [
|
|
'student_id' => (int) $studentId,
|
|
'class_section_id' => $classSectionId,
|
|
'updated_by' => $updatedBy,
|
|
'score' => is_numeric($score) ? (float) $score : null,
|
|
'semester' => $semester,
|
|
'school_year' => $schoolYear,
|
|
'updated_at' => $now,
|
|
];
|
|
|
|
if ($existing) {
|
|
DB::table($table)
|
|
->where('id', $existing->id)
|
|
->update($dataToSave);
|
|
} else {
|
|
$dataToSave['created_at'] = $now;
|
|
DB::table($table)->insert($dataToSave);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get roster + saved participation scores for a specific classSection/term.
|
|
*/
|
|
private function getSavedScores(int $classSectionId, string $semester, string $schoolYear): array
|
|
{
|
|
if ($classSectionId <= 0) {
|
|
throw new \InvalidArgumentException('Invalid class section id.');
|
|
}
|
|
|
|
session()->put('class_section_id', $classSectionId);
|
|
|
|
// Main query: Students + LEFT JOIN participation for same section/term
|
|
$students = DB::table('students as s')
|
|
->select([
|
|
's.id AS student_id',
|
|
's.school_id',
|
|
's.firstname',
|
|
's.lastname',
|
|
'p.score',
|
|
])
|
|
->join('student_class as sc', function ($join) use ($classSectionId, $schoolYear) {
|
|
$join->on('sc.student_id', '=', 's.id')
|
|
->where('sc.class_section_id', '=', $classSectionId)
|
|
->where('sc.school_year', '=', $schoolYear);
|
|
})
|
|
->leftJoin('participation as p', function ($join) use ($classSectionId, $semester, $schoolYear) {
|
|
$join->on('p.student_id', '=', 's.id')
|
|
->where('p.class_section_id', '=', $classSectionId)
|
|
->where('p.semester', '=', $semester)
|
|
->where('p.school_year', '=', $schoolYear);
|
|
})
|
|
->distinct()
|
|
->orderBy('s.lastname', 'ASC')
|
|
->orderBy('s.firstname', 'ASC')
|
|
->get()
|
|
->map(function ($row) {
|
|
return (array) $row;
|
|
})
|
|
->toArray();
|
|
|
|
// Final safety net: ensure one row per student_id
|
|
$unique = [];
|
|
foreach ($students as $r) {
|
|
$unique[(int) $r['student_id']] = $r;
|
|
}
|
|
|
|
$students = array_values($unique);
|
|
|
|
return [
|
|
'students' => $students,
|
|
'semester' => $semester,
|
|
'schoolYear' => $schoolYear,
|
|
];
|
|
}
|
|
}
|