<?php
include('config.php');
include('includes/user_data.php');

// Check if session variables are set
if (!isset($_SESSION['ad_no'], $_SESSION['classes'], $_SESSION['session'], $_SESSION['term'])) {
    echo "<script>alert('Please select student details first'); window.location.href='end_term_report.php';</script>";
    exit();
}

// Function to generate comment based on percentage
function generateSubjectComment($percentage) {
    if ($percentage >= 80) {
        return "Excellent (A1)";
    } elseif ($percentage >= 70) {
        return "Very Good (B2)";
    } elseif ($percentage >= 60) {
        return "Good (B3)";
    } elseif ($percentage >= 50) {
        return "Credit (C)";
    } elseif ($percentage >= 45) {
        return "Pass (D)";
    } else {
        return "Fail (F)";
    }
}

function generateOverallComment($percentage) {
    if ($percentage >= 80) {
        return "Excellent performance. Keep it up!";
    } elseif ($percentage >= 70) {
        return "Very good performance.";
    } elseif ($percentage >= 60) {
        return "Good performance. Room for improvement.";
    } elseif ($percentage >= 50) {
        return "Average performance. Needs to work harder.";
    } elseif ($percentage >= 40) {
        return "Below average. Requires serious attention.";
    } else {
        return "Poor performance. Needs immediate intervention.";
    }
}

// Fetch student data
$ad_no = $_SESSION['ad_no'];
$class_id = $_SESSION['classes'];
$session = $_SESSION['session'];
$term = $_SESSION['term'];

try {
    // Get student details
    $stmt = $dbh->prepare("SELECT * FROM students WHERE Admission_num = :ad_no");
    $stmt->bindParam(':ad_no', $ad_no);
    $stmt->execute();
    $student = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$student) {
        throw new Exception("Student not found");
    }
    
    // Get class name
    $stmt = $dbh->prepare("SELECT name FROM classes WHERE id = :class_id");
    $stmt->bindParam(':class_id', $class_id);
    $stmt->execute();
    $class = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Get term name
    $stmt = $dbh->prepare("SELECT term_name FROM terms WHERE id = :term");
    $stmt->bindParam(':term', $term);
    $stmt->execute();
    $term_data = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Get session year
    $stmt = $dbh->prepare("SELECT session_year FROM sessions WHERE id = :session");
    $stmt->bindParam(':session', $session);
    $stmt->execute();
    $session_data = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Get report data
    $stmt = $dbh->prepare("
        SELECT er.*, s.name as subject_name 
        FROM end_term_report er 
        JOIN Subjects s ON er.subject = s.id 
        WHERE er.Admission_no = :ad_no 
        AND er.classes = :class_id 
        AND er.session = :session 
        AND er.term = :term
    ");
    $stmt->bindParam(':ad_no', $ad_no);
    $stmt->bindParam(':class_id', $class_id);
    $stmt->bindParam(':session', $session);
    $stmt->bindParam(':term', $term);
    $stmt->execute();
    $report_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Calculate totals and averages
    $total_marks = 0;
    $total_percentage = 0;
    $subject_count = count($report_data);
    
    foreach ($report_data as $subject) {
        $total_marks += $subject['total'];
        $total_percentage += $subject['total']; // Total is already out of 100
    }
    
    $average_percentage = $subject_count > 0 ? $total_percentage / $subject_count : 0;
    $overall_comment = generateOverallComment($average_percentage);
    
} catch (Exception $e) {
    $error = "Error: " . $e->getMessage();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Terminal Report Card</title>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- html2canvas for image download -->
    <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
    
    <!-- jsPDF for PDF download -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    
    <style>
        @media print {
            body * {
                visibility: hidden;
            }
            #report-card, #report-card * {
                visibility: visible;
            }
            #report-card {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
            }
            .no-print {
                display: none !important;
            }
        }
        
        .watermark {
            position: relative;
        }
        
        .watermark::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-image: url('assets/images/logo-icon.png'); /* Update with your logo path */
            background-repeat: repeat;
            background-size: 200px 200px;
            opacity: 0.1;
            z-index: -1;
        }
        
        .subject-row:nth-child(even) {
            background-color: #f9fafb;
        }
        
        .subject-row:hover {
            background-color: #f3f4f6;
        }
        
        /* Color coding for grades */
        .grade-excellent { color: #059669; font-weight: bold; }
        .grade-very-good { color: #10b981; font-weight: bold; }
        .grade-good { color: #3b82f6; font-weight: bold; }
        .grade-credit { color: #f59e0b; font-weight: bold; }
        .grade-pass { color: #d97706; font-weight: bold; }
        .grade-fail { color: #dc2626; font-weight: bold; }
    </style>
</head>
<body class="bg-gray-100">
    <div class="container mx-auto p-4">
        <!-- Action Buttons -->
        <div class="flex justify-end space-x-4 mb-4 no-print">
            <button onclick="window.print()" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
                Print Report
            </button>
            <button onclick="downloadAsJPG()" class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
                Download as JPG
            </button>
            <button onclick="downloadAsPDF()" class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">
                Download as PDF
            </button>
            <a href="end_of_term_result.php" class="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded">
                Back
            </a>
        </div>
        
        <?php if (isset($error)): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                <span class="block sm:inline"><?php echo $error; ?></span>
            </div>
        <?php else: ?>
        
        <!-- Report Card -->
        <div id="report-card" class="bg-white shadow-lg rounded-lg overflow-hidden watermark">
            <!-- Header with School Logo and Info -->
            <div class="bg-blue-800 text-white p-6">
                <div class="flex justify-between items-center">
                    <div class="flex items-center">
                        <!-- School Logo - Update path as needed -->
                        <img src="assets/images/logo-icon.png" alt="School Logo" class="h-20 w-20 mr-4">
                        <div>
                            <h1 class="text-2xl font-bold">PENUEL COLLEGE</h1>
                            <p class="text-sm">Address:  Ibadan Oyo state</p>
                            <p class="text-sm"> Email: info@penuel.com.ng</p>
                        </div>
                    </div>
                    <div class="text-right">
                        <h2 class="text-xl font-semibold">TERMINAL REPORT CARD</h2>
                        <p class="text-sm">Academic Session: <?php echo htmlspecialchars($session_data['session_year'] ?? ''); ?></p>
                    </div>
                </div>
            </div>
            
            <!-- Student Information -->
            <div class="p-6 border-b">
                <div class="grid grid-cols-3 gap-4">
                    <div>
                        <p><strong>Student Name:</strong> <?php echo htmlspecialchars($student['name'] ?? ''); ?></p>
                        <p><strong>Class:</strong> <?php echo htmlspecialchars($class['name'] ?? ''); ?></p>
                    </div>
                    <div>
                        <p><strong>Admission No:</strong> <?php echo htmlspecialchars($ad_no); ?></p>
                        <p><strong>Term:</strong> <?php echo htmlspecialchars($term_data['term_name'] ?? ''); ?></p>
                    </div>
                    <div class="flex justify-end">
                        <!-- Student Photo - Update path as needed -->
                        <img src="<?php echo !empty($student['image']) ? '../staff/'.$student['image'] : 'assets/images/default-avatar.png'; ?>" 
                             alt="Student Photo" class="h-24 w-24 rounded-full border-2 border-gray-300">
                    </div>
                </div>
            </div>
            
            <!-- Report Name -->
            <div class="p-4 bg-gray-100 border-b">
                <h3 class="text-xl font-bold text-center text-blue-800">ACADEMIC PERFORMANCE REPORT</h3>
            </div>
            
            <!-- Subjects Table -->
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">S/N</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Subjects</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">CA Test</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Exam Score</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Total (100)</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">% Total</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Comment</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php if (count($report_data) > 0): ?>
                            <?php $counter = 1; ?>
                            <?php foreach ($report_data as $subject): 
                                $percentage = $subject['total'];
                                $comment = generateSubjectComment($percentage);
                                $grade_class = '';
                                if ($percentage >= 80) $grade_class = 'grade-excellent';
                                elseif ($percentage >= 70) $grade_class = 'grade-very-good';
                                elseif ($percentage >= 60) $grade_class = 'grade-good';
                                elseif ($percentage >= 50) $grade_class = 'grade-credit';
                                elseif ($percentage >= 45) $grade_class = 'grade-pass';
                                else $grade_class = 'grade-fail';
                            ?>
                                <tr class="subject-row">
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo $counter++; ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?php echo htmlspecialchars($subject['subject_name']); ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo htmlspecialchars($subject['ca_test']); ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo htmlspecialchars($subject['exam_score']); ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo htmlspecialchars($subject['total']); ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo htmlspecialchars($subject['total']); ?>%</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm <?php echo $grade_class; ?>"><?php echo $comment; ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-center">No report data available for this term.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Grading Legend -->
            <div class="p-4 bg-gray-50 border-t">
                <h4 class="font-bold text-lg mb-2">Grading System</h4>
                <div class="grid grid-cols-3 gap-2 text-sm">
                    <div class="flex items-center">
                        <span class="grade-excellent mr-2">●</span>
                        <span>80-100%: Excellent</span>
                    </div>
                    <div class="flex items-center">
                        <span class="grade-very-good mr-2">●</span>
                        <span>70-79%: Very Good</span>
                    </div>
                    <div class="flex items-center">
                        <span class="grade-good mr-2">●</span>
                        <span>60-69%: Good</span>
                    </div>
                    <div class="flex items-center">
                        <span class="grade-credit mr-2">●</span>
                        <span>50-59%: Credit</span>
                    </div>
                    <div class="flex items-center">
                        <span class="grade-pass mr-2">●</span>
                        <span>45-49%: Pass</span>
                    </div>
                    <div class="flex items-center">
                        <span class="grade-fail mr-2">●</span>
                        <span>Below 45%: Fail</span>
                    </div>
                </div>
            </div>
            
            <!-- Summary and Overall Comment -->
            <div class="p-6 bg-gray-50 border-t">
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <h4 class="font-bold text-lg mb-2">Performance Summary</h4>
                        <p><strong>Total Subjects:</strong> <?php echo $subject_count; ?></p>
                        <p><strong>Total Marks:</strong> <?php echo $total_marks; ?></p>
                        <p><strong>Average Percentage:</strong> <span class="<?php 
                            if ($average_percentage >= 80) echo 'grade-excellent';
                            elseif ($average_percentage >= 70) echo 'grade-very-good';
                            elseif ($average_percentage >= 60) echo 'grade-good';
                            elseif ($average_percentage >= 50) echo 'grade-credit';
                            elseif ($average_percentage >= 45) echo 'grade-pass';
                            else echo 'grade-fail';
                        ?>"><?php echo number_format($average_percentage, 2); ?>%</span></p>
                    </div>
                    <div>
                        <h4 class="font-bold text-lg mb-2">Overall Comment</h4>
                        <p class="italic"><?php echo $overall_comment; ?></p>
                        
                        <!-- Teacher's Signature Area -->
                        <div class="mt-4">
                            <p class="border-t border-gray-400 pt-2 w-48">Class Teacher's Signature</p>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Footer -->
            <div class="bg-blue-800 text-white p-4 text-center">
                <p class="text-sm">Generated on: <?php echo date('F j, Y'); ?></p>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <script>
        // Download as JPG function
        function downloadAsJPG() {
            html2canvas(document.getElementById('report-card')).then(function(canvas) {
                var link = document.createElement('a');
                link.download = 'Terminal_Report_<?php echo $ad_no; ?>.jpg';
                link.href = canvas.toDataURL('image/jpeg', 0.9);
                link.click();
            });
        }

        // Download as PDF function
        function downloadAsPDF() {
            const { jsPDF } = window.jspdf;
            
            html2canvas(document.getElementById('report-card')).then(function(canvas) {
                const imgData = canvas.toDataURL('image/jpeg', 0.9);
                const pdf = new jsPDF('p', 'mm', 'a4');
                const imgWidth = 210; // A4 width in mm
                const pageHeight = 295; // A4 height in mm
                const imgHeight = canvas.height * imgWidth / canvas.width;
                let heightLeft = imgHeight;
                let position = 0;

                pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
                heightLeft -= pageHeight;

                while (heightLeft >= 0) {
                    position = heightLeft - imgHeight;
                    pdf.addPage();
                    pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
                    heightLeft -= pageHeight;
                }

                pdf.save('Terminal_Report_<?php echo $ad_no; ?>.pdf');
            });
        }
    </script>
</body>
</html>