<?php
// Include database connection
include('db_connection.php');

// Initialize variables
$student_id = isset($_GET['id']) ? $_GET['id'] : null;
$student = null;
$parent = null;
$class = null;

// Fetch student details
if ($student_id) {
    $student_query = "SELECT students.*, classes.class_name, parents.name as parent_name 
                      FROM students 
                      JOIN classes ON students.class_id = classes.class_id 
                      JOIN parents ON students.parent_id = parents.parent_id 
                      WHERE students.student_id = ?";
    $stmt = $conn->prepare($student_query);
    $stmt->bind_param("i", $student_id);
    $stmt->execute();
    $student_result = $stmt->get_result();
    if ($student_result->num_rows > 0) {
        $student = $student_result->fetch_assoc();
    }
    $stmt->close();
}

// Fetch distinct years and terms for the dropdowns
$years_query = "SELECT DISTINCT year FROM academic_history WHERE student_id = ?";
$stmt = $conn->prepare($years_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$years_result = $stmt->get_result();
$stmt->close();

$terms_query = "SELECT DISTINCT term FROM academic_history WHERE student_id = ?";
$stmt = $conn->prepare($terms_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$terms_result = $stmt->get_result();
$stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Profile - School Management System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #3a57e8;
            --secondary: #6c757d;
            --success: #1cbb8c;
            --info: #17a2b8;
            --warning: #f5b759;
            --danger: #fc5b69;
            --light: #f8f9fa;
            --dark: #343a40;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background-color: #f5f7ff;
            color: #333;
        }
        
        .card {
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            margin-bottom: 20px;
            border: none;
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--primary) 0%, #2039c5 100%);
            color: white;
            border-radius: 10px 10px 0 0 !important;
            font-weight: 600;
        }
        
        .profile-header {
            background: linear-gradient(135deg, var(--primary) 0%, #2039c5 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .profile-img {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            object-fit: cover;
            border: 4px solid rgba(255, 255, 255, 0.3);
        }
        
        .info-card {
            padding: 20px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            margin-bottom: 20px;
        }
        
        .info-item {
            display: flex;
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        
        .info-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        
        .info-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: rgba(58, 87, 232, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 15px;
            color: var(--primary);
        }
        
        .info-content {
            flex: 1;
        }
        
        .info-label {
            font-size: 0.9rem;
            color: var(--secondary);
            margin-bottom: 3px;
        }
        
        .info-value {
            font-weight: 500;
            color: var(--dark);
        }
        
        .badge-status {
            padding: 0.5em 1em;
            border-radius: 20px;
            font-weight: 600;
        }
        
        .badge-present {
            background-color: rgba(28, 187, 140, 0.2);
            color: var(--success);
        }
        
        .badge-absent {
            background-color: rgba(252, 91, 105, 0.2);
            color: var(--danger);
        }
        
        .badge-late {
            background-color: rgba(245, 183, 89, 0.2);
            color: var(--warning);
        }
        
        .table th {
            background-color: var(--primary);
            color: white;
        }
        
        .filter-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            margin-bottom: 20px;
        }
        
        .back-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: none;
            border-radius: 50px;
            padding: 8px 20px;
            transition: all 0.3s;
        }
        
        .back-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2 class="mb-0"><i class="fas fa-user-graduate me-2"></i>Student Profile</h2>
            <a href="manage_students.php" class="btn btn-outline-primary"><i class="fas fa-arrow-left me-1"></i> Back to Students</a>
        </div>

        <?php if ($student): ?>
        <!-- Profile Header -->
        <div class="profile-header">
            <div class="row align-items-center">
                <div class="col-md-2 text-center">
                    <img src="<?php echo isset($student['profile_pic']) && !empty($student['profile_pic']) ? 'uploads/' . htmlspecialchars($student['profile_pic']) : 'https://via.placeholder.com/120x120'; ?>" 
                         alt="Profile Picture" class="profile-img">
                </div>
                <div class="col-md-10">
                    <h2><?php echo htmlspecialchars($student['name']); ?></h2>
                    <p class="mb-1">Student ID: <?php echo htmlspecialchars($student['student_id']); ?></p>
                    <p class="mb-0"><?php echo htmlspecialchars($student['class_name']); ?> • <?php echo htmlspecialchars($student['parent_name']); ?>'s Ward</p>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Student Information -->
            <div class="col-md-5">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-info-circle me-2"></i>Student Information</h5>
                    </div>
                    <div class="card-body">
                        <div class="info-item">
                            <div class="info-icon">
                                <i class="fas fa-id-card"></i>
                            </div>
                            <div class="info-content">
                                <div class="info-label">Student ID</div>
                                <div class="info-value"><?php echo htmlspecialchars($student['student_id']); ?></div>
                            </div>
                        </div>
                        
                        <div class="info-item">
                            <div class="info-icon">
                                <i class="fas fa-user"></i>
                            </div>
                            <div class="info-content">
                                <div class="info-label">Full Name</div>
                                <div class="info-value"><?php echo htmlspecialchars($student['name']); ?></div>
                            </div>
                        </div>
                        
                        <div class="info-item">
                            <div class="info-icon">
                                <i class="fas fa-envelope"></i>
                            </div>
                            <div class="info-content">
                                <div class="info-label">Email</div>
                                <div class="info-value"><?php echo htmlspecialchars($student['email']); ?></div>
                            </div>
                        </div>
                        
                        <div class="info-item">
                            <div class="info-icon">
                                <i class="fas fa-phone"></i>
                            </div>
                            <div class="info-content">
                                <div class="info-label">Phone</div>
                                <div class="info-value"><?php echo htmlspecialchars($student['phone']); ?></div>
                            </div>
                        </div>
                        
                        <div class="info-item">
                            <div class="info-icon">
                                <i class="fas fa-book"></i>
                            </div>
                            <div class="info-content">
                                <div class="info-label">Class</div>
                                <div class="info-value"><?php echo htmlspecialchars($student['class_name']); ?></div>
                            </div>
                        </div>
                        
                        <div class="info-item">
                            <div class="info-icon">
                                <i class="fas fa-users"></i>
                            </div>
                            <div class="info-content">
                                <div class="info-label">Parent</div>
                                <div class="info-value"><?php echo htmlspecialchars($student['parent_name']); ?></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Academic History -->
            <div class="col-md-7">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-graduation-cap me-2"></i>Academic History</h5>
                    </div>
                    <div class="card-body">
                        <!-- Filters -->
                        <div class="filter-card mb-4">
                            <div class="row">
                                <div class="col-md-6">
                                    <label for="year" class="form-label">Year</label>
                                    <select id="year" name="year" class="form-select" onchange="fetchAcademicHistory()">
                                        <option value="">Select Year</option>
                                        <?php 
                                        if ($years_result->num_rows > 0) {
                                            while ($year_row = $years_result->fetch_assoc()): 
                                        ?>
                                            <option value="<?php echo htmlspecialchars($year_row['year']); ?>">
                                                <?php echo htmlspecialchars($year_row['year']); ?>
                                            </option>
                                        <?php 
                                            endwhile;
                                        } else {
                                            echo '<option value="">No years available</option>';
                                        }
                                        ?>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label for="term" class="form-label">Term</label>
                                    <select id="term" name="term" class="form-select" onchange="fetchAcademicHistory()">
                                        <option value="">Select Term</option>
                                        <?php 
                                        if ($terms_result->num_rows > 0) {
                                            while ($term_row = $terms_result->fetch_assoc()): 
                                        ?>
                                            <option value="<?php echo htmlspecialchars($term_row['term']); ?>">
                                                <?php echo htmlspecialchars($term_row['term']); ?>
                                            </option>
                                        <?php 
                                            endwhile;
                                        } else {
                                            echo '<option value="">No terms available</option>';
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Academic History Table -->
                        <div id="academic-history">
                            <div class="text-center py-5">
                                <i class="fas fa-book-open fa-3x text-muted mb-3"></i>
                                <p class="text-muted">Select a year and term to view academic history</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <?php else: ?>
        <!-- Student Not Found -->
        <div class="text-center py-5">
            <i class="fas fa-exclamation-circle fa-3x text-danger mb-3"></i>
            <h3>Student Not Found</h3>
            <p class="text-muted">The requested student record could not be found.</p>
            <a href="manage_students.php" class="btn btn-primary mt-3"><i class="fas fa-arrow-left me-1"></i> Back to Students</a>
        </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function fetchAcademicHistory() {
            var year = document.getElementById('year').value;
            var term = document.getElementById('term').value;
            var studentId = <?php echo $student_id ? $student_id : 'null'; ?>;
            
            if (!year || !term || !studentId) {
                document.getElementById("academic-history").innerHTML = `
                    <div class="text-center py-5">
                        <i class="fas fa-book-open fa-3x text-muted mb-3"></i>
                        <p class="text-muted">Select a year and term to view academic history</p>
                    </div>
                `;
                return;
            }
            
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "fetch_academic_history.php", true);
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        document.getElementById("academic-history").innerHTML = xhr.responseText;
                    } else {
                        document.getElementById("academic-history").innerHTML = `
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-triangle me-2"></i> Error loading academic history
                            </div>
                        `;
                    }
                }
            };
            xhr.send("student_id=" + studentId + "&year=" + year + "&term=" + term);
        }
        
        // Initialize tooltips
        document.addEventListener('DOMContentLoaded', function() {
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl)
            });
        });
    </script>
</body>
</html>

<?php
// Close database connection
$conn->close();
?>