<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/dbconfig4.php'); // Add central settings
require_once('source/function.php');
require_once('source/restrict_admin.php');

// Get current branch settings from central database
$branchCode = getCurrentBranchCode();
$branchSettings = getSchoolSettings($branchCode);

if ($branchSettings) {
    $schoolName = $branchSettings['branch_name'];
    $schoolAddress = $branchSettings['branch_address'];
    $schoolShortName = $branchSettings['branch_short_name'];
    $schoolMotto = $branchSettings['school_motto'];
    $schoolLogo = $branchSettings['school_logo_path'];
    $schoolPhone = $branchSettings['contact_phone'];
    $schoolEmail = $branchSettings['contact_email'];
    $footerText = $branchSettings['footer_text'];
    $footerCopyright = $branchSettings['footer_copyright'];
} else {
    // Fallback values if no branch settings found
    $schoolName = "Verbum Dei International College";
    $schoolAddress = "";
    $schoolShortName = "VDIC";
    $schoolMotto = "Achieving Excellence Together";
    $schoolLogo = "coll_logo.jpg";
    $schoolPhone = "+234 803 292 9756";
    $schoolEmail = "info@vda.com.ng";
    $footerText = "Achieving Excellence Together";
    $footerCopyright = "Copyright © Verbum Dei International College";
}

// Get system-wide settings
$supportPhone = getSystemSetting('support_phone') ?: $schoolPhone;
$supportEmail = getSystemSetting('support_email') ?: $schoolEmail;
$developerName = getSystemSetting('developer_name') ?: 'DataSwift Coders';
$developerWebsite = getSystemSetting('developer_website') ?: 'https://dataswift.com.ng';

// Initialize message variable
$msg = '';
if (isset($_GET['msg'])) {
    $messages = [
        'refered' => "<div class='alert alert-success'>Referred successfully</div>",
        'failed' => "<div class='alert alert-warning'>Something went wrong, please try again</div>",
    ];
    $msg = $messages[$_GET['msg']] ?? '';
}

if (isset($_SESSION['msg']) && $_SESSION['msg'] == "update") {
    $msg = "<div class='alert alert-success text-center'>Order Update Successful. Customer will receive email. <a href='new_order.php' class='btn btn-sm btn-outline-success'>Refresh</a></div>";
    unset($_SESSION['msg']);
}

// 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>");
}

// 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';

// Set profile picture path
if ($user_profile_pic == 'default' || empty($user_profile_pic) || !file_exists('profile_pic/' . $user_profile_pic)) {
    $profile_pic = "<img class='img-fluid rounded-circle profile-pic' width='100' src='../coll_admin/profile/profile.jpg' alt='Profile'>";
} else {
    $profile_pic = "<img class='img-fluid rounded-circle profile-pic' width='100' src='profile_pic/$user_profile_pic?t=" . time() . "' alt='Profile'>";
}

// Calculate age - Fixing the mktime() error
$age = '';
if (!empty($user_age)) {
    // Handle different date formats (assuming format could be Y-m-d or m/d/Y)
    if (strpos($user_age, '/') !== false) {
        // For dates in m/d/Y format
        $birthDate = explode('/', $user_age);
        $month = (int)$birthDate[0];
        $day = (int)$birthDate[1];
        $year = (int)$birthDate[2];
    } elseif (strpos($user_age, '-') !== false) {
        // For dates in Y-m-d format
        $birthDate = explode('-', $user_age);
        $year = (int)$birthDate[0];
        $month = (int)$birthDate[1];
        $day = (int)$birthDate[2];
    } else {
        // Invalid date format
        $month = 1;
        $day = 1;
        $year = 2000;
    }

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

    $age = $currentYear - $year;
    
    // Adjust if birthday hasn't occurred yet this year
    if ($currentMonth < $month || ($currentMonth == $month && $currentDay < $day)) {
        $age--;
    }
} else {
    $age = 'N/A';
}

// Fetch result summary
error_log("Count Student Query Params: myclass='$myclass', term='$term', examyear='$examyear'");
try {
    $stmt = $DBH->prepare("SELECT COUNT(DISTINCT registration_no) AS student_count FROM tbl_student_results WHERE TRIM(class) = ? AND TRIM(term) = ? AND TRIM(year) = ?");
    $stmt->execute([$myclass, $term, $examyear]);
    $count_student = (int)$stmt->fetchColumn();
    error_log("Number in Class for $myclass, $term, $examyear: $count_student");
} catch (PDOException $e) {
    error_log("Error counting students: " . $e->getMessage());
    $count_student = 0;
}
if ($count_student === 0) {
    error_log("Warning: No students found for class='$myclass', term='$term', year='$examyear'");
}

// Fetch all results for the student
$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);
}

// Calculate class average
$class_results = sql($DBH, "SELECT * FROM tbl_student_results WHERE class = ? AND term = ? AND year = ?", [$myclass, $term, $examyear], "rows");
if (empty($class_results)) {
    $class_avg = 0;
    $min_score = 0;
    $max_score = 0;
} else {
    $class_total_sum = 0;
    $scores = [];
    foreach ($class_results as $row) {
        $total = ($row['test1'] + $row['test2'] + $row['exam']);
        $class_total_sum += $total;
        $scores[] = $total;
    }
    $class_avg = round($class_total_sum / count($class_results), 2);
    $min_score = min($scores);
    $max_score = max($scores);
}

// 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 = []; // To store position information

foreach ($terms as $t) {
    // Get term totals and averages
    $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'
    ];

    // Get position data for each term
    $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';

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

if ($term == '3rd Term') {
    // Get cumulative averages and positions per subject
    foreach ($results as $row) {
        $subject = $row['subject'];
        
        // Get all three terms' data for this 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"
        );
        
        // Calculate cumulative average
        $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' // Show best position
        ];
    }
    
    // Get overall cumulative position in class
    $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 '<span class="badge bg-secondary">N/A</span>';
    }
    
    $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 = '';
    $icon = '';
    
    if ($position == 1) {
        $badge_class = 'bg-warning text-dark';
        $icon = '<i class="fas fa-crown me-1"></i>';
    } elseif ($position == 2) {
        $badge_class = 'bg-secondary';
        $icon = '<i class="fas fa-medal me-1"></i>';
    } elseif ($position == 3) {
        $badge_class = 'bg-info text-dark';
        $icon = '<i class="fas fa-medal me-1"></i>';
    } elseif ($position <= 10) {
        $badge_class = 'bg-success';
        $icon = '<i class="fas fa-star me-1"></i>';
    } else {
        $badge_class = 'bg-primary';
        $icon = '<i class="fas fa-user me-1"></i>';
    }
    
    return "<span class='badge $badge_class p-2'>$icon $position_text</span>";
}

// Get admin full name for display
$admin_fullname = '';
$rows = sql($DBH, "SELECT fullname FROM tbl_admin WHERE status = ?", ["Active"], "rows");
if(!empty($rows)) {
    $admin_fullname = $rows[0]['fullname'];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $schoolName; ?> - Student Result</title>
    <!-- Bootstrap 5 CDN -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome CDN -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&family=Playfair+Display:wght@700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-blue: #1a4b8c;
            --secondary-gold: #FFD700;
            --dark-blue: #0f2b4f;
            --light-blue: #4a7db5;
            --light-gold: #FFF1B8;
            --success-green: #2e7d32;
            --warning-orange: #ff8f00;
            --danger-red: #c62828;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background-color: #f8f9fa;
            color: #333;
            padding: 0;
            margin: 0;
        }
        
        /* Header Styles */
        .header {
            background: linear-gradient(135deg, var(--primary-blue) 0%, var(--dark-blue) 100%);
            color: white;
            padding: 1.5rem 0;
            margin-bottom: 2rem;
            border-bottom: 3px solid var(--secondary-gold);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        
        .school-logo {
            border: 3px solid var(--secondary-gold);
            border-radius: 50%;
            padding: 5px;
            background: white;
        }
        
        .school-name {
            font-family: 'Playfair Display', serif;
            font-weight: 700;
            font-size: 2.2rem;
            margin-bottom: 0.5rem;
            color: white;
        }
        
        .school-motto {
            font-style: italic;
            opacity: 0.9;
            font-size: 1rem;
            color: var(--secondary-gold);
        }
        
        .report-title {
            background: rgba(255,255,255,0.1);
            display: inline-block;
            padding: 0.5rem 2rem;
            border-radius: 50px;
            margin-top: 1rem;
            border: 2px solid var(--secondary-gold);
            font-weight: 600;
        }
        
        /* Card Styles */
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(26, 75, 140, 0.1);
            margin-bottom: 1.5rem;
            border: 1px solid rgba(255, 215, 0, 0.2);
            transition: all 0.3s ease;
        }
        
        .card:hover {
            box-shadow: 0 8px 20px rgba(26, 75, 140, 0.15);
            border-color: var(--secondary-gold);
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--primary-blue) 0%, var(--dark-blue) 100%);
            color: white;
            font-weight: 600;
            border-radius: 15px 15px 0 0 !important;
            padding: 1rem 1.5rem;
            border-bottom: 2px solid var(--secondary-gold);
        }
        
        .card-header i {
            color: var(--secondary-gold);
            margin-right: 8px;
        }
        
        .profile-pic {
            border: 4px solid var(--secondary-gold);
            box-shadow: 0 4px 10px rgba(0,0,0,0.2);
            width: 120px;
            height: 120px;
            object-fit: cover;
        }
        
        /* Table Styles */
        .table {
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 0;
        }
        
        .table thead th {
            background: linear-gradient(135deg, var(--light-blue), var(--primary-blue));
            color: white;
            font-weight: 600;
            border-bottom: 2px solid var(--secondary-gold);
            text-align: center;
            vertical-align: middle;
            padding: 12px;
        }
        
        .table tbody td {
            vertical-align: middle;
            padding: 10px;
            text-align: center;
        }
        
        .table tbody tr:hover {
            background-color: var(--light-gold);
        }
        
        /* Grade Badges */
        .badge-grade {
            font-size: 0.85rem;
            padding: 0.4rem 0.8rem;
            border-radius: 50px;
            font-weight: 600;
            display: inline-block;
            min-width: 45px;
        }
        
        .grade-A, .grade-A\+ { background: linear-gradient(135deg, #2e7d32, #1b5e20); color: white; }
        .grade-B, .grade-B\+ { background: linear-gradient(135deg, #689f38, #558b2f); color: white; }
        .grade-C, .grade-C\+ { background: linear-gradient(135deg, #ff8f00, #ff6f00); color: white; }
        .grade-D { background: linear-gradient(135deg, #ef6c00, #e65100); color: white; }
        .grade-F { background: linear-gradient(135deg, #c62828, #b71c1c); color: white; }
        
        /* Progress Bars */
        .progress {
            height: 20px;
            border-radius: 10px;
            background-color: #e9ecef;
            margin: 5px 0;
        }
        
        .progress-bar {
            background: linear-gradient(90deg, var(--primary-blue), var(--light-blue));
            border-radius: 10px;
            color: white;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        /* Position Badges */
        .position-badge {
            font-size: 0.9rem;
            padding: 0.5rem 1rem;
            border-radius: 50px;
            font-weight: 600;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            display: inline-block;
        }
        
        .bg-warning.text-dark { background: linear-gradient(135deg, #FFD700, #D4AF37) !important; }
        .bg-secondary { background: linear-gradient(135deg, #C0C0C0, #A8A8A8) !important; }
        .bg-info.text-dark { background: linear-gradient(135deg, #CD7F32, #A67C52) !important; }
        .bg-success { background: linear-gradient(135deg, #4CAF50, #2E7D32) !important; }
        .bg-primary { background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue)) !important; }
        
        /* Comments Section */
        .comment-box {
            background: linear-gradient(135deg, #f8f9fa, #ffffff);
            padding: 1rem;
            border-radius: 10px;
            border-left: 4px solid var(--secondary-gold);
            margin-bottom: 1rem;
        }
        
        .comment-box h5 {
            color: var(--dark-blue);
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .signature-area {
            border: 2px dashed var(--secondary-gold);
            padding: 1.5rem;
            border-radius: 15px;
            background: linear-gradient(135deg, #fff9e6, #ffffff);
        }
        
        /* Print Button */
        .btn-print {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
            font-weight: 600;
            padding: 0.8rem 2rem;
            border-radius: 50px;
            border: 2px solid var(--secondary-gold);
            transition: all 0.3s ease;
            font-size: 1.1rem;
        }
        
        .btn-print:hover {
            background: linear-gradient(135deg, var(--secondary-gold), #e6b800);
            color: var(--dark-blue);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(255,215,0,0.3);
        }
        
        /* Footer */
        .footer {
            background: linear-gradient(135deg, var(--dark-blue), var(--primary-blue));
            color: white;
            padding: 1.5rem 0;
            margin-top: 3rem;
            border-top: 3px solid var(--secondary-gold);
        }
        
        .footer a {
            color: var(--secondary-gold);
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .footer a:hover {
            color: white;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .school-name {
                font-size: 1.5rem;
            }
            .profile-pic {
                width: 100px;
                height: 100px;
            }
            .table thead th {
                font-size: 0.85rem;
                padding: 8px;
            }
            .table tbody td {
                font-size: 0.85rem;
                padding: 6px;
            }
        }
        
        /* Print Styles */
        @media print {
            body {
                background-color: white;
                font-size: 10pt;
                padding: 0.5cm;
            }
            
            .no-print {
                display: none !important;
            }
            
            .header {
                background: var(--primary-blue) !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
                color: white;
                padding: 0.8cm 0;
                margin: 0;
            }
            
            .card {
                box-shadow: none;
                border: 1px solid #ddd;
                page-break-inside: avoid;
            }
            
            .card-header {
                background: var(--primary-blue) !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
                color: white;
            }
            
            .badge, .progress-bar, .position-badge {
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .table thead th {
                background: var(--light-blue) !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .grade-A, .grade-A\+ { background: #2e7d32 !important; }
            .grade-B, .grade-B\+ { background: #689f38 !important; }
            .grade-C, .grade-C\+ { background: #ff8f00 !important; }
            .grade-D { background: #ef6c00 !important; }
            .grade-F { background: #c62828 !important; }
            
            @page {
                size: A4;
                margin: 1cm;
            }
            
            a {
                text-decoration: none;
                color: black;
            }
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="header text-center no-print">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-3 text-md-end">
                    <?php if ($schoolLogo && file_exists('../' . $schoolLogo)): ?>
                        <img src="../<?php echo $schoolLogo; ?>" alt="School Logo" height="80" class="school-logo">
                    <?php endif; ?>
                </div>
                <div class="col-md-6">
                    <h1 class="school-name"><?php echo htmlspecialchars($schoolName); ?></h1>
                    <p class="school-motto"><?php echo htmlspecialchars($schoolMotto); ?></p>
                    <div class="report-title">
                        <i class="fas fa-certificate me-2" style="color: var(--secondary-gold);"></i>
                        STUDENT ACADEMIC REPORT
                    </div>
                </div>
                <div class="col-md-3 text-md-start">
                    <img src="datalogo.png" alt="DataSwift" height="40" class="bg-white p-2 rounded" onerror="this.style.display='none';">
                </div>
            </div>
        </div>
    </div>

    <!-- Print Header (appears only in print) -->
    <div class="print-header text-center d-none" style="display: none !important;">
        <h1><?php echo htmlspecialchars($schoolName); ?></h1>
        <h3>Student Academic Report</h3>
    </div>

    <!-- Main Content -->
    <div class="container">
        <?php if ($msg) echo $msg; ?>
        
        <!-- Student Info Card -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-user-graduate"></i> Student Information
            </div>
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-md-2 text-center">
                        <?php echo $profile_pic; ?>
                    </div>
                    <div class="col-md-10">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <div class="border-start border-3 border-warning ps-3">
                                    <small class="text-muted">Full Name</small>
                                    <h6 class="mb-0 fw-bold"><?php echo htmlspecialchars($user_name); ?></h6>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="border-start border-3 border-warning ps-3">
                                    <small class="text-muted">Reg Number</small>
                                    <h6 class="mb-0 fw-bold"><?php echo htmlspecialchars($registration_no); ?></h6>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="border-start border-3 border-warning ps-3">
                                    <small class="text-muted">Gender</small>
                                    <h6 class="mb-0 fw-bold"><?php echo htmlspecialchars($user_gender); ?></h6>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="border-start border-3 border-warning ps-3">
                                    <small class="text-muted">Age</small>
                                    <h6 class="mb-0 fw-bold"><?php echo $age; ?> Years</h6>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="border-start border-3 border-warning ps-3">
                                    <small class="text-muted">Class</small>
                                    <h6 class="mb-0 fw-bold"><?php echo htmlspecialchars($myclass); ?></h6>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="border-start border-3 border-warning ps-3">
                                    <small class="text-muted">Term</small>
                                    <h6 class="mb-0 fw-bold"><?php echo htmlspecialchars($term); ?></h6>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="border-start border-3 border-warning ps-3">
                                    <small class="text-muted">Session</small>
                                    <h6 class="mb-0 fw-bold"><?php echo htmlspecialchars($examyear); ?></h6>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="border-start border-3 border-warning ps-3">
                                    <small class="text-muted">Class Size</small>
                                    <h6 class="mb-0 fw-bold"><?php echo $count_student; ?></h6>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Performance Summary Cards -->
        <div class="row g-3 mb-4">
            <div class="col-md-3">
                <div class="card bg-primary text-white h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-white-50">Student Avg</h6>
                                <h3 class="text-white"><?php echo $average_score; ?>%</h3>
                            </div>
                            <i class="fas fa-chart-line fa-3x opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-white-50">Class Avg</h6>
                                <h3 class="text-white"><?php echo $class_avg; ?>%</h3>
                            </div>
                            <i class="fas fa-users fa-3x opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-dark h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-dark-50">Grade</h6>
                                <h3 class="text-dark"><?php echo $cgrade; ?></h3>
                            </div>
                            <i class="fas fa-star fa-3x opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-white-50">Remark</h6>
                                <h6 class="text-white"><?php echo $cgradeR; ?></h6>
                            </div>
                            <i class="fas fa-comment fa-3x opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Attendance Card -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-calendar-check"></i> Attendance Record
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-2">
                        <div class="text-center p-2 bg-light rounded">
                            <h3 class="text-primary mb-0"><?php echo $SchOpen; ?></h3>
                            <small>School Days</small>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="text-center p-2 bg-light rounded">
                            <h3 class="text-success mb-0"><?php echo $Present; ?></h3>
                            <small>Present</small>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="text-center p-2 bg-light rounded">
                            <h3 class="text-danger mb-0"><?php echo $Absent; ?></h3>
                            <small>Absent</small>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="text-center p-2 bg-light rounded">
                            <h3 class="text-info mb-0"><?php echo $SchOpen > 0 ? round(($Present/$SchOpen)*100, 1) : 0; ?>%</h3>
                            <small>Attendance</small>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="text-center p-2 bg-light rounded">
                            <h6 class="mb-0"><?php echo htmlspecialchars($DateOfReport); ?></h6>
                            <small>Term Ends</small>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="text-center p-2 bg-light rounded">
                            <h6 class="mb-0"><?php echo htmlspecialchars($NextTermBegins); ?></h6>
                            <small>Next Term</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Results Table -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-poll"></i> Academic Performance - <?php echo strtoupper(htmlspecialchars($term)); ?>, <?php echo htmlspecialchars($examyear); ?>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>Subject</th>
                                <th>CA1<br><small>(20)</small></th>
                                <th>CA2<br><small>(20)</small></th>
                                <th>Exam<br><small>(60)</small></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>
                                    <th>Remark</th>
                                <?php else: ?>
                                    <th>Total<br><small>(100)</small></th>
                                    <th>Class<br>Avg</th>
                                    <th>Position</th>
                                    <th>Grade</th>
                                    <th>Remark</th>
                                <?php endif; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            foreach ($results as $row) {
                                $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'] : '—';
                                    
                                    // 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'] : '—';
                                }
                                
                                // 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) : '';

                                echo "<tr>
                                    <td class='text-start fw-bold'>" . htmlspecialchars($subject) . "</td>
                                    <td>" . htmlspecialchars($row['test1']) . "</td>
                                    <td>" . htmlspecialchars($row['test2']) . "</td>
                                    <td>" . htmlspecialchars($row['exam']) . "</td>
                                    <td><strong>" . htmlspecialchars($total) . "</strong></td>";
                                    
                                if ($term == '3rd Term') {
                                    $cum_avg = $subject_cumulative[$subject]['avg'] ?? 'N/A';
                                    $cum_avg_display = is_numeric($cum_avg) ? $cum_avg : '—';
                                    
                                    echo "<td>" . htmlspecialchars($first_term_result) . "</td>
                                          <td>" . htmlspecialchars($second_term_result) . "</td>
                                          <td><strong>" . htmlspecialchars($cum_avg_display) . "</strong></td>
                                          <td><span class='badge-grade $grade_class'>" . htmlspecialchars($subject_grade) . "</span></td>
                                          <td>" . htmlspecialchars($subject_remark) . "</td>";
                                } else {
                                    echo "<td>" . htmlspecialchars($class_avg_subj) . "</td>
                                          <td class='position-cell'>" . formatPositionBadge($subject_position) . "</td>
                                          <td><span class='badge-grade $grade_class'>" . htmlspecialchars($subject_grade) . "</span></td>
                                          <td>" . htmlspecialchars($subject_remark) . "</td>";
                                }
                                
                                echo "</tr>";
                            }
                            ?>
                        </tbody>
                        <tfoot class="table-light">
                            <tr>
                                <td colspan="<?php echo ($term == '3rd Term') ? '6' : '6'; ?>" class="text-end fw-bold">Totals / Averages:</td>
                                <td class="fw-bold"><?php echo $grand_total_current; ?></td>
                                <?php if ($term == '3rd Term'): ?>
                                    <td></td>
                                    <td></td>
                                    <td class="fw-bold"><?php echo $cummulative_avg; ?></td>
                                    <td></td>
                                    <td></td>
                                <?php else: ?>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                <?php endif; ?>
                            </tr>
                        </tfoot>
                    </table>
                </div>
                
                <?php if ($term == '3rd Term'): ?>
                <div class="row mt-4">
                    <div class="col-md-12">
                        <div class="alert alert-info">
                            <div class="row">
                                <div class="col-md-3">
                                    <strong>1st Term Avg:</strong> <?php echo $cumulative['1st Term']['avg']; ?>%
                                    <?php if ($position_data['1st Term'] != 'N/A'): ?>
                                        <?php echo formatPositionBadge($position_data['1st Term']); ?>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <strong>2nd Term Avg:</strong> <?php echo $cumulative['2nd Term']['avg']; ?>%
                                    <?php if ($position_data['2nd Term'] != 'N/A'): ?>
                                        <?php echo formatPositionBadge($position_data['2nd Term']); ?>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <strong>3rd Term Avg:</strong> <?php echo $cumulative['3rd Term']['avg']; ?>%
                                    <?php if ($position_data['3rd Term'] != 'N/A'): ?>
                                        <?php echo formatPositionBadge($position_data['3rd Term']); ?>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <strong>Cumulative Position:</strong> 
                                    <?php echo formatPositionBadge($overall_position, true); ?>
                                    <small>of <?php echo $count_student; ?></small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Skills Assessment -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-brain"></i> Skills Assessment
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <h5 class="text-center mb-3"><i class="fas fa-running me-2" style="color: var(--secondary-gold);"></i> Psychomotor Skills</h5>
                        <table class="table table-bordered">
                            <?php 
                            $has_psychomotor = false;
                            foreach ($psychomotor as $skill => $value): 
                                if ($value): 
                                    $has_psychomotor = true;
                            ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($skill); ?></td>
                                    <td 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; ?>/5
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            <?php 
                                endif; 
                            endforeach; 
                            if (!$has_psychomotor):
                                echo '<tr><td colspan="2" class="text-center text-muted">No psychomotor skills recorded</td></tr>';
                            endif;
                            ?>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h5 class="text-center mb-3"><i class="fas fa-heart me-2" style="color: var(--secondary-gold);"></i> Affective Traits</h5>
                        <table class="table table-bordered">
                            <?php 
                            $has_affective = false;
                            foreach ($affective as $skill => $value): 
                                if ($value): 
                                    $has_affective = true;
                            ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($skill); ?></td>
                                    <td 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; ?>/5
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            <?php 
                                endif; 
                            endforeach; 
                            if (!$has_affective):
                                echo '<tr><td colspan="2" class="text-center text-muted">No affective traits recorded</td></tr>';
                            endif;
                            ?>
                        </table>
                    </div>
                </div>
                <div class="alert alert-info mt-3 mb-0">
                    <i class="fas fa-info-circle me-2" style="color: var(--secondary-gold);"></i>
                    <strong>Rating Scale:</strong> 5 = Excellent, 4 = Very Good, 3 = Good, 2 = Fair, 1 = Needs Improvement
                </div>
            </div>
        </div>

        <!-- Comments -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-comments"></i> Comments & Recommendations
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="comment-box">
                            <h5><i class="fas fa-chalkboard-teacher me-2" style="color: var(--secondary-gold);"></i>Class Teacher's Remarks</h5>
                            <p class="mb-0"><?php echo htmlspecialchars($TeachersRemarks ?: 'No comment provided.'); ?></p>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="comment-box">
                            <h5><i class="fas fa-user-tie me-2" style="color: var(--secondary-gold);"></i>Principal's Comments</h5>
                            <p class="mb-0"><?php echo htmlspecialchars($htcomments); ?></p>
                        </div>
                    </div>
                </div>
                
                <div class="signature-area text-center mt-4">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-2"><strong>Class Teacher</strong></div>
                            <div class="border-top d-inline-block pt-2 px-5">Signature & Date</div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-2"><strong>Principal</strong></div>
                            <div class="border-top d-inline-block pt-2 px-5">Signature & Date</div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-2"><strong>School Seal</strong></div>
                            <div class="border p-3 d-inline-block rounded">
                                <i class="fas fa-stamp fa-2x" style="color: var(--secondary-gold);"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Print Button -->
        <div class="text-center no-print my-5">
            <button class="btn-print" onclick="window.print()">
                <i class="fas fa-print me-2"></i> Print / Download Result
            </button>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer no-print">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <p class="mb-0">
                        <i class="fas fa-copyright me-1" style="color: var(--secondary-gold);"></i>
                        <?php echo $footerCopyright; ?> <?php echo date("Y"); ?>
                    </p>
                </div>
                <div class="col-md-6 text-md-end">
                    <a href="<?php echo $developerWebsite; ?>" target="_blank" class="powered-by-link">
                        <span>Powered by <?php echo $developerName; ?></span>
                        <img src="datalogo.png" alt="<?php echo $developerName; ?>" height="30" class="ms-2" style="filter: brightness(0) invert(1);" onerror="this.style.display='none';">
                    </a>
                </div>
            </div>
        </div>
    </footer>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Auto-hide alerts after 5 seconds
        setTimeout(function() {
            document.querySelectorAll('.alert').forEach(function(alert) {
                alert.style.transition = 'opacity 0.5s';
                alert.style.opacity = '0';
                setTimeout(function() {
                    alert.remove();
                }, 500);
            });
        }, 5000);
    </script>
</body>
</html>