<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/function.php');
require_once('source/restrict_user.php');

// Validate and sanitize input parameters
$registration_no = $_GET['myreg'] ?? '';
$myclass = trim($_GET['myclass'] ?? '');
$term = trim($_GET['term'] ?? '');
$examyear = trim($_GET['examyear'] ?? '');

if (empty($registration_no) || empty($myclass) || empty($term) || empty($examyear)) {
    die("<div class='alert alert-danger'>Required parameters are missing.</div>");
}

// [Include all the same data fetching logic from my_results.php here]
// Fetch student details
$student = sql($DBH, "SELECT * FROM tbl_user WHERE registration_no = ?", [$registration_no], "rows");
if (empty($student)) {
    die("<div class='alert alert-danger'>Student not found.</div>");
}
$student = $student[0];

$user_name = $student['fullname'];
$user_gender = $student['gender'];
$user_age = $student['age'];
$user_profile_pic = $student['profile_pic'] ?: 'default';

// Calculate age
$age = '';
if (!empty($user_age)) {
    if (strpos($user_age, '/') !== false) {
        $birthDate = explode('/', $user_age);
        $month = (int)$birthDate[0];
        $day = (int)$birthDate[1];
        $year = (int)$birthDate[2];
    } elseif (strpos($user_age, '-') !== false) {
        $birthDate = explode('-', $user_age);
        $year = (int)$birthDate[0];
        $month = (int)$birthDate[1];
        $day = (int)$birthDate[2];
    } else {
        $month = 1;
        $day = 1;
        $year = 2000;
    }

    $currentYear = date('Y');
    $currentMonth = date('m');
    $currentDay = date('d');

    $age = $currentYear - $year;
    if ($currentMonth < $month || ($currentMonth == $month && $currentDay < $day)) {
        $age--;
    }
} else {
    $age = 'N/A';
}

// Fetch result summary
$results = sql($DBH, "SELECT * FROM tbl_student_results WHERE registration_no = ? AND class = ? AND term = ? AND year = ?", [$registration_no, $myclass, $term, $examyear], "rows");

// Calculate student average
if (empty($results)) {
    $average_score = 0;
    $grand_total_current = 0;
} else {
    $total_sum = 0;
    foreach ($results as $row) {
        $total = ($row['test1'] + $row['test2'] + $row['exam']);
        $total_sum += $total;
    }
    $grand_total_current = $total_sum;
    $average_score = round($total_sum / count($results), 2);
}

// Grade and comments configuration
$grade_comments = [
    ['range' => [0, 49], 'grade' => 'F', 'remark' => 'Fail', 'comment' => 'Poor result, requires hard work and consistent effort to excel.'],
    ['range' => [50, 59], 'grade' => 'D', 'remark' => 'Weak Pass', 'comment' => 'Poor pass! Requires genuine interest and extra effort to make good grades.'],
    ['range' => [60, 64], 'grade' => 'C+', 'remark' => 'Pass', 'comment' => 'Pass, needs to study harder next term to achieve outstanding grades.'],
    ['range' => [65, 69], 'grade' => 'C+', 'remark' => 'Pass', 'comment' => 'Satisfactory result, ensure you work harder next term.'],
    ['range' => [70, 74], 'grade' => 'B', 'remark' => 'Credit', 'comment' => 'Good result, remain focused and work harder next term.'],
    ['range' => [75, 79], 'grade' => 'B+', 'remark' => 'Credit', 'comment' => 'Very good result. Do not relent, extra hard work needed next term.'],
    ['range' => [80, 89], 'grade' => 'A', 'remark' => 'Distinction', 'comment' => 'Fantastic performance! Stay on track to improve more.'],
    ['range' => [90, 100], 'grade' => 'A+', 'remark' => 'Distinction', 'comment' => 'Bravo! Keep soaring.']
];

// Determine grade and comments
$grade_info = null;
foreach ($grade_comments as $grade) {
    if ($average_score >= $grade['range'][0] && $average_score <= $grade['range'][1]) {
        $grade_info = $grade;
        break;
    }
}

$cgrade = $grade_info ? $grade_info['grade'] : 'N/A';
$cgradeR = $grade_info ? $grade_info['remark'] : 'N/A';
$htcomments = $grade_info ? $grade_info['comment'] : 'No comment available.';

// Fetch attendance
$attendance = sql($DBH, "SELECT * FROM attendance WHERE registration_no = ? AND class = ? AND term = ? AND year = ?", [$registration_no, $myclass, $term, $examyear], "rows")[0] ?? [];
$SchOpen = $attendance['SchOpen'] ?? 0;
$Present = $attendance['Present'] ?? 0;
$Absent = $SchOpen - $Present;
$DateOfReport = $attendance['DateOfReport'] ?? '';
$NextTermBegins = $attendance['NextTermBegins'] ?? '';
$TeachersRemarks = $attendance['TeachersRemarks'] ?? '';
$PrincipalsComment = $attendance['PrincipalsComment'] ?? '';

// Fetch skills
$skills = sql($DBH, "SELECT * FROM skills WHERE registration_no = ? AND class = ? AND term = ? AND year = ?", [$registration_no, $myclass, $term, $examyear], "rows")[0] ?? [];
$psychomotor = [
    'Handwriting' => $skills['Handwriting'] ?? '',
    'Fluency' => $skills['Fluency'] ?? '',
    'Games' => $skills['Games'] ?? '',
    'HandlingTools' => $skills['HandlingTools'] ?? '',
    'Drawing' => $skills['Drawing'] ?? '',
    'Creativity' => $skills['Creativity'] ?? '',
    'MusicalSkills' => $skills['MusicalSkills'] ?? ''
];
$affective = [
    'Punctuality' => $skills['Punctuality'] ?? '',
    'AttendanceToClass' => $skills['AttendanceToClass'] ?? '',
    'Reliability' => $skills['Reliability'] ?? '',
    'Neatness' => $skills['Neatness'] ?? '',
    'Politeness' => $skills['Politeness'] ?? '',
    'Honesty' => $skills['Honesty'] ?? '',
    'Obedience' => $skills['Obedience'] ?? '',
    'RelationshipWithOthers' => $skills['RelationshipWithOthers'] ?? '',
    'SelfControl' => $skills['SelfControl'] ?? '',
    'Attentiveness' => $skills['Attentiveness'] ?? '',
    'Initiative' => $skills['Initiative'] ?? '',
    'OrganizationalAbility' => $skills['OrganizationalAbility'] ?? '',
    'Perseverance' => $skills['Perseverance'] ?? ''
];

// Fetch cumulative results and positions
$terms = ['1st Term', '2nd Term', '3rd Term'];
$cumulative = [];
$position_data = [];

foreach ($terms as $t) {
    $result = sql($DBH, "SELECT SUM(test1 + test2 + exam) as total, COUNT(*) as count FROM tbl_student_results WHERE registration_no = ? AND class = ? AND term = ? AND year = ?", 
        [$registration_no, $myclass, $t, $examyear], "rows")[0];
    
    $cumulative[$t] = [
        'total' => $result['total'] ?? 0,
        'avg' => $result['count'] > 0 ? round($result['total'] / $result['count'], 2) : 'N/A'
    ];

    $pos_query = sql($DBH, "SELECT position FROM tbl_overall WHERE reg_no = ? AND class = ? AND term = ? AND year = ?",
        [$registration_no, $myclass, $t, $examyear], "rows");
    
    $position_data[$t] = !empty($pos_query) ? $pos_query[0]['position'] : 'N/A';
}

$grand_total = array_sum(array_column($cumulative, 'total'));
$valid_avgs = array_filter(array_column($cumulative, 'avg'), function($v) { return $v !== 'N/A'; });
$cummulative_avg = !empty($valid_avgs) ? round(array_sum($valid_avgs) / count($valid_avgs), 2) : 'N/A';

// Subject cumulative data for 3rd Term
$subject_cumulative = [];
$overall_position = 'N/A';

if ($term == '3rd Term') {
    foreach ($results as $row) {
        $subject = $row['subject'];
        
        $terms_data = sql($DBH, 
            "SELECT term, (test1 + test2 + exam) as total, position 
             FROM tbl_student_results 
             WHERE registration_no = ? AND class = ? AND year = ? AND subject = ? 
             ORDER BY term",
            [$registration_no, $myclass, $examyear, $subject], 
            "rows"
        );
        
        $sum = 0;
        $count = 0;
        $positions = [];
        foreach ($terms_data as $term_data) {
            $sum += $term_data['total'];
            $count++;
            if (isset($term_data['position'])) {
                $positions[] = $term_data['position'];
            }
        }
        
        $subject_cumulative[$subject] = [
            'avg' => $count > 0 ? round($sum / $count, 2) : 'N/A',
            'position' => !empty($positions) ? min($positions) : 'N/A'
        ];
    }
    
    $overall_position_query = sql($DBH,
        "SELECT position FROM tbl_overall 
         WHERE reg_no = ? AND class = ? AND year = ? AND term = '3rd Term'",
        [$registration_no, $myclass, $examyear],
        "rows"
    );
    
    if (!empty($overall_position_query)) {
        $overall_position = $overall_position_query[0]['position'];
    }
}

// Function to format position badges
function formatPositionBadge($position, $full_text = false) {
    if (!is_numeric($position)) {
        return htmlspecialchars($position);
    }
    
    $position_text = $full_text ? 
        ($position == 1 ? '1st Position' : 
         ($position == 2 ? '2nd Position' : 
          ($position == 3 ? '3rd Position' : 
           ($position <= 10 ? 'Top 10 (#' . $position . ')' : '#' . $position)))) : 
        $position;
    
    $badge_class = '';
    if ($position == 1) {
        $badge_class = 'position-gold';
        $icon = '🥇';
    } elseif ($position == 2) {
        $badge_class = 'position-silver';
        $icon = '🥈';
    } elseif ($position == 3) {
        $badge_class = 'position-bronze';
        $icon = '🥉';
    } elseif ($position <= 10) {
        $badge_class = 'position-top10';
        $icon = '🏅';
    } else {
        $icon = '';
    }
    
    return "<span class='badge rounded-pill position-badge $badge_class'>$icon $position_text</span>";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Print Result - Verbum Dei International College</title>
    <!-- Bootstrap 5 CDN -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #0d47a1;
            --secondary-color: #1976d2;
            --accent-color: #bbdefb;
            --dark-color: #002171;
            --light-color: #e3f2fd;
            --success-color: #2e7d32;
            --warning-color: #ff8f00;
            --danger-color: #c62828;
        }
        
        @page {
            size: A4;
            margin: 10mm;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background-color: white;
            color: #333;
            padding: 20px;
        }
        
        .print-container {
            width: 100%;
            max-width: 100%;
            margin: 0 auto;
        }
        
        .print-header {
            text-align: center;
            margin-bottom: 15px;
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            color: white;
            padding: 10px;
            border-radius: 8px;
        }
        
        .school-name {
            font-weight: bold;
            font-size: 18pt;
            margin-bottom: 5px;
        }
        
        .student-info {
            margin-bottom: 15px;
            font-size: 11pt;
            background-color: var(--light-color);
            padding: 10px;
            border-radius: 8px;
            border-left: 4px solid var(--primary-color);
        }
        
        .performance-section {
            display: flex;
            margin-bottom: 15px;
            gap: 15px;
        }
        
        .academic-performance {
            flex: 3;
            background-color: white;
            padding: 10px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .skills-assessment {
            flex: 2;
            background-color: white;
            padding: 10px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .table {
            width: 100%;
            border-collapse: collapse;
            font-size: 9pt;
        }
        
        .table th {
            background-color: var(--primary-color);
            color: white;
            text-align: center;
            padding: 6px;
            border: 1px solid #ddd;
        }
        
        .table td {
            border: 1px solid #ddd;
            padding: 5px;
            text-align: center;
        }
        
        .table tr:nth-child(even) {
            background-color: var(--light-color);
        }
        
        .table tr:nth-child(odd) {
            background-color: white;
        }
        
        .table tr:hover {
            background-color: var(--accent-color);
        }
        
        .skills-table {
            width: 100%;
            margin-bottom: 10px;
            font-size: 9pt;
        }
        
        .skills-table td {
            padding: 4px;
        }
        
        .progress {
            height: 15px;
            margin-bottom: 5px;
            background-color: #e9ecef;
            border-radius: 4px;
        }
        
        .progress-bar {
            background-color: var(--secondary-color);
            font-size: 8pt;
            line-height: 15px;
            border-radius: 4px;
        }
        
        .comments-section {
            margin-top: 15px;
            position: relative;
            background-color: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .principal-stamp {
            position: absolute;
            right: 20px;
            bottom: 20px;
            opacity: 0.3;
            z-index: -1;
            width: 120px;
        }
        
        .grade-badge {
            padding: 3px 6px;
            border-radius: 4px;
            font-weight: bold;
            font-size: 9pt;
        }
        
        .grade-A { background-color: var(--success-color); color: white; }
        .grade-B { background-color: #689f38; color: white; }
        .grade-C { background-color: var(--warning-color); color: white; }
        .grade-D { background-color: #ef6c00; color: white; }
        .grade-F { background-color: var(--danger-color); color: white; }
        
        .position-badge {
            font-size: 9pt;
            padding: 3px 8px;
            font-weight: 700;
        }
        
        .position-gold {
            background: linear-gradient(135deg, #FFD700 0%, #D4AF37 100%);
            color: #000;
        }
        
        .position-silver {
            background: linear-gradient(135deg, #C0C0C0 0%, #A8A8A8 100%);
            color: #000;
        }
        
        .position-bronze {
            background: linear-gradient(135deg, #CD7F32 0%, #A67C52 100%);
            color: #fff;
        }
        
        .position-top10 {
            background: linear-gradient(135deg, #4CAF50 0%, #2E7D32 100%);
            color: #fff;
        }
        
        .summary-box {
            background-color: var(--light-color);
            padding: 10px;
            border-radius: 8px;
            margin-top: 10px;
            border-left: 4px solid var(--primary-color);
        }
        
        @media print {
            body {
                padding: 0;
                font-size: 10pt;
            }
            
            .no-print {
                display: none !important;
            }
            
            .print-header {
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .table th {
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .principal-stamp {
                opacity: 0.7;
            }
            
            .table tr:nth-child(even) {
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
        }
    </style>
</head>
<body>
    <div class="print-container">
        <!-- Header -->
        <div class="print-header">
            <div class="school-name">Verbum Dei International College</div>
            <div>Student Academic Report - <?php echo htmlspecialchars($term); ?>, <?php echo htmlspecialchars($examyear); ?></div>
        </div>
        
        <!-- Student Info -->
        <div class="student-info">
            <div class="row">
                <div class="col-4"><strong>Name:</strong> <?php echo htmlspecialchars($user_name); ?></div>
                <div class="col-4"><strong>Reg No:</strong> <?php echo htmlspecialchars($registration_no); ?></div>
                <div class="col-4"><strong>Class:</strong> <?php echo htmlspecialchars($myclass); ?></div>
                <div class="col-4"><strong>Gender:</strong> <?php echo htmlspecialchars($user_gender); ?></div>
                <div class="col-4"><strong>Age:</strong> <?php echo $age; ?> Years</div>
                <div class="col-4"><strong>Term:</strong> <?php echo htmlspecialchars($term); ?></div>
            </div>
        </div>
        
        <!-- Attendance Summary -->
        <div class="summary-box">
            <div class="row">
                <div class="col-3"><strong>School Days:</strong> <?php echo $SchOpen; ?></div>
                <div class="col-3"><strong>Present:</strong> <?php echo $Present; ?></div>
                <div class="col-3"><strong>Absent:</strong> <?php echo $Absent; ?></div>
                <div class="col-3"><strong>Attendance Rate:</strong> <?php echo $SchOpen > 0 ? round(($Present/$SchOpen)*100, 2) : 0; ?>%</div>
                <div class="col-4"><strong>Term Ends:</strong> <?php echo htmlspecialchars($DateOfReport); ?></div>
                <div class="col-4"><strong>Next Term:</strong> <?php echo htmlspecialchars($NextTermBegins); ?></div>
                <div class="col-4"><strong>Class Size:</strong> <?php echo $count_student; ?></div>
            </div>
        </div>
        
        <!-- Performance Section -->
        <div class="performance-section">
            <!-- Academic Performance (Left) -->
            <div class="academic-performance">
                <h5 style="text-align: center; color: var(--primary-color); margin-bottom: 15px;">Academic Performance</h5>
                <table class="table">
                    <thead>
                        <tr>
                            <th>Subject</th>
                            <th>1st CA<br>(20)</th>
                            <th>2nd CA<br>(20)</th>
                            <th>Exam<br>(60)</th>
                            <?php if ($term == '3rd Term'): ?>
                                <th>3rd Term<br>Total</th>
                                <th>1st Term</th>
                                <th>2nd Term</th>
                                <th>Cum.<br>Avg</th>
                                <th>Grade</th>
                            <?php else: ?>
                                <th>Total</th>
                                <th>Class<br>Avg</th>
                                <th>Position</th>
                                <th>Grade</th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($results as $row): ?>
                            <?php 
                            $total = ($row['test1'] + $row['test2'] + $row['exam']);
                            $subject = $row['subject'];
                            
                            // Get class average for subject
                            $class_results_subj = sql($DBH, 
                                "SELECT * FROM tbl_student_results 
                                 WHERE class = ? AND term = ? AND year = ? AND subject = ?", 
                                [$myclass, $term, $examyear, $subject], 
                                "rows"
                            );
                            
                            $class_avg_subj = 0;
                            if (!empty($class_results_subj)) {
                                $class_total = 0;
                                foreach ($class_results_subj as $class_row) {
                                    $class_total += ($class_row['test1'] + $class_row['test2'] + $class_row['exam']);
                                }
                                $class_avg_subj = round($class_total / count($class_results_subj), 2);
                            }
                            
                            // Get position for current term/subject
                            $subject_position = $row['position'] ?? 'N/A';
                            
                            // Get previous term results for 3rd Term
                            $second_term_result = '';
                            $first_term_result = '';
                            if ($term == '3rd Term') {
                                // Get 2nd Term result
                                $second_term = sql($DBH, 
                                    "SELECT (test1 + test2 + exam) as total 
                                     FROM tbl_student_results 
                                     WHERE registration_no = ? AND class = ? AND term = '2nd Term' AND year = ? AND subject = ?", 
                                    [$registration_no, $myclass, $examyear, $subject], 
                                    "rows"
                                );
                                $second_term_result = !empty($second_term) ? $second_term[0]['total'] : 'N/A';
                                
                                // Get 1st Term result
                                $first_term = sql($DBH, 
                                    "SELECT (test1 + test2 + exam) as total 
                                     FROM tbl_student_results 
                                     WHERE registration_no = ? AND class = ? AND term = '1st Term' AND year = ? AND subject = ?", 
                                    [$registration_no, $myclass, $examyear, $subject], 
                                    "rows"
                                );
                                $first_term_result = !empty($first_term) ? $first_term[0]['total'] : 'N/A';
                            }
                            
                            // Find grade info for this subject
                            $grade_info_subj = null;
                            foreach ($grade_comments as $grade) {
                                if ($total >= $grade['range'][0] && $total <= $grade['range'][1]) {
                                    $grade_info_subj = $grade;
                                    break;
                                }
                            }
                            $subject_grade = $grade_info_subj ? $grade_info_subj['grade'] : 'N/A';
                            $subject_remark = $grade_info_subj ? $grade_info_subj['remark'] : 'N/A';
                            $grade_class = $subject_grade ? 'grade-' . substr($subject_grade, 0, 1) : '';
                            ?>
                            
                            <tr>
                                <td style="text-align: left;"><?php echo htmlspecialchars($subject); ?></td>
                                <td><?php echo htmlspecialchars($row['test1']); ?></td>
                                <td><?php echo htmlspecialchars($row['test2']); ?></td>
                                <td><?php echo htmlspecialchars($row['exam']); ?></td>
                                <td><?php echo htmlspecialchars($total); ?></td>
                                
                                <?php if ($term == '3rd Term'): ?>
                                    <td><?php echo htmlspecialchars($first_term_result); ?></td>
                                    <td><?php echo htmlspecialchars($second_term_result); ?></td>
                                    <td><?php echo htmlspecialchars($subject_cumulative[$subject]['avg'] ?? 'N/A'); ?></td>
                                    <td><span class="grade-badge <?php echo $grade_class; ?>"><?php echo htmlspecialchars($subject_grade); ?></span></td>
                                <?php else: ?>
                                    <td><?php echo htmlspecialchars($class_avg_subj); ?></td>
                                    <td><?php echo formatPositionBadge($subject_position); ?></td>
                                    <td><span class="grade-badge <?php echo $grade_class; ?>"><?php echo htmlspecialchars($subject_grade); ?></span></td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                
                <!-- Performance Summary -->
                <div class="summary-box">
                    <div class="row">
                        <div class="col-4"><strong>Grand Total:</strong> <?php echo htmlspecialchars($grand_total_current); ?></div>
                        <div class="col-4"><strong>Average Score:</strong> <?php echo htmlspecialchars($average_score); ?>%</div>
                        <div class="col-4"><strong>Grade:</strong> <span class="grade-badge grade-<?php echo substr($cgrade, 0, 1); ?>"><?php echo htmlspecialchars($cgrade); ?></span></div>
                    </div>
                    
                    <?php if ($term == '3rd Term'): ?>
                    <div class="row mt-2">
                        <div class="col-4"><strong>1st Term Avg:</strong> <?php echo htmlspecialchars($cumulative['1st Term']['avg']); ?>%</div>
                        <div class="col-4"><strong>2nd Term Avg:</strong> <?php echo htmlspecialchars($cumulative['2nd Term']['avg']); ?>%</div>
                        <div class="col-4"><strong>3rd Term Avg:</strong> <?php echo htmlspecialchars($cumulative['3rd Term']['avg']); ?>%</div>
                        <div class="col-6 mt-2"><strong>Cumulative Avg:</strong> <?php echo htmlspecialchars($cummulative_avg); ?>%</div>
                        <div class="col-6 mt-2"><strong>Annual Total:</strong> <?php echo htmlspecialchars($grand_total); ?></div>
                        <div class="col-12 mt-2"><strong>Cumulative Position:</strong> <?php echo formatPositionBadge($overall_position, true); ?></div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Skills Assessment (Right) -->
            <div class="skills-assessment">
                <h5 style="text-align: center; color: var(--primary-color); margin-bottom: 15px;">Skills Assessment</h5>
                
                <!-- Psychomotor Skills -->
                <h6 style="color: var(--secondary-color); font-size: 10pt; margin-top: 10px;">Psychomotor Skills</h6>
                <table class="skills-table">
                    <?php foreach ($psychomotor as $skill => $value): ?>
                        <?php if ($value): ?>
                        <tr>
                            <td style="text-align: left;"><?php echo htmlspecialchars($skill); ?></td>
                            <td style="width: 60%;">
                                <div class="progress">
                                    <div class="progress-bar" role="progressbar" style="width: <?php echo ($value/5)*100; ?>%" 
                                         aria-valuenow="<?php echo $value; ?>" aria-valuemin="0" aria-valuemax="5">
                                        <?php echo $value; ?>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </table>
                
                <!-- Affective Traits -->
                <h6 style="color: var(--secondary-color); font-size: 10pt; margin-top: 15px;">Affective Traits</h6>
                <table class="skills-table">
                    <?php foreach ($affective as $skill => $value): ?>
                        <?php if ($value): ?>
                        <tr>
                            <td style="text-align: left;"><?php echo htmlspecialchars($skill); ?></td>
                            <td style="width: 60%;">
                                <div class="progress">
                                    <div class="progress-bar" role="progressbar" style="width: <?php echo ($value/5)*100; ?>%" 
                                         aria-valuenow="<?php echo $value; ?>" aria-valuemin="0" aria-valuemax="5">
                                        <?php echo $value; ?>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </table>
                
                <div style="font-size: 8pt; margin-top: 5px; color: #666;">
                    <strong>Rating Scale:</strong> 5 = Excellent, 4 = Very Good, 3 = Good, 2 = Fair, 1 = Needs Improvement
                </div>
            </div>
        </div>
        
        <!-- Comments Section -->
        <div class="comments-section">
            <img src="stamp.jpg" class="principal-stamp" alt="Principal's Stamp">
            
            <div style="margin-bottom: 15px;">
                <h5 style="color: var(--primary-color); font-size: 11pt;">Class Teacher's Remarks</h5>
                <div style="border: 1px solid #ddd; padding: 8px; min-height: 50px; border-radius: 4px;">
                    <?php echo htmlspecialchars($TeachersRemarks); ?>
                </div>
            </div>
            
            <div>
                <h5 style="color: var(--primary-color); font-size: 11pt;">HOS' Comments</h5>
                <div style="border: 1px solid #ddd; padding: 8px; min-height: 50px; border-radius: 4px;">
                    <?php echo htmlspecialchars($htcomments); ?>
                </div>
            </div>
            
            <div style="text-align: right; margin-top: 30px;">
                <div style="display: inline-block; text-align: center;">
                    <div style="border-top: 1px solid #000; width: 150px; margin-bottom: 5px;"></div>
                    <div>Principal's Signature</div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Print Button -->
    <div class="no-print text-center mt-3">
        <button class="btn btn-primary" onclick="window.print()" style="background-color: var(--primary-color);">
            <i class="fas fa-print me-2"></i> Print Now
        </button>
        <a href="my_results.php?myreg=<?php echo urlencode($registration_no); ?>&myclass=<?php echo urlencode($myclass); ?>&term=<?php echo urlencode($term); ?>&examyear=<?php echo urlencode($examyear); ?>" class="btn btn-secondary ms-2">
            <i class="fas fa-arrow-left me-2"></i> Back to Full View
        </a>
    </div>
    
    <script>
        // Auto-print when page loads (optional)
        window.onload = function() {
            // Uncomment the next line if you want the print dialog to open automatically
            // window.print();
        };
    </script>
</body>
</html>