<?php
require_once '../includes/config.php';

// Check if user is logged in and is admin
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || $_SESSION['role'] !== 'admin') {
    header('Location: ../auth/login.php');
    exit();
}

$title = "View Student";

// Initialize variables
$student_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$message = '';
$message_type = '';

// Check for URL messages
if (isset($_GET['msg'])) {
    switch ($_GET['msg']) {
        case 'added':
            $message = 'Student added successfully!';
            $message_type = 'success';
            break;
        case 'updated':
            $message = 'Student updated successfully!';
            $message_type = 'success';
            break;
        case 'deleted':
            $message = 'Student deleted successfully!';
            $message_type = 'success';
            break;
    }
}

// Get student data
$student = null;
if ($student_id > 0) {
    $sql = "SELECT s.*, g.name as gender, c.code as course_code, c.name as course_name, 
                   d.code as department_code, d.name as department_name,
                   sc.code as school_code, sc.name as school_name
            FROM students s
            LEFT JOIN genders g ON s.gender_id = g.id
            LEFT JOIN courses c ON s.course_id = c.id
            LEFT JOIN departments d ON s.department_id = d.id
            LEFT JOIN schools sc ON s.school_id = sc.id
            WHERE s.id = ?";
    
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, 'i', $student_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $student = mysqli_fetch_assoc($result);
    } else {
        $message = 'Student not found!';
        $message_type = 'danger';
        header('Location: manage_students.php?msg=notfound');
        exit();
    }
    mysqli_stmt_close($stmt);
} else {
    $message = 'Invalid student ID!';
    $message_type = 'danger';
    header('Location: manage_students.php?msg=invalid');
    exit();
}

include '../includes/header.php';
?>

<!-- Page Header -->
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-2">
                <i class="bi bi-person me-2"></i> Student Details
            </h1>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                    <li class="breadcrumb-item"><a href="manage_students.php">Manage Students</a></li>
                    <li class="breadcrumb-item active">View Student</li>
                </ol>
            </nav>
        </div>
        <div>
            <a href="manage_students.php" class="btn btn-outline-secondary me-2">
                <i class="bi bi-arrow-left me-2"></i> Back to Students
            </a>
            <a href="edit_student.php?id=<?php echo $student_id; ?>" class="btn btn-warning">
                <i class="bi bi-pencil me-2"></i> Edit Student
            </a>
        </div>
    </div>

    <!-- Message Alert -->
    <?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
        <i class="bi bi-<?php echo $message_type == 'success' ? 'check-circle' : 'exclamation-triangle'; ?> me-2"></i>
        <?php echo $message; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>

    <?php if ($student): ?>
    <div class="row">
        <div class="col-lg-4">
            <!-- Profile Card -->
            <div class="card shadow mb-4">
                <div class="card-body text-center">
                    <?php if (!empty($student['picture_path'])): ?>
                        <img src="../<?php echo htmlspecialchars($student['picture_path']); ?>" 
                             alt="Student Photo" class="rounded-circle mb-3" 
                             style="width: 150px; height: 150px; object-fit: cover;">
                    <?php else: ?>
                        <div class="bg-primary rounded-circle d-flex align-items-center justify-content-center mx-auto mb-3" 
                             style="width: 150px; height: 150px;">
                            <i class="bi bi-person" style="font-size: 4rem; color: white;"></i>
                        </div>
                    <?php endif; ?>
                    
                    <h4><?php echo htmlspecialchars($student['full_name']); ?></h4>
                    <p class="text-muted mb-1"><?php echo htmlspecialchars($student['student_id']); ?></p>
                    
                    <div class="mb-3">
                        <?php if ($student['status'] == 1): ?>
                            <span class="badge bg-success">
                                <i class="bi bi-check-circle me-1"></i> Active
                            </span>
                        <?php else: ?>
                            <span class="badge bg-danger">
                                <i class="bi bi-x-circle me-1"></i> Inactive
                            </span>
                        <?php endif; ?>
                    </div>
                    
                    <div class="d-grid gap-2">
                        <a href="edit_student.php?id=<?php echo $student_id; ?>" class="btn btn-warning">
                            <i class="bi bi-pencil me-2"></i> Edit Profile
                        </a>
                        
                        <div class="btn-group">
                            <a href="../qr/generate.php?id=<?php echo $student_id; ?>" 
                               class="btn btn-primary" target="_blank">
                                <i class="bi bi-qr-code me-2"></i> View QR
                            </a>
                            <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" 
                                    data-bs-toggle="dropdown">
                                <span class="visually-hidden">Toggle Dropdown</span>
                            </button>
                            <ul class="dropdown-menu">
                                <li>
                                    <a class="dropdown-item" href="../qr/generate.php?id=<?php echo $student_id; ?>&print=1" target="_blank">
                                        <i class="bi bi-printer me-2"></i> Print QR
                                    </a>
                                </li>
                                <li>
                                    <a class="dropdown-item" href="../qr/generate.php?id=<?php echo $student_id; ?>&download=1">
                                        <i class="bi bi-download me-2"></i> Download QR
                                    </a>
                                </li>
                                <li>
                                    <a class="dropdown-item" href="../qr/generate.php?id=<?php echo $student_id; ?>&autoPrint=1" target="_blank">
                                        <i class="bi bi-printer-fill me-2"></i> Auto Print
                                    </a>
                                </li>
                            </ul>
                        </div>
                        
                        <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
                            <i class="bi bi-trash me-2"></i> Delete Student
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- QR Code Card -->
            <div class="card shadow">
                <div class="card-header bg-info text-white">
                    <h6 class="m-0 font-weight-bold">
                        <i class="bi bi-qr-code me-2"></i> QR Code Information
                    </h6>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <strong class="d-block">QR Code</strong>
                        <code class="text-break"><?php echo htmlspecialchars($student['qr_code']); ?></code>
                    </div>
                    <div class="mb-3">
                        <strong class="d-block">Generated</strong>
                        <?php echo date('F j, Y, h:i A', strtotime($student['created_at'])); ?>
                    </div>
                    <div class="text-center">
                        <a href="../qr/generate.php?id=<?php echo $student_id; ?>" 
                           class="btn btn-outline-primary btn-sm" target="_blank">
                            <i class="bi bi-eye me-1"></i> Preview QR Code
                        </a>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-lg-8">
            <!-- Student Information Card -->
            <div class="card shadow mb-4">
                <div class="card-header bg-primary text-white">
                    <h6 class="m-0 font-weight-bold">
                        <i class="bi bi-person-lines-fill me-2"></i> Personal Information
                    </h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-4">
                                <strong class="d-block text-muted mb-1">Student ID</strong>
                                <h5 class="text-primary"><?php echo htmlspecialchars($student['student_id']); ?></h5>
                            </div>
                            
                            <div class="mb-4">
                                <strong class="d-block text-muted mb-1">Full Name</strong>
                                <h5><?php echo htmlspecialchars($student['full_name']); ?></h5>
                            </div>
                            
                            <div class="mb-4">
                                <strong class="d-block text-muted mb-1">Gender</strong>
                                <p class="mb-0"><?php echo htmlspecialchars($student['gender']); ?></p>
                            </div>
                            
                            <div class="mb-4">
                                <strong class="d-block text-muted mb-1">Birth Date</strong>
                                <p class="mb-0">
                                    <?php if ($student['birth_date']): ?>
                                        <?php echo date('F j, Y', strtotime($student['birth_date'])); ?>
                                        <small class="text-muted">
                                            (<?php echo date_diff(date_create($student['birth_date']), date_create('today'))->y; ?> years old)
                                        </small>
                                    <?php else: ?>
                                        <span class="text-muted">Not set</span>
                                    <?php endif; ?>
                                </p>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-4">
                                <strong class="d-block text-muted mb-1">Contact Information</strong>
                                <?php if (!empty($student['email'])): ?>
                                    <div class="d-flex align-items-center mb-2">
                                        <i class="bi bi-envelope me-2 text-muted"></i>
                                        <a href="mailto:<?php echo htmlspecialchars($student['email']); ?>">
                                            <?php echo htmlspecialchars($student['email']); ?>
                                        </a>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if (!empty($student['contact_number'])): ?>
                                    <div class="d-flex align-items-center">
                                        <i class="bi bi-telephone me-2 text-muted"></i>
                                        <a href="tel:<?php echo htmlspecialchars($student['contact_number']); ?>">
                                            <?php echo htmlspecialchars($student['contact_number']); ?>
                                        </a>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="mb-4">
                                <strong class="d-block text-muted mb-1">Address</strong>
                                <p class="mb-0">
                                    <?php if (!empty($student['address'])): ?>
                                        <?php echo nl2br(htmlspecialchars($student['address'])); ?>
                                    <?php else: ?>
                                        <span class="text-muted">Not set</span>
                                    <?php endif; ?>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Academic Information Card -->
            <div class="card shadow">
                <div class="card-header bg-success text-white">
                    <h6 class="m-0 font-weight-bold">
                        <i class="bi bi-mortarboard me-2"></i> Academic Information
                    </h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-4">
                                <strong class="d-block text-muted mb-1">Year Level</strong>
                                <span class="badge bg-info" style="font-size: 1rem;">
                                    Year <?php echo $student['year_level']; ?>
                                </span>
                            </div>
                            
                            <div class="mb-4">
                                <strong class="d-block text-muted mb-1">School</strong>
                                <h5><?php echo htmlspecialchars($student['school_name']); ?></h5>
                            </div>
                            
                            <div class="mb-4">
                                <strong class="d-block text-muted mb-1">Department</strong>
                                <h5><?php echo htmlspecialchars($student['department_name']); ?></h5>
                                <small class="text-muted"><?php echo htmlspecialchars($student['department_code']); ?></small>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-4">
                                <strong class="d-block text-muted mb-1">Course</strong>
                                <h5><?php echo htmlspecialchars($student['course_name']); ?></h5>
                                <small class="text-muted"><?php echo htmlspecialchars($student['course_code']); ?></small>
                            </div>
                            
                            <div class="mb-4">
                                <strong class="d-block text-muted mb-1">Account Status</strong>
                                <?php if ($student['status'] == 1): ?>
                                    <span class="badge bg-success" style="font-size: 1rem;">
                                        <i class="bi bi-check-circle me-1"></i> Active
                                    </span>
                                    <p class="mt-1 mb-0 text-muted">Student can log in and use the system</p>
                                <?php else: ?>
                                    <span class="badge bg-danger" style="font-size: 1rem;">
                                        <i class="bi bi-x-circle me-1"></i> Inactive
                                    </span>
                                    <p class="mt-1 mb-0 text-muted">Student cannot log in to the system</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <strong class="d-block text-muted mb-1">Date Created</strong>
                                <p class="mb-0">
                                    <i class="bi bi-calendar-plus me-1"></i>
                                    <?php echo date('F j, Y, h:i A', strtotime($student['created_at'])); ?>
                                </p>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <strong class="d-block text-muted mb-1">Last Updated</strong>
                                <p class="mb-0">
                                    <i class="bi bi-clock-history me-1"></i>
                                    <?php echo date('F j, Y, h:i A', strtotime($student['updated_at'])); ?>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">
                        <i class="bi bi-exclamation-triangle me-2"></i> Confirm Delete
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete student <strong><?php echo htmlspecialchars($student['full_name']); ?></strong>?</p>
                    <p class="text-danger">
                        <i class="bi bi-exclamation-circle me-1"></i>
                        This action cannot be undone. All related activities and records will also be deleted.
                    </p>
                    <div class="alert alert-warning">
                        <i class="bi bi-info-circle me-2"></i>
                        <strong>Student Information:</strong><br>
                        ID: <?php echo htmlspecialchars($student['student_id']); ?><br>
                        Course: <?php echo htmlspecialchars($student['course_code']); ?><br>
                        Department: <?php echo htmlspecialchars($student['department_name']); ?>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <form method="POST" action="manage_students.php" style="display: inline;">
                        <input type="hidden" name="delete_student" value="1">
                        <input type="hidden" name="id" value="<?php echo $student_id; ?>">
                        <button type="submit" class="btn btn-danger">
                            <i class="bi bi-trash me-2"></i> Delete Student
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <?php else: ?>
    <!-- Student Not Found -->
    <div class="card shadow">
        <div class="card-body text-center py-5">
            <i class="bi bi-person-x" style="font-size: 4rem; color: #dc3545;"></i>
            <h3 class="mt-3">Student Not Found</h3>
            <p class="text-muted">The student you're trying to view does not exist or has been deleted.</p>
            <a href="manage_students.php" class="btn btn-primary mt-3">
                <i class="bi bi-arrow-left me-2"></i> Back to Students List
            </a>
        </div>
    </div>
    <?php endif; ?>
</div>

<?php 
$page_scripts = '
<script>
$(document).ready(function() {
    // Print student information
    $("#printStudentBtn").click(function() {
        const printWindow = window.open("", "_blank");
        printWindow.document.write(`
            <!DOCTYPE html>
            <html>
            <head>
                <title>Student Information - <?php echo htmlspecialchars($student[\'student_id\']); ?></title>
                <style>
                    body { font-family: Arial, sans-serif; margin: 20px; }
                    h1 { text-align: center; margin-bottom: 30px; }
                    .student-info { margin-bottom: 30px; }
                    .section { margin-bottom: 20px; }
                    .section-title { font-weight: bold; border-bottom: 2px solid #333; padding-bottom: 5px; margin-bottom: 10px; }
                    .info-row { margin-bottom: 8px; }
                    .label { font-weight: bold; display: inline-block; width: 150px; }
                    .footer { text-align: center; margin-top: 30px; font-size: 12px; color: #666; }
                    @media print {
                        .no-print { display: none; }
                        button { display: none; }
                    }
                </style>
            </head>
            <body>
                <h1>Student Information</h1>
                <div class="student-info">
                    <div class="section">
                        <div class="section-title">Personal Information</div>
                        <div class="info-row">
                            <span class="label">Student ID:</span>
                            <?php echo htmlspecialchars($student[\'student_id\']); ?>
                        </div>
                        <div class="info-row">
                            <span class="label">Full Name:</span>
                            <?php echo htmlspecialchars($student[\'full_name\']); ?>
                        </div>
                        <div class="info-row">
                            <span class="label">Gender:</span>
                            <?php echo htmlspecialchars($student[\'gender\']); ?>
                        </div>
                        <div class="info-row">
                            <span class="label">Birth Date:</span>
                            <?php echo $student[\'birth_date\'] ? date(\'F j, Y\', strtotime($student[\'birth_date\'])) : \'Not set\'; ?>
                        </div>
                        <div class="info-row">
                            <span class="label">Contact:</span>
                            <?php echo !empty($student[\'contact_number\']) ? htmlspecialchars($student[\'contact_number\']) : \'Not set\'; ?>
                        </div>
                        <div class="info-row">
                            <span class="label">Email:</span>
                            <?php echo !empty($student[\'email\']) ? htmlspecialchars($student[\'email\']) : \'Not set\'; ?>
                        </div>
                        <div class="info-row">
                            <span class="label">Address:</span>
                            <?php echo !empty($student[\'address\']) ? htmlspecialchars($student[\'address\']) : \'Not set\'; ?>
                        </div>
                    </div>
                    
                    <div class="section">
                        <div class="section-title">Academic Information</div>
                        <div class="info-row">
                            <span class="label">Year Level:</span>
                            Year <?php echo $student[\'year_level\']; ?>
                        </div>
                        <div class="info-row">
                            <span class="label">School:</span>
                            <?php echo htmlspecialchars($student[\'school_name\']); ?>
                        </div>
                        <div class="info-row">
                            <span class="label">Department:</span>
                            <?php echo htmlspecialchars($student[\'department_name\']); ?>
                        </div>
                        <div class="info-row">
                            <span class="label">Course:</span>
                            <?php echo htmlspecialchars($student[\'course_name\']); ?>
                        </div>
                        <div class="info-row">
                            <span class="label">Status:</span>
                            <?php echo $student[\'status\'] == 1 ? \'Active\' : \'Inactive\'; ?>
                        </div>
                        <div class="info-row">
                            <span class="label">QR Code:</span>
                            <?php echo htmlspecialchars($student[\'qr_code\']); ?>
                        </div>
                    </div>
                    
                    <div class="section">
                        <div class="section-title">System Information</div>
                        <div class="info-row">
                            <span class="label">Date Created:</span>
                            <?php echo date(\'F j, Y, h:i A\', strtotime($student[\'created_at\'])); ?>
                        </div>
                        <div class="info-row">
                            <span class="label">Last Updated:</span>
                            <?php echo date(\'F j, Y, h:i A\', strtotime($student[\'updated_at\'])); ?>
                        </div>
                    </div>
                </div>
                <div class="footer">
                    Student Management System - Generated on: <?php echo date(\'F j, Y, h:i A\'); ?>
                </div>
                <div style="text-align: center; margin-top: 20px;" class="no-print">
                    <button onclick="window.print()">Print Report</button>
                    <button onclick="window.close()" style="margin-left: 10px;">Close</button>
                </div>
                <script>
                    window.onload = function() {
                        window.print();
                    };
                <\/script>
            </body>
            </html>
        `);
        printWindow.document.close();
    });
    
    // Copy QR code to clipboard
    $("#copyQRBtn").click(function() {
        const qrCode = "<?php echo htmlspecialchars($student[\'qr_code\']); ?>";
        navigator.clipboard.writeText(qrCode).then(function() {
            showNotification("QR code copied to clipboard!", "success");
        }).catch(function(err) {
            console.error("Failed to copy: ", err);
            showNotification("Failed to copy QR code", "danger");
        });
    });
});

// Show notification
function showNotification(message, type = "info") {
    const alertClass = {
        "success": "alert-success",
        "danger": "alert-danger",
        "warning": "alert-warning",
        "info": "alert-info"
    }[type] || "alert-info";
    
    const icon = {
        "success": "check-circle",
        "danger": "exclamation-triangle",
        "warning": "exclamation-circle",
        "info": "info-circle"
    }[type] || "info-circle";
    
    // Remove existing alerts
    $(".alert-dismissible").remove();
    
    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            <i class="bi bi-${icon} me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;
    
    // Add alert at the top of the page
    $(".d-flex.justify-content-between.align-items-center.mb-4").after(alertHtml);
    
    // Auto-remove after 5 seconds
    setTimeout(() => {
        $(".alert-dismissible").alert("close");
    }, 5000);
}
</script>
';

include '../includes/footer.php';
?>