<?php
session_start();
require_once '../config.php';

// Check if user is logged in and is admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

header('Content-Type: application/json');

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        echo json_encode(['success' => false, 'message' => 'Invalid JSON input']);
        exit;
    }
    
    $school_id = $input['school_id'] ?? 0;
    $academic_year = $input['academic_year'] ?? '';
    $term = $input['term'] ?? '';
    $exam_id = $input['exam_id'] ?? 0;
    $class_id = $input['class_id'] ?? 0;
    
    // Validate inputs
    if (empty($school_id) || empty($academic_year) || empty($term) || empty($exam_id) || empty($class_id)) {
        echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
        exit;
    }
    
    // Validate school_id matches user's school
    if ($school_id != $_SESSION["school_id"]) {
        echo json_encode(['success' => false, 'message' => 'Invalid school access']);
        exit;
    }
    
    // Fetch school details
    $school_name = "School Name";
    $school_logo_path = "images/default_school_logo.png";
    
    $sql_school = "SELECT school_name, logo FROM schools WHERE school_id = ?";
    if ($stmt_school = $conn->prepare($sql_school)) {
        $stmt_school->bind_param("i", $school_id);
        if ($stmt_school->execute()) {
            $stmt_school->bind_result($school_name_db, $school_logo_db);
            if ($stmt_school->fetch()) {
                $school_name = htmlspecialchars($school_name_db);
                $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
            }
        }
        $stmt_school->close();
    }
    
    // Fetch exam and class details
    $exam_name = '';
    $class_name = '';
    
    $sql_exam = "SELECT exam_name FROM exams WHERE exam_id = ? AND school_id = ?";
    if ($stmt_exam = $conn->prepare($sql_exam)) {
        $stmt_exam->bind_param("ii", $exam_id, $school_id);
        if ($stmt_exam->execute()) {
            $stmt_exam->bind_result($exam_name_db);
            if ($stmt_exam->fetch()) {
                $exam_name = htmlspecialchars($exam_name_db);
            }
        }
        $stmt_exam->close();
    }
    
    $sql_class = "SELECT class_name FROM classes WHERE class_id = ? AND school_id = ?";
    if ($stmt_class = $conn->prepare($sql_class)) {
        $stmt_class->bind_param("ii", $class_id, $school_id);
        if ($stmt_class->execute()) {
            $stmt_class->bind_result($class_name_db);
            if ($stmt_class->fetch()) {
                $class_name = htmlspecialchars($class_name_db);
            }
        }
        $stmt_class->close();
    }
    
    // Fetch students with grades
    $students_with_grades = [];
    $sql_students = "
        SELECT DISTINCT s.student_id, s.first_name, s.last_name, s.admission_number
        FROM students s 
        JOIN student_classes sc ON s.student_id = sc.student_id
        WHERE sc.class_id = ? AND s.school_id = ?
        ORDER BY s.last_name, s.first_name
    ";
    
    if ($stmt_students = $conn->prepare($sql_students)) {
        $stmt_students->bind_param("ii", $class_id, $school_id);
        if ($stmt_students->execute()) {
            $students_result = $stmt_students->get_result();
            
            while ($student = $students_result->fetch_assoc()) {
                $student_id = $student['student_id'];
                
                // Fetch grades for this student
                $sql_grades = "
                    SELECT g.marks, g.grade, s.subject_name, s.total_marks
                    FROM grades g
                    JOIN subjects s ON g.subject_id = s.subject_id
                    WHERE g.student_id = ? AND g.exam_id = ? AND s.school_id = ?
                    ORDER BY s.subject_name
                ";
                
                $grades = [];
                if ($stmt_grades = $conn->prepare($sql_grades)) {
                    $stmt_grades->bind_param("iii", $student_id, $exam_id, $school_id);
                    if ($stmt_grades->execute()) {
                        $grades_result = $stmt_grades->get_result();
                        while ($grade = $grades_result->fetch_assoc()) {
                            $grades[] = $grade;
                        }
                    }
                    $stmt_grades->close();
                }
                
                // Calculate totals
                $total_marks_obtained = 0;
                $total_possible_marks = 0;
                foreach ($grades as $grade) {
                    $total_marks_obtained += $grade['marks'];
                    $total_possible_marks += $grade['total_marks'];
                }
                
                $percentage = $total_possible_marks > 0 ? round(($total_marks_obtained / $total_possible_marks) * 100, 2) : 0;
                
                $students_with_grades[] = [
                    'student' => $student,
                    'grades' => $grades,
                    'total_marks_obtained' => $total_marks_obtained,
                    'total_possible_marks' => $total_possible_marks,
                    'percentage' => $percentage
                ];
            }
        }
        $stmt_students->close();
    }
    
    // Generate HTML for report cards
    $html = '';
    foreach ($students_with_grades as $student_data) {
        $student = $student_data['student'];
        $grades = $student_data['grades'];
        
        $html .= '<div class="report-card" style="border: 2px solid #007bff; margin-bottom: 30px; background: white; border-radius: 10px; overflow: hidden;">';
        
        // Header
        $html .= '<div style="background: linear-gradient(135deg, #007bff, #0056b3); color: white; padding: 20px; text-align: center;">';
        $html .= '<h2 style="margin: 0; font-size: 1.5rem;">' . $school_name . '</h2>';
        $html .= '<p style="margin: 5px 0;">Student Report Card</p>';
        $html .= '<p style="margin: 5px 0;">' . $academic_year . ' - ' . $term . '</p>';
        $html .= '</div>';
        
        // Student info
        $html .= '<div style="padding: 20px; background: #f8f9fa;">';
        $html .= '<h3 style="margin: 0 0 15px 0; text-align: center; color: #333;">' . htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) . '</h3>';
        $html .= '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">';
        $html .= '<div><strong>Admission Number:</strong> ' . htmlspecialchars($student['admission_number']) . '</div>';
        $html .= '<div><strong>Class:</strong> ' . $class_name . '</div>';
        $html .= '<div><strong>Exam:</strong> ' . $exam_name . '</div>';
        $html .= '<div><strong>Academic Year:</strong> ' . $academic_year . '</div>';
        $html .= '</div></div>';
        
        // Grades table
        if (!empty($grades)) {
            $html .= '<table style="width: 100%; border-collapse: collapse;">';
            $html .= '<thead><tr style="background: #007bff; color: white;">';
            $html .= '<th style="padding: 10px; text-align: left;">Subject</th>';
            $html .= '<th style="padding: 10px; text-align: center;">Marks</th>';
            $html .= '<th style="padding: 10px; text-align: center;">Total</th>';
            $html .= '<th style="padding: 10px; text-align: center;">%</th>';
            $html .= '<th style="padding: 10px; text-align: center;">Grade</th>';
            $html .= '</tr></thead><tbody>';
            
            foreach ($grades as $grade) {
                $percentage = $grade['total_marks'] > 0 ? round(($grade['marks'] / $grade['total_marks']) * 100, 1) : 0;
                $html .= '<tr style="border-bottom: 1px solid #eee;">';
                $html .= '<td style="padding: 8px;">' . htmlspecialchars($grade['subject_name']) . '</td>';
                $html .= '<td style="padding: 8px; text-align: center;">' . $grade['marks'] . '</td>';
                $html .= '<td style="padding: 8px; text-align: center;">' . $grade['total_marks'] . '</td>';
                $html .= '<td style="padding: 8px; text-align: center;">' . $percentage . '%</td>';
                $html .= '<td style="padding: 8px; text-align: center; font-weight: bold;">' . htmlspecialchars($grade['grade']) . '</td>';
                $html .= '</tr>';
            }
            
            // Total row
            $html .= '<tr style="background: #e8f5e8; font-weight: bold; border-top: 2px solid #28a745;">';
            $html .= '<td style="padding: 8px;">TOTAL</td>';
            $html .= '<td style="padding: 8px; text-align: center;">' . $student_data['total_marks_obtained'] . '</td>';
            $html .= '<td style="padding: 8px; text-align: center;">' . $student_data['total_possible_marks'] . '</td>';
            $html .= '<td style="padding: 8px; text-align: center;">' . $student_data['percentage'] . '%</td>';
            $html .= '<td style="padding: 8px; text-align: center;">';
            if ($student_data['percentage'] >= 80) $html .= 'A';
            elseif ($student_data['percentage'] >= 70) $html .= 'B';
            elseif ($student_data['percentage'] >= 60) $html .= 'C';
            elseif ($student_data['percentage'] >= 50) $html .= 'D';
            else $html .= 'F';
            $html .= '</td></tr>';
            $html .= '</tbody></table>';
        } else {
            $html .= '<div style="padding: 20px; text-align: center; color: #666;">No grades recorded for this student.</div>';
        }
        
        $html .= '</div>';
    }
    
    if (empty($students_with_grades)) {
        $html = '<div style="text-align: center; padding: 40px; color: #666;"><h3>No Data Found</h3><p>No students or grades found for the selected criteria.</p></div>';
    }
    
    echo json_encode([
        'success' => true, 
        'html' => $html,
        'student_count' => count($students_with_grades)
    ]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
}

$conn->close();
?>