<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get student ID from URL
$student_id = $_GET['id'] ?? null;

if (!$student_id) {
    die("Student ID not specified.");
}

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

// Get student data
$stmt = $pdo->prepare("SELECT s.*, u.email, u.last_login, u.is_active,
                      CONCAT(c.first_name, ' ', c.last_name) as counselor_name,
                      c.profile_photo as counselor_photo,
                      c.id as counselor_id
                      FROM students s
                      JOIN users u ON s.id = u.id
                      LEFT JOIN counselors c ON s.assigned_counselor_id = c.id
                      WHERE s.id = ?");
$stmt->execute([$student_id]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$student) {
    die("Student profile not found.");
}

// Get student applications
$applications = $pdo->prepare("SELECT a.*, p.name as program_name, p.degree_level,
                              u.name as university_name, u.logo as university_logo,
                              a.application_status as status
                              FROM applications a
                              JOIN programs p ON a.program_id = p.id
                              JOIN universities u ON p.university_id = u.id
                              WHERE a.student_id = ?
                              ORDER BY a.created_at DESC");
$applications->execute([$student_id]);
$applications = $applications->fetchAll();

// Get student documents
$documents = $pdo->prepare("SELECT * FROM student_documents
                           WHERE student_id = ?
                           ORDER BY created_at DESC");
$documents->execute([$student_id]);
$documents = $documents->fetchAll();

// Get student messages
$messages = $pdo->prepare("SELECT m.*, 
                          CASE 
                            WHEN m.sender_id = ? THEN 'sent'
                            ELSE 'received'
                          END as message_direction,
                          COALESCE(cs.first_name, ca.first_name) as sender_first,
                          COALESCE(cs.last_name, ca.last_name) as sender_last
                          FROM messages m
                          LEFT JOIN students cs ON m.sender_id = cs.id
                          LEFT JOIN counselors ca ON m.sender_id = ca.id
                          LEFT JOIN admins ad ON m.sender_id = ad.id
                          WHERE (m.sender_id = ? AND m.receiver_id = ?) 
                          OR (m.sender_id = ? AND m.receiver_id = ?)
                          ORDER BY m.created_at DESC LIMIT 10");
$messages->execute([$student_id, $student_id, $_SESSION['user_id'], $_SESSION['user_id'], $student_id]);
$messages = $messages->fetchAll();

// Handle status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $new_status = $_POST['status'] ?? '';
    $notes = $_POST['notes'] ?? '';
    
    if ($new_status) {
        try {
            $stmt = $pdo->prepare("UPDATE students SET status = ?, notes = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$new_status, $notes, $student_id]);
            
            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "student_status_updated",
                "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} updated status for {$student['first_name']} {$student['last_name']} to {$new_status}"
            ]);
            
            // Create notification for student
            $pdo->prepare("INSERT INTO notifications (
                user_id, title, message, is_read, notification_type, created_at
            ) VALUES (?, ?, ?, 0, 'status_update', NOW())")->execute([
                $student_id,
                "Your Status Has Been Updated",
                "Your student status has been updated to: {$new_status}. {$notes}"
            ]);
            
            // Redirect to avoid resubmission
            header("Location: admin-student-profile.php?id={$student_id}&status_updated=1");
            exit;
        } catch (Exception $e) {
            $error = "Failed to update status. Please try again.";
        }
    }
}

// Handle counselor assignment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_counselor'])) {
    $counselor_id = $_POST['counselor_id'] ?? null;
    
    if ($counselor_id) {
        try {
            $stmt = $pdo->prepare("UPDATE students SET assigned_counselor_id = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$counselor_id, $student_id]);
            
            // Get counselor name for logging
            $counselor_stmt = $pdo->prepare("SELECT first_name, last_name FROM counselors WHERE id = ?");
            $counselor_stmt->execute([$counselor_id]);
            $counselor = $counselor_stmt->fetch();
            
            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "student_assigned",
                "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} assigned {$student['first_name']} {$student['last_name']} to counselor {$counselor['first_name']} {$counselor['last_name']}"
            ]);
            
            // Create notification for student
            $pdo->prepare("INSERT INTO notifications (
                user_id, title, message, is_read, notification_type, created_at
            ) VALUES (?, ?, ?, 0, 'assignment', NOW())")->execute([
                $student_id,
                "You've Been Assigned a Counselor",
                "You have been assigned to counselor {$counselor['first_name']} {$counselor['last_name']}"
            ]);
            
            // Create notification for counselor
            $pdo->prepare("INSERT INTO notifications (
                user_id, title, message, is_read, notification_type, created_at
            ) VALUES (?, ?, ?, 0, 'assignment', NOW())")->execute([
                $counselor_id,
                "New Student Assigned",
                "Student {$student['first_name']} {$student['last_name']} has been assigned to you"
            ]);
            
            // Redirect to avoid resubmission
            header("Location: admin-student-profile.php?id={$student_id}&counselor_assigned=1");
            exit;
        } catch (Exception $e) {
            $error = "Failed to assign counselor. Please try again.";
        }
    }
}

// Get counselors for assignment
$counselors = $pdo->query("SELECT id, first_name, last_name FROM counselors ORDER BY last_name, first_name")->fetchAll();

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title><?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?> - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .profile-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0;
            padding: 30px;
        }
        .profile-img {
            width: 120px;
            height: 120px;
            object-fit: cover;
            border-radius: 50%;
            border: 5px solid white;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9em;
        }
        .status-prospective {
            background: #fff3cd;
            color: #856404;
        }
        .status-active {
            background: #d4edda;
            color: #155724;
        }
        .status-admitted {
            background: #d1ecf1;
            color: #0c5460;
        }
        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }
        .status-alumni {
            background: #d6d8d9;
            color: #383d41;
        }
        .section-card {
            border: 1px solid #eee;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .section-header {
            background: #f8f9fa;
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            border-radius: 10px 10px 0 0;
            font-weight: 600;
        }
        .section-body {
            padding: 20px;
        }
        .info-item {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px dashed #eee;
        }
        .info-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        .info-label {
            font-weight: 600;
            color: #6c757d;
            margin-bottom: 5px;
        }
        .info-value {
            font-size: 1.1em;
        }
        .university-logo {
            height: 40px;
            object-fit: contain;
            background: white;
            padding: 3px;
            border-radius: 5px;
        }
        .application-status {
            font-size: 0.9em;
            padding: 3px 8px;
            border-radius: 15px;
            font-weight: 600;
        }
        .status-submitted {
            background: #fff3cd;
            color: #856404;
        }
        .status-under_review {
            background: #cce5ff;
            color: #004085;
        }
        .status-accepted {
            background: #d4edda;
            color: #155724;
        }
        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }
        .document-status {
            font-size: 0.8em;
            padding: 3px 8px;
            border-radius: 15px;
        }
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        .status-verified {
            background: #d4edda;
            color: #155724;
        }
        .status-rejected-doc {
            background: #f8d7da;
            color: #721c24;
        }
        .counselor-photo {
            width: 50px;
            height: 50px;
            object-fit: cover;
            border-radius: 50%;
            margin-right: 15px;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .tabs {
            display: flex;
            border-bottom: 1px solid #dee2e6;
            margin-bottom: 20px;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: 1px solid transparent;
            border-bottom: none;
            border-radius: 5px 5px 0 0;
            margin-right: 5px;
        }
        .tab.active {
            background: #f8f9fa;
            border-color: #dee2e6;
            border-bottom: 1px solid #f8f9fa;
        }
        .action-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        .btn-outline-primary {
            border-color: #3fb7fe;
            color: #3fb7fe;
        }
        .btn-outline-primary:hover {
            background: #3fb7fe;
            color: white;
        }
    </style>
</head>
<body>

<?php include 'admin-navbar.php'; ?>

<div class="container py-5">
    <div class="row">
        <div class="col-lg-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="display-5">Student Profile</h1>
                <div>
                    <a href="admin-manage-students.php" class="btn btn-outline-primary">Back to Students</a>
                </div>
            </div>
        </div>
    </div>

    <!-- Profile Header -->
    <div class="profile-header text-center text-white mb-4">
        <div class="d-flex align-items-center justify-content-center mb-3">
            <img src="<?= htmlspecialchars($student['profile_photo'] ?: 'img/profile-placeholder.jpg') ?>" 
                 alt="<?= htmlspecialchars($student['first_name']) ?>" class="profile-img">
        </div>
        <h2><?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?></h2>
        <p class="lead mb-2"><?= htmlspecialchars($student['email']) ?></p>
        <div class="d-flex justify-content-center align-items-center">
            <span class="status-badge status-<?= $student['status'] ?>">
                <?= ucfirst($student['status']) ?>
            </span>
            <?php if ($student['counselor_name']): ?>
            <span class="ml-3">Counselor: <strong><?= htmlspecialchars($student['counselor_name']) ?></strong></span>
            <?php else: ?>
            <span class="ml-3 text-warning">No counselor assigned</span>
            <?php endif; ?>
        </div>
    </div>

    <!-- Success Messages -->
    <?php if (isset($_GET['status_updated'])): ?>
        <div class="alert alert-success">Student status updated successfully!</div>
    <?php endif; ?>
    
    <?php if (isset($_GET['counselor_assigned'])): ?>
        <div class="alert alert-success">Counselor assigned successfully!</div>
    <?php endif; ?>
    
    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <!-- Tabs -->
    <div class="tabs">
        <div class="tab active" data-tab="overview">Overview</div>
        <div class="tab" data-tab="applications">Applications</div>
        <div class="tab" data-tab="documents">Documents</div>
        <div class="tab" data-tab="messages">Messages</div>
        <div class="tab" data-tab="settings">Settings</div>
    </div>

    <!-- Overview Tab -->
    <div id="overview" class="tab-content active">
        <div class="row">
            <div class="col-lg-8">
                <!-- Personal Information -->
                <div class="section-card">
                    <div class="section-header">Personal Information</div>
                    <div class="section-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="info-item">
                                    <div class="info-label">First Name</div>
                                    <div class="info-value"><?= htmlspecialchars($student['first_name']) ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Last Name</div>
                                    <div class="info-value"><?= htmlspecialchars($student['last_name']) ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Email</div>
                                    <div class="info-value"><?= htmlspecialchars($student['email']) ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Phone</div>
                                    <div class="info-value"><?= htmlspecialchars($student['phone'] ?? 'Not provided') ?></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="info-item">
                                    <div class="info-label">Date of Birth</div>
                                    <div class="info-value"><?= $student['date_of_birth'] ? date('M j, Y', strtotime($student['date_of_birth'])) : 'Not provided' ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Gender</div>
                                    <div class="info-value"><?= htmlspecialchars($student['gender'] ?? 'Not specified') ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Address</div>
                                    <div class="info-value"><?= htmlspecialchars($student['address'] ?? 'Not provided') ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Last Login</div>
                                    <div class="info-value"><?= $student['last_login'] ? date('M j, Y H:i', strtotime($student['last_login'])) : 'Never' ?></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Academic Information -->
                <div class="section-card">
                    <div class="section-header">Academic Information</div>
                    <div class="section-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="info-item">
                                    <div class="info-label">Education Level</div>
                                    <div class="info-value"><?= htmlspecialchars($student['education_level'] ?? 'Not specified') ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Current Institution</div>
                                    <div class="info-value"><?= htmlspecialchars($student['current_institution'] ?? 'Not specified') ?></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="info-item">
                                    <div class="info-label">GPA</div>
                                    <div class="info-value"><?= $student['gpa'] ? number_format($student['gpa'], 2) : 'Not specified' ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Budget</div>
                                    <div class="info-value"><?= $student['budget'] ? '$' . number_format($student['budget']) : 'Not specified' ?></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Preferences -->
                <div class="section-card">
                    <div class="section-header">Preferences</div>
                    <div class="section-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="info-item">
                                    <div class="info-label">Preferred Countries</div>
                                    <div class="info-value">
                                        <?php 
                                        $countries = json_decode($student['preferred_countries'] ?? '[]', true);
                                        echo $countries ? implode(', ', $countries) : 'Not specified';
                                        ?>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="info-item">
                                    <div class="info-label">Preferred Courses</div>
                                    <div class="info-value">
                                        <?php 
                                        $courses = json_decode($student['preferred_courses'] ?? '[]', true);
                                        echo $courses ? implode(', ', $courses) : 'Not specified';
                                        ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-4">
                <!-- Counselor Assignment -->
                <div class="section-card">
                    <div class="section-header">Counselor Assignment</div>
                    <div class="section-body">
                        <?php if ($student['counselor_name']): ?>
                        <div class="d-flex align-items-center mb-3">
                            <img src="<?= htmlspecialchars($student['counselor_photo'] ?: 'img/profile-placeholder.jpg') ?>" 
                                 alt="<?= htmlspecialchars($student['counselor_name']) ?>" class="counselor-photo">
                            <div>
                                <strong><?= htmlspecialchars($student['counselor_name']) ?></strong>
                                <div class="small text-muted">Education Consultant</div>
                            </div>
                        </div>
                        <a href="admin-messages.php?student_id=<?= $student_id ?>&counselor_id=<?= $student['counselor_id'] ?>" 
                           class="btn btn-primary btn-block">Message Counselor</a>
                        <?php else: ?>
                        <form method="POST">
                            <div class="form-group">
                                <label>Assign Counselor</label>
                                <select name="counselor_id" class="form-control" required>
                                    <option value="">Select Counselor</option>
                                    <?php foreach ($counselors as $c): ?>
                                    <option value="<?= $c['id'] ?>">
                                        <?= htmlspecialchars($c['first_name'] . ' ' . $c['last_name']) ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <button type="submit" name="assign_counselor" class="btn btn-primary btn-block">
                                Assign Counselor
                            </button>
                        </form>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Status Management -->
                <div class="section-card">
                    <div class="section-header">Status Management</div>
                    <div class="section-body">
                        <form method="POST">
                            <div class="form-group">
                                <label>Student Status</label>
                                <select name="status" class="form-control" required>
                                    <option value="prospective" <?= $student['status'] === 'prospective' ? 'selected' : '' ?>>Prospective</option>
                                    <option value="active" <?= $student['status'] === 'active' ? 'selected' : '' ?>>Active</option>
                                    <option value="admitted" <?= $student['status'] === 'admitted' ? 'selected' : '' ?>>Admitted</option>
                                    <option value="rejected" <?= $student['status'] === 'rejected' ? 'selected' : '' ?>>Rejected</option>
                                    <option value="alumni" <?= $student['status'] === 'alumni' ? 'selected' : '' ?>>Alumni</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Notes</label>
                                <textarea name="notes" class="form-control" rows="3"><?= htmlspecialchars($student['notes'] ?? '') ?></textarea>
                            </div>
                            <button type="submit" name="update_status" class="btn btn-primary btn-block">
                                Update Status
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Quick Actions -->
                <div class="section-card">
                    <div class="section-header">Quick Actions</div>
                    <div class="section-body">
                        <div class="action-buttons">
                            <a href="admin-messages.php?student_id=<?= $student_id ?>" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-comments"></i> Message
                            </a>
                            <a href="admin-create-application.php?student_id=<?= $student_id ?>" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-file-alt"></i> Apply
                            </a>
                        </div>
                        <div class="action-buttons">
                            <a href="#" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-calendar"></i> Schedule
                            </a>
                            <a href="admin-documents.php?student_id=<?= $student_id ?>" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-folder"></i> Documents
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Applications Tab -->
    <div id="applications" class="tab-content">
        <div class="section-card">
            <div class="section-header">Applications</div>
            <div class="section-body">
                <?php if (empty($applications)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-file-alt fa-3x text-muted mb-3"></i>
                    <p class="text-muted">No applications found for this student.</p>
                    <a href="admin-create-application.php?student_id=<?= $student_id ?>" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Create Application
                    </a>
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>University</th>
                                <th>Program</th>
                                <th>Status</th>
                                <th>Submitted</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($applications as $app): ?>
                            <tr>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <img src="<?= htmlspecialchars($app['university_logo'] ?: 'img/university-placeholder.png') ?>" 
                                             alt="<?= htmlspecialchars($app['university_name']) ?>" class="university-logo mr-2">
                                        <?= htmlspecialchars($app['university_name']) ?>
                                    </div>
                                </td>
                                <td><?= htmlspecialchars($app['degree_level'] . ' in ' . $app['program_name']) ?></td>
                                <td>
                                    <span class="application-status status-<?= str_replace(' ', '_', strtolower($app['status'])) ?>">
                                        <?= ucfirst(str_replace('_', ' ', $app['status'])) ?>
                                    </span>
                                </td>
                                <td><?= $app['submission_date'] ? date('M j, Y', strtotime($app['submission_date'])) : 'Not submitted' ?></td>
                                <td>
                                    <a href="admin-application-review.php?id=<?= $app['id'] ?>" class="btn btn-sm btn-primary">Review</a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Documents Tab -->
    <div id="documents" class="tab-content">
        <div class="section-card">
            <div class="section-header">Documents</div>
            <div class="section-body">
                <?php if (empty($documents)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-folder-open fa-3x text-muted mb-3"></i>
                    <p class="text-muted">No documents uploaded by this student.</p>
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>Document</th>
                                <th>Uploaded</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($documents as $doc): ?>
                            <tr>
                                <td><?= ucfirst($doc['document_type']) ?></td>
                                <td><?= date('M j, Y', strtotime($doc['created_at'])) ?></td>
                                <td>
                                    <span class="document-status status-<?= $doc['status'] === 'rejected' ? 'rejected-doc' : $doc['status'] ?>">
                                        <?= ucfirst($doc['status']) ?>
                                    </span>
                                </td>
                                <td>
                                    <a href="<?= htmlspecialchars($doc['file_path']) ?>" class="btn btn-sm btn-primary" target="_blank">View</a>
                                    <a href="admin-documents.php" class="btn btn-sm btn-outline-primary">Verify</a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Messages Tab -->
    <div id="messages" class="tab-content">
        <div class="section-card">
            <div class="section-header">Recent Messages</div>
            <div class="section-body">
                <?php if (empty($messages)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-comments fa-3x text-muted mb-3"></i>
                    <p class="text-muted">No messages exchanged with this student.</p>
                    <a href="admin-messages.php?student_id=<?= $student_id ?>" class="btn btn-primary">
                        <i class="fas fa-paper-plane"></i> Send Message
                    </a>
                </div>
                <?php else: ?>
                <div class="message-container" style="max-height: 400px; overflow-y: auto;">
                    <?php foreach (array_reverse($messages) as $msg): ?>
                    <div class="media mb-3 <?= $msg['message_direction'] === 'sent' ? 'ml-auto' : '' ?>" style="max-width: 80%;">
                        <div class="media-body">
                            <div class="bg-<?= $msg['message_direction'] === 'sent' ? 'primary' : 'light' ?> p-3 rounded">
                                <p class="mb-0 text-white"><?= htmlspecialchars($msg['content']) ?></p>
                            </div>
                            <small class="text-muted mt-1 d-block">
                                <?= date('M j, H:i', strtotime($msg['created_at'])) ?>
                                <?php if ($msg['message_direction'] === 'sent' && $msg['is_read']): ?>
                                <i class="fas fa-check-double text-primary"></i>
                                <?php elseif ($msg['message_direction'] === 'sent'): ?>
                                <i class="fas fa-check text-muted"></i>
                                <?php endif; ?>
                            </small>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <div class="mt-3">
                    <a href="admin-messages.php?student_id=<?= $student_id ?>" class="btn btn-primary">
                        <i class="fas fa-paper-plane"></i> Send Message
                    </a>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Settings Tab -->
    <div id="settings" class="tab-content">
        <div class="section-card">
            <div class="section-header">Account Settings</div>
            <div class="section-body">
                <div class="info-item">
                    <div class="info-label">Account Status</div>
                    <div class="info-value">
                        <span class="status-badge <?= $student['is_active'] ? 'status-active' : 'status-inactive' ?>">
                            <?= $student['is_active'] ? 'Active' : 'Inactive' ?>
                        </span>
                    </div>
                </div>
                <div class="info-item">
                    <div class="info-label">Created</div>
                    <div class="info-value"><?= date('M j, Y', strtotime($student['created_at'])) ?></div>
                </div>
                <div class="info-item">
                    <div class="info-label">Last Updated</div>
                    <div class="info-value"><?= date('M j, Y', strtotime($student['updated_at'])) ?></div>
                </div>
                <div class="action-buttons">
                    <button class="btn btn-danger" onclick="confirmAction('deactivate', '<?= $student['first_name'] ?>')">
                        <i class="fas fa-user-slash"></i> Deactivate Account
                    </button>
                    <button class="btn btn-danger" onclick="confirmAction('delete', '<?= $student['first_name'] ?>')">
                        <i class="fas fa-trash"></i> Delete Account
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script>
    // Tab functionality
    document.querySelectorAll('.tab').forEach(tab => {
        tab.addEventListener('click', () => {
            // Remove active class from all tabs and content
            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
            
            // Add active class to clicked tab
            tab.classList.add('active');
            
            // Show corresponding content
            const tabId = tab.getAttribute('data-tab');
            document.getElementById(tabId).classList.add('active');
        });
    });
    
    // Confirm action function
    function confirmAction(action, studentName) {
        let message = '';
        let confirmText = '';
        
        if (action === 'deactivate') {
            message = `Are you sure you want to deactivate ${studentName}'s account? This will prevent them from logging in.`;
            confirmText = 'Deactivate';
        } else if (action === 'delete') {
            message = `Are you sure you want to delete ${studentName}'s account? This action cannot be undone and will permanently remove all their data.`;
            confirmText = 'Delete';
        }
        
        if (confirm(message)) {
            alert(`In a real application, this would ${action} the student account.`);
        }
    }
</script>
</body>
</html>