false, 'message' => '', 'html' => '']; try { // Check PIN usage and restrictions $associateQuery = $DBcon->prepare("SELECT * FROM pinassociate WHERE PINCODE = ? ORDER BY SN DESC LIMIT 1"); $associateQuery->execute([$pin]); $associateData = $associateQuery->fetch(PDO::FETCH_ASSOC); if ($associateData) { if ($associateData['NOUSED'] >= 6) { $response['message'] = 'This PIN has exceeded the maximum usage limit. Please get a new PIN.'; echo json_encode($response); exit; } if ($associateData['REGNO'] !== $regno) { $response['message'] = 'This PIN is already associated with another registration number.'; echo json_encode($response); exit; } if ($associateData['TERM'] !== $term || $associateData['acadsession'] !== $academic_year) { if (!($associateData['TERM'] === 'ANNUAL TERM' && $term === 'THIRD TERM')) { $response['message'] = 'This PIN is restricted to ' . $associateData['TERM'] . ' ' . $associateData['acadsession'] . ' result only.'; echo json_encode($response); exit; } } $updateQuery = $DBcon->prepare("UPDATE pinassociate SET NOUSED = NOUSED + 1 WHERE PINCODE = ?"); $updateQuery->execute([$pin]); } else { $insertQuery = $DBcon->prepare("INSERT INTO pinassociate (REGNO, NOUSED, PINCODE, TERM, acadsession) VALUES (?, 1, ?, ?, ?)"); $insertQuery->execute([$regno, $pin, $term, $academic_year]); } // Fetch student details $studentQuery = $DBcon->prepare("SELECT * FROM students WHERE reg_no = ?"); $studentQuery->execute([$regno]); $student = $studentQuery->fetch(PDO::FETCH_ASSOC); if (!$student) { $response['message'] = 'Student record not found.'; echo json_encode($response); exit; } // Fetch student's marks $marksQuery = $DBcon->prepare("SELECT * FROM marks WHERE regno = ? AND acyear = ? AND term = ? AND klass = ?"); $marksQuery->execute([$regno, $academic_year, $term, $class]); $marks = $marksQuery->fetchAll(PDO::FETCH_ASSOC); if (empty($marks)) { $response['message'] = 'No result found for the selected criteria.'; echo json_encode($response); exit; } // Fetch all students in the class for position calculation $classStudentsQuery = $DBcon->prepare("SELECT DISTINCT regno FROM marks WHERE acyear = ? AND term = ? AND klass = ?"); $classStudentsQuery->execute([$academic_year, $term, $class]); $classStudents = $classStudentsQuery->fetchAll(PDO::FETCH_COLUMN); // Calculate averages for all students to determine position $studentAverages = []; foreach ($classStudents as $studentRegno) { $studentMarksQuery = $DBcon->prepare("SELECT * FROM marks WHERE regno = ? AND acyear = ? AND term = ? AND klass = ?"); $studentMarksQuery->execute([$studentRegno, $academic_year, $term, $class]); $studentMarks = $studentMarksQuery->fetchAll(PDO::FETCH_ASSOC); if (!empty($studentMarks)) { $totalScore = 0; $subjectCount = count($studentMarks); foreach ($studentMarks as $mark) { $totalScore += $mark['test'] + $mark['exam']; } $average = $subjectCount > 0 ? $totalScore / $subjectCount : 0; $studentAverages[$studentRegno] = $average; } } // Sort students by average (descending) arsort($studentAverages); // Find current student's position $position = array_search($regno, array_keys($studentAverages)) + 1; // Calculate class statistics for each subject $subjectStats = []; $subjectsQuery = $DBcon->prepare("SELECT DISTINCT subject FROM marks WHERE acyear = ? AND term = ? AND klass = ?"); $subjectsQuery->execute([$academic_year, $term, $class]); $subjects = $subjectsQuery->fetchAll(PDO::FETCH_COLUMN); foreach ($subjects as $subject) { $statsQuery = $DBcon->prepare(" SELECT MAX(test + exam) as highest, MIN(test + exam) as lowest FROM marks WHERE acyear = ? AND term = ? AND klass = ? AND subject = ? "); $statsQuery->execute([$academic_year, $term, $class, $subject]); $stats = $statsQuery->fetch(PDO::FETCH_ASSOC); $subjectStats[$subject] = [ 'highest' => $stats['highest'] ?? 0, 'lowest' => $stats['lowest'] ?? 0 ]; } // Generate HTML result $html = generateResultHTML($student, $marks, $subjectStats, $class, $term, $academic_year, $position, $studentAverages[$regno]); $response['success'] = true; $response['html'] = $html; } catch (PDOException $e) { error_log("Result fetch error: " . $e->getMessage()); $response['message'] = 'System error. Please try again later.'; } echo json_encode($response); exit; } function generateResultHTML($student, $marks, $subjectStats, $class, $term, $academic_year, $position, $average) { $studentPhoto = (!empty($student['image']) && $student['image'] !== 'NILL') ? $student['image'] : 'images/default-student.png'; $currentDate = date('F j, Y'); $html = '

Government Approved


Name: '.$student['fullname'].' Term: '.$term.'
Registration No: '.$student['reg_no'].' Academic Year: '.$academic_year.'
Class: '.$class.' Position: '.$position.'
Student Photo
'; $totalScore = 0; $subjectCount = count($marks); foreach ($marks as $mark) { $total = $mark['test'] + $mark['exam']; $totalScore += $total; $grade = calculateGrade($total); $remark = calculateRemark($grade); $gradeColor = getGradeColor($grade); $html .= ' '; } $html .= '
Subject Test Exam Total Class Highest Class Lowest Grade Remark
'.$mark['subject'].' '.$mark['test'].' '.$mark['exam'].' '.$total.' '.($subjectStats[$mark['subject']]['highest'] ?? 'N/A').' '.($subjectStats[$mark['subject']]['lowest'] ?? 'N/A').' '.$grade.' '.$remark.'

PERFORMANCE SUMMARY

Total Score
'.$totalScore.'
Subjects
'.$subjectCount.'
Average
'.number_format($average, 2).'
Position
'.$position.'
CLASS TEACHER\'S COMMENT

'.getTeacherComment($average).'

Signature: ___________________

PRINCIPAL\'S COMMENT

'.getPrincipalComment($average).'

Signature: ___________________

Date Issued:

'.$currentDate.'

School Stamp

OFFICIAL STAMP

Note: This result is computer generated and requires no signature when printed.

'; return $html; } function calculateGrade($score) { if ($score >= 81) return 'A'; if ($score >= 61) return 'B'; if ($score >= 51) return 'C'; if ($score >= 40) return 'D'; return 'F'; } function calculateRemark($grade) { switch ($grade) { case 'A': return 'Excellent'; case 'B': return 'Very Good'; case 'C': return 'Good'; case 'D': return 'Pass'; case 'F': return 'Fail'; default: return ''; } } function getGradeColor($grade) { switch ($grade) { case 'A': return '#27ae60'; case 'B': return '#2980b9'; case 'C': return '#f39c12'; case 'D': return '#e67e22'; case 'F': return '#e74c3c'; default: return '#7f8c8d'; } } function getTeacherComment($average) { if ($average >= 80) return 'An outstanding performance! Keep up the excellent work.'; if ($average >= 70) return 'Very good performance. Continue to strive for excellence.'; if ($average >= 60) return 'Good effort demonstrated. aim for better results can be achieved.'; if ($average >= 50) return 'Satisfactory performance. There is room for improvement with more dedication to studies.'; if ($average >= 40) return 'Basic understanding shown. Requires more effort and regular study to improve performance.'; return 'Needs significant improvement. Please pay more attention to studies and seek help when needed.'; } function getPrincipalComment($average) { if ($average >= 80) return 'Exceptional academic achievement! A model student worthy of emulation. '; if ($average >= 70) return 'Commendable performance, Continue to maintain this standard of excellence.'; if ($average >= 60) return 'Satisfactory performance showing promise. With increased effort, higher achievement is attainable.'; if ($average >= 50) return 'Acceptable performance that requires enhancement. Greater commitment to academic work is encouraged.'; if ($average >= 40) return 'Minimal performance level achieved. Immediate improvement through dedicated study is necessary.'; return 'Academic performance requires urgent attention. Parental guidance and extra lessons are recommended for improvement.'; } ?>