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

// Check if session variables are set
if(!isset($_SESSION['name']) || !isset($_SESSION['ad_no']) || !isset($_SESSION['classes']) || !isset($_SESSION['session']) || !isset($_SESSION['term'])) {
    echo "<script>alert('Please fill the form first'); window.history.back();</script>";
    exit();
}

// Fetch additional student data
$student_query = $dbh->prepare("SELECT s.*, c.name as class_name FROM students s 
                               LEFT JOIN classes c ON s.class_id = c.id 
                               WHERE s.Admission_num = :ad_no");
$student_query->bindParam(':ad_no', $_SESSION['ad_no']);
$student_query->execute();
$student_data = $student_query->fetch(PDO::FETCH_ASSOC);

// Fetch session and term names
$session_query = $dbh->prepare("SELECT session_year FROM sessions WHERE id = :session_id");
$session_query->bindParam(':session_id', $_SESSION['session']);
$session_query->execute();
$session_data = $session_query->fetch(PDO::FETCH_ASSOC);

$term_query = $dbh->prepare("SELECT term_name FROM terms WHERE id = :term_id");
$term_query->bindParam(':term_id', $_SESSION['term']);
$term_query->execute();
$term_data = $term_query->fetch(PDO::FETCH_ASSOC);

// Fetch class name
$class_query = $dbh->prepare("SELECT name FROM classes WHERE id = :class_id");
$class_query->bindParam(':class_id', $_SESSION['classes']);
$class_query->execute();
$class_data = $class_query->fetch(PDO::FETCH_ASSOC);

// Fetch mid-term results
$result_query = $dbh->prepare("SELECT m.*, s.name as subject_name FROM mid_term_test m 
                              LEFT JOIN Subjects s ON m.subject = s.id 
                              WHERE m.Admission_no = :ad_no 
                              AND m.classes = :class_id 
                              AND m.session = :session_id 
                              AND m.term = :term_id");
$result_query->bindParam(':ad_no', $_SESSION['ad_no']);
$result_query->bindParam(':class_id', $_SESSION['classes']);
$result_query->bindParam(':session_id', $_SESSION['session']);
$result_query->bindParam(':term_id', $_SESSION['term']);
$result_query->execute();
$results = $result_query->fetchAll(PDO::FETCH_ASSOC);

// Calculate totals for summary
$total_test = 0;
$total_mid_test = 0;
$total_overall = 0;
$subject_count = count($results);

foreach($results as $result) {
    $total_test += $result['wk_test'];
    $total_mid_test += $result['mid_test'];
    $total_overall += $result['total'];
}

$average_score = $subject_count > 0 ? $total_overall / $subject_count : 0;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mid Term Report - <?php echo $_SESSION['name']; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <style>
        @media print {
            .no-print {
                display: none !important;
            }
            body {
                background: white !important;
            }
            .report-container {
                box-shadow: none !important;
                border: none !important;
            }
        }
        
        .watermark {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: url('assets/images/logo-icon.png');
            background-repeat: repeat;
            background-size: 200px;
            opacity: 0.1;
            z-index: -1;
            pointer-events: none;
        }
        
        .report-container {
            position: relative;
            z-index: 1;
        }
    </style>
</head>
<body class="bg-gray-100">
    <!-- Watermark Background -->
    <div class="watermark"></div>

    <div class="container mx-auto px-4 py-8">
        <!-- Action Buttons -->
        <div class="no-print flex justify-end space-x-4 mb-6">
            <button onclick="window.print()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition duration-200">
                🖨️ Print Report
            </button>
            <button onclick="downloadJPG()" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg transition duration-200">
                📷 Download JPG
            </button>
            <button onclick="downloadPDF()" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg transition duration-200">
                📄 Save as PDF
            </button>
            <button onclick="window.history.back()" class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg transition duration-200">
                ← Back
            </button>
        </div>

        <!-- Report Container -->
        <div id="report-content" class="report-container bg-white rounded-lg shadow-lg p-8 max-w-4xl mx-auto">
            <!-- Row 1: School Header -->
            <div class="text-center border-b-2 border-gray-300 pb-4 mb-6">
                <div class="flex justify-center items-center mb-4">
                    <img src="assets/images/logo-icon.png" alt="School Logo" class="h-20 w-20 mr-4">
                    <div>
                        <h1 class="text-3xl font-bold text-gray-800">Penuel College</h1>
                        <p class="text-gray-600 mt-2"> Address: Ibadan Oyo state </p>
                        <p class="text-gray-600">Phone: (+234) 8147 0581 44 | Email: info@penuel.com.ng</p>
                    </div>
                </div>
            </div>

            <!-- Row 2: Student Information -->
            <div class="text-center border-b-2 border-gray-300 pb-4 mb-6">
                
                <div class="flex justify-center items-center mb-">
                    
                        <table class="w-full     ">
                       <tr class="  text-white">
                            <th class="   px-4 py-3 text-left">
                            <span class="font-semibold text-gray-700 w-32">Full Name:</span>
                        <span class="text-gray-900"><?php echo htmlspecialchars($_SESSION['name']); ?></span>
                            </th>
                            <th class="   px-4 py-3 text-left">
                                <span class="font-semibold text-gray-700 w-32">Admission No:</span>
                        <span class="text-gray-900"><?php echo htmlspecialchars($_SESSION['ad_no']); ?></span>
                                
                            </th>
                            <th class="   px-4 py-3 text-left">
                                <span class="font-semibold text-gray-700 w-32">Passport:</span>
                        <div class="w-16 h-16 bg-gray-200 rounded-full border-2   overflow-hidden">
                            <?php if(!empty($student_data['image'])): ?>
                                <img src="../staff/<?php echo htmlspecialchars($student_data['image']); ?>" alt="Passport" class="w-full h-full object-cover">
                            <?php else: ?>
                                <div class="w-full h-full flex items-center justify-center text-gray-400 text-sm">No Image</div>
                            <?php endif; ?>
                                
                            </th>
                        </tr>
                        <tr class="  text-white">
                            <th class="   px-4 py-3 text-left">
                            <span class="font-semibold text-gray-700 w-32">Class:</span>
                        <span class="text-gray-900"><?php echo htmlspecialchars($class_data['name'] ?? 'N/A'); ?></span>
                            </th>
                            <th class="   px-4 py-3 text-left">
                                <span class="font-semibold text-gray-700 w-32">Session:</span>
                        <span class="text-gray-900"><?php echo htmlspecialchars($session_data['session_year'] ?? 'N/A'); ?></span>
                                
                            </th>
                            <th class="   px-4 py-3 text-left">
                                <span class="font-semibold text-gray-700 w-32">Term:</span>
                        <span class="text-gray-900"><?php echo htmlspecialchars($term_data['term_name'] ?? 'N/A'); ?></span>
                                
                            </th>
                            
                        </tr>
                        </table>
                    
                    
                    
                    
                    
                    
                </div>
            </div>

            <!-- Row 3: Report Name -->
            <div class="text-center mb-6">
                <h2 class="text-2xl font-bold text-blue-800 bg-blue-50 py-3 rounded-lg border-l-4 border-blue-600">
                    MID TERM REPORT CARD
                </h2>
            </div>

            <!-- Row 4: Results Table -->
            <div class="overflow-x-auto mb-6">
                <table class="w-full border-collapse border border-gray-300">
                    <thead>
                        <tr class="bg-gray-800 text-white">
                            <th class="border border-gray-300 px-4 py-3 text-left">S/N</th>
                            <th class="border border-gray-300 px-4 py-3 text-left">Subjects</th>
                            <th class="border border-gray-300 px-4 py-3 text-center">Test</th>
                            <th class="border border-gray-300 px-4 py-3 text-center">Mid-Term Test</th>
                            <th class="border border-gray-300 px-4 py-3 text-center">Total</th>
                            <th class="border border-gray-300 px-4 py-3 text-center">Comment</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(count($results) > 0): ?>
                            <?php foreach($results as $index => $result): ?>
                                <tr class="hover:bg-gray-50 <?php echo $index % 2 === 0 ? 'bg-white' : 'bg-gray-50'; ?>">
                                    <td class="border border-gray-300 px-4 py-3"><?php echo $index + 1; ?></td>
                                    <td class="border border-gray-300 px-4 py-3 font-medium"><?php echo htmlspecialchars($result['subject_name']); ?></td>
                                    <td class="border border-gray-300 px-4 py-3 text-center"><?php echo htmlspecialchars($result['wk_test']); ?></td>
                                    <td class="border border-gray-300 px-4 py-3 text-center"><?php echo htmlspecialchars($result['mid_test']); ?></td>
                                    <td class="border border-gray-300 px-4 py-3 text-center font-semibold"><?php echo htmlspecialchars($result['total']); ?></td>
                                    <td class="border border-gray-300 px-4 py-3 text-center text-sm">
                                        <span class="inline-block px-2 py-1 rounded 
                                            <?php 
                                            $comment = strtolower($result['comment']);
                                            if(strpos($comment, 'excellent') !== false) echo 'bg-green-100 text-green-800';
                                            elseif(strpos($comment, 'good') !== false) echo 'bg-blue-100 text-blue-800';
                                            elseif(strpos($comment, 'fair') !== false) echo 'bg-yellow-100 text-yellow-800';
                                            elseif(strpos($comment, 'poor') !== false) echo 'bg-red-100 text-red-800';
                                            else echo 'bg-gray-100 text-gray-800';
                                            ?>">
                                            <?php echo htmlspecialchars($result['comment']); ?>
                                        </span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6" class="border border-gray-300 px-4 py-8 text-center text-gray-500">
                                    No results found for the selected criteria.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Summary Section -->
            <?php if(count($results) > 0): ?>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div class="bg-blue-50 p-4 rounded-lg border border-blue-200">
                    <h3 class="font-semibold text-blue-800 mb-2">Test Summary</h3>
                    <p class="text-sm">Total Test Score: <span class="font-bold"><?php echo $total_test; ?></span></p>
                    <p class="text-sm">Total Mid-Term: <span class="font-bold"><?php echo $total_mid_test; ?></span></p>
                </div>
                <div class="bg-green-50 p-4 rounded-lg border border-green-200">
                    <h3 class="font-semibold text-green-800 mb-2">Overall Performance</h3>
                    <p class="text-sm">Total Score: <span class="font-bold"><?php echo $total_overall; ?></span></p>
                    <p class="text-sm">Average Score: <span class="font-bold"><?php echo number_format($average_score, 2); ?></span></p>
                </div>
                <div class="bg-purple-50 p-4 rounded-lg border border-purple-200">
                    <h3 class="font-semibold text-purple-800 mb-2">Subject Count</h3>
                    <p class="text-sm">Total Subjects: <span class="font-bold"><?php echo $subject_count; ?></span></p>
                    <p class="text-sm">Status: <span class="font-bold text-green-600">Active</span></p>
                </div>
            </div>
            <?php endif; ?>

            <!-- Footer -->
            <div class="border-t-2 border-gray-300 pt-4 mt-6 text-center text-gray-600 text-sm">
                <p>Generated on: <?php echo date('F j, Y, g:i A'); ?></p>
                <p class="mt-2">This is a computer generated report and does not require a signature.</p>
            </div>
        </div>
    </div>

    <script>
        // Download as JPG
        function downloadJPG() {
            html2canvas(document.getElementById('report-content'), {
                scale: 2,
                useCORS: true,
                logging: false
            }).then(function(canvas) {
                const link = document.createElement('a');
                link.download = 'mid-term-report-<?php echo $_SESSION['ad_no']; ?>.jpg';
                link.href = canvas.toDataURL('image/jpeg', 0.9);
                link.click();
            });
        }

        // Download as PDF
        function downloadPDF() {
            const { jsPDF } = window.jspdf;
            
            html2canvas(document.getElementById('report-content'), {
                scale: 2,
                useCORS: true,
                logging: false
            }).then(function(canvas) {
                const imgData = canvas.toDataURL('image/jpeg', 0.9);
                const pdf = new jsPDF('p', 'mm', 'a4');
                const imgWidth = 210;
                const pageHeight = 295;
                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('mid-term-report-<?php echo $_SESSION['ad_no']; ?>.pdf');
            });
        }

        // Auto-print if URL has print parameter
        if(window.location.search.includes('print=true')) {
            window.print();
        }
    </script>
</body>
</html>