<?php
// check_record.php
session_start();

// Initialize JSON file if it doesn't exist
if (!file_exists('data/students.json')) {
    file_put_contents('data/students.json', json_encode([]));
}

$students = json_decode(file_get_contents('data/students.json'), true);
$searchResults = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $searchTerm = $_POST['search_term'];
    
    foreach ($students as $student) {
        if (stripos($student['surname'], $searchTerm) !== false || 
            stripos($student['other_names'], $searchTerm) !== false ||
            $student['prime_id'] === $searchTerm) {
            $searchResults[] = $student;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Check Student Record</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@7.2.96/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-lg-10">
                <div class="card shadow">
                    <div class="card-header bg-info text-white">
                        <h3 class="card-title"><i class="mdi mdi-account-search"></i> Check Student Record</h3>
                    </div>
                    <div class="card-body">
                        <form method="POST" class="mb-4">
                            <div class="input-group">
                                <input type="text" class="form-control form-control-lg" 
                                       name="search_term" placeholder="Enter Prime ID, Surname or Other Names" required>
                                <button class="btn btn-primary" type="submit"><i class="mdi mdi-magnify"></i> Search</button>
                            </div>
                        </form>
                        
                        <?php if (!empty($searchResults)): ?>
                            <div class="search-results">
                                <h4 class="mb-3">Search Results (<?= count($searchResults) ?>)</h4>
                                
                                <?php foreach ($searchResults as $student): ?>
                                    <div class="card mb-4 student-record">
                                        <div class="card-header d-flex justify-content-between align-items-center">
                                            <h5 class="mb-0">Student Details</h5>
                                            <div>
                                                <a href="edit_student.php?prime_id=<?= $student['prime_id'] ?>" class="btn btn-sm btn-outline-primary">
                                                    <i class="mdi mdi-pencil"></i> Edit
                                                </a>
                                                <a href="id_card.php?prime_id=<?= $student['prime_id'] ?>" class="btn btn-sm btn-outline-info">
                                                    <i class="mdi mdi-card-account-details"></i> ID Card
                                                </a>
                                                <button class="btn btn-sm btn-outline-success print-btn" 
                                                        data-student-id="<?= $student['prime_id'] ?>">
                                                    <i class="mdi mdi-printer"></i> Print
                                                </button>
                                            </div>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-3 text-center">
                                                    <?php if (isset($student['photo']) && file_exists('uploads/' . $student['photo'])): ?>
                                                        <img src="uploads/<?= $student['photo'] ?>" 
                                                             alt="Student Photo" class="img-fluid rounded mb-3" style="max-height: 200px;">
                                                    <?php else: ?>
                                                        <div class="bg-light rounded d-flex align-items-center justify-content-center mb-3" 
                                                             style="height: 200px;">
                                                            <i class="mdi mdi-account-box-outline mdi-48px text-muted"></i>
                                                        </div>
                                                    <?php endif; ?>
                                                    
                                                    <div id="qrcode-<?= $student['prime_id'] ?>" class="mb-3"></div>
                                                </div>
                                                <div class="col-md-9">
                                                    <div class="row">
                                                        <div class="col-md-6">
                                                            <p><strong>Prime ID:</strong> <?= $student['prime_id'] ?></p>
                                                            <p><strong>Surname:</strong> <?= $student['surname'] ?></p>
                                                            <p><strong>Other Names:</strong> <?= $student['other_names'] ?></p>
                                                            <p><strong>Sex:</strong> <?= $student['sex'] ?></p>
                                                            <p><strong>Date of Birth:</strong> <?= $student['dob'] ?></p>
                                                            <p><strong>Religion:</strong> <?= $student['religion'] ?></p>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <p><strong>Father's Phone:</strong> <?= $student['father_phone'] ?></p>
                                                            <p><strong>Mother's Phone:</strong> <?= $student['mother_phone'] ?></p>
                                                            <p><strong>Previous Class:</strong> <?= $student['previous_class'] ?></p>
                                                            <p><strong>Proposed Class:</strong> <?= $student['proposed_class'] ?></p>
                                                            <p><strong>State of Origin:</strong> <?= $student['state_origin'] ?></p>
                                                            <p><strong>Home Town:</strong> <?= $student['home_town'] ?></p>
                                                        </div>
                                                    </div>
                                                    <div class="row mt-3">
                                                        <div class="col-12">
                                                            <p><strong>Parent Email:</strong> <?= $student['parent_email'] ?></p>
                                                            <p><strong>Home Address:</strong> <?= $student['home_address'] ?></p>
                                                            <p><strong>Previous School:</strong> <?= $student['previous_school'] ?></p>
                                                            <p><strong>Status:</strong> 
                                                                <span class="badge 
                                                                    <?= $student['status'] == 'qualified' ? 'bg-success' : 
                                                                        ($student['status'] == 'disqualified' ? 'bg-danger' : 'bg-warning') ?>">
                                                                    <?= ucfirst($student['status']) ?>
                                                                </span>
                                                            </p>
                                                            <p><strong>Registration Date:</strong> <?= $student['registration_date'] ?></p>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php elseif ($_SERVER['REQUEST_METHOD'] === 'POST'): ?>
                            <div class="alert alert-warning">No student records found matching your search criteria.</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <?php include 'includes/footer.php'; ?>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.1/build/qrcode.min.js"></script>
    <script>
        // Generate QR codes for search results
        <?php if (!empty($searchResults)): ?>
            <?php foreach ($searchResults as $student): ?>
                setTimeout(function() {
                    var qrElement = document.getElementById('qrcode-<?= $student['prime_id'] ?>');
                    if (qrElement) {
                        // Clear any existing content
                        qrElement.innerHTML = '';
                        
                        // Generate QR code
                        QRCode.toCanvas(qrElement, 
                            'PRIME ID: <?= $student['prime_id'] ?>\nNAME: <?= $student['surname'] ?> <?= $student['other_names'] ?>\nCLASS: <?= $student['proposed_class'] ?>\nSTATUS: <?= $student['status'] ?>', 
                            { width: 150, margin: 1 }, function(error) {
                                if (error) console.error(error);
                            }
                        );
                    }
                }, 100);
            <?php endforeach; ?>
        <?php endif; ?>
        
        // Print functionality
        document.querySelectorAll('.print-btn').forEach(button => {
            button.addEventListener('click', function() {
                const studentId = this.getAttribute('data-student-id');
                const studentRecord = this.closest('.student-record');
                
                const printWindow = window.open('', '_blank');
                printWindow.document.write(`
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <title>Student Record - ${studentId}</title>
                        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
                        <style>
                            body { 
                                background-color: #fff; 
                                padding: 20px;
                            }
                            .watermark {
                                position: fixed;
                                top: 50%;
                                left: 50%;
                                transform: translate(-50%, -50%) rotate(-45deg);
                                opacity: 0.1;
                                z-index: -1;
                                width: 80%;
                            }
                            @media print {
                                .watermark {
                                    display: block !important;
                                }
                                .card {
                                    border: 1px solid #000 !important;
                                }
                            }
                        </style>
                    </head>
                    <body>
                        <img src="assets/watermark.png" class="watermark" style="display: none;">
                        <div class="container">
                            ${studentRecord.innerHTML}
                        </div>
                        <script>
                            window.onload = function() {
                                window.print();
                            }
                        <\/script>
                    </body>
                    </html>
                `);
                printWindow.document.close();
            });
        });
    </script>
</body>
</html>