<?php
/**
 * Counselor Student Profile Page
 * View and manage student information
 */

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'] !== 'counselor') {
    header('Location: counselor-login.php');
    exit;
}

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

if (!$counselor) {
    die("Counselor profile not found.");
}

// Get student ID from URL
$student_id = $_GET['id'] ?? null;
if (!$student_id) {
    header('Location: counselor-students.php');
    exit;
}

// Verify that this student is assigned to this counselor
$stmt = $pdo->prepare("SELECT s.assigned_counselor_id FROM students s WHERE s.id = ?");
$stmt->execute([$student_id]);
$assignment = $stmt->fetch();

if (!$assignment || $assignment['assigned_counselor_id'] != $_SESSION['user_id']) {
    die("You don't have permission to view this student's profile.");
}

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

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

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

// Get student's 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's appointments
$appointments = $pdo->prepare("SELECT a.*, 
                              CONCAT(c.first_name, ' ', c.last_name) as counselor_name,
                              a.appointment_type, a.notes as appointment_notes
                      FROM appointments a
                      JOIN counselors c ON a.counselor_id = c.id
                      WHERE a.student_id = ?
                      ORDER BY a.scheduled_time DESC");
$appointments->execute([$student_id]);
$appointments = $appointments->fetchAll();

// Get student's visa applications
$visa_applications = $pdo->prepare("SELECT va.*, co.name as country_name, co.code as country_code
                                   FROM visa_applications va
                                   JOIN countries co ON va.country_id = co.id
                                   WHERE va.student_id = ?
                                   ORDER BY va.created_at DESC");
$visa_applications->execute([$student_id]);
$visa_applications = $visa_applications->fetchAll();

// Get student's 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
                          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([$_SESSION['user_id'], $_SESSION['user_id'], $student_id, $student_id, $_SESSION['user_id']]);
$messages = $messages->fetchAll();

// Handle form submissions
$error = '';
$success = '';

// Update student status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $new_status = $_POST['status'] ?? '';
    
    if (!in_array($new_status, ['prospective', 'active', 'admitted', 'rejected', 'alumni'])) {
        $error = "Invalid status selected.";
    } else {
        try {
            $stmt = $pdo->prepare("UPDATE students SET status = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$new_status, $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",
                "Counselor updated student {$student_id} status to {$new_status}"
            ]);
            
            $success = "Student status updated successfully!";
            
            // Refresh student data
            $stmt = $pdo->prepare("SELECT s.*, u.email,
                                  CONCAT(c.first_name, ' ', c.last_name) as counselor_name
                                  FROM students s 
                                  LEFT JOIN counselors c ON s.assigned_counselor_id = c.id
                                  JOIN users u ON s.id = u.id 
                                  WHERE s.id = ?");
            $stmt->execute([$student_id]);
            $student = $stmt->fetch(PDO::FETCH_ASSOC);
            
        } catch (Exception $e) {
            $error = "Failed to update student status. Please try again.";
        }
    }
}

// Send message to student
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_message'])) {
    $message_content = trim($_POST['message_content'] ?? '');
    
    if (!empty($message_content)) {
        try {
            // Insert message
            $stmt = $pdo->prepare("INSERT INTO messages (sender_id, receiver_id, content, created_at) 
                                  VALUES (?, ?, ?, NOW())");
            $stmt->execute([$_SESSION['user_id'], $student_id, $message_content]);
            
            // Create notification for student
            $pdo->prepare("INSERT INTO notifications (user_id, title, message, is_read, notification_type, created_at) 
                          VALUES (?, ?, ?, 0, 'message', NOW())")->execute([
                $student_id,
                "New Message from Counselor",
                "You have received a new message from your counselor."
            ]);
            
            // Log the activity
            $pdo->prepare("INSERT INTO activities (user_id, activity_type, description, created_at) 
                          VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "message_sent",
                "Counselor sent a message to student {$student_id}"
            ]);
            
            $success = "Message sent successfully!";
            
        } catch (Exception $e) {
            $error = "Failed to send message. Please try again.";
        }
    } else {
        $error = "Message content cannot be empty.";
    }
}

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: counselor-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, #3fb7fe, #1a73e8);
            color: white;
            border-radius: 10px 10px 0 0;
            padding: 30px;
            margin-bottom: 30px;
        }
        .profile-img {
            width: 120px;
            height: 120px;
            object-fit: cover;
            border: 5px solid white;
            border-radius: 50%;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .section-title {
            position: relative;
            padding-bottom: 10px;
            margin-bottom: 25px;
            border-bottom: 2px solid #3fb7fe;
        }
        .section-title::after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 0;
            width: 60px;
            height: 2px;
            background: #3fb7fe;
        }
        .info-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 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: #333;
            margin-bottom: 5px;
        }
        .status-badge {
            font-size: 0.8em;
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
        }
        .status-prospective {
            background: #fff3cd;
            color: #856404;
        }
        .status-active {
            background: #d1ecf1;
            color: #0c5460;
        }
        .status-admitted {
            background: #d4edda;
            color: #155724;
        }
        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }
        .status-alumni {
            background: #e9ecef;
            color: #495057;
        }
        .application-card {
            border-left: 4px solid #3fb7fe;
            margin-bottom: 15px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        .document-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }
        .document-item:last-child {
            border-bottom: none;
        }
        .message-item {
            margin-bottom: 15px;
            padding: 15px;
            border-radius: 10px;
        }
        .message-sent {
            background: #e7f5ff;
            margin-left: 20%;
            border-left: 4px solid #3fb7fe;
        }
        .message-received {
            background: #f8f9fa;
            margin-right: 20%;
            border-left: 4px solid #28a745;
        }
        .message-meta {
            font-size: 0.8em;
            color: #666;
            margin-top: 5px;
        }
        .tab-content {
            padding: 20px 0;
        }
        .nav-pills .nav-link {
            border-radius: 10px;
            margin: 0 5px;
            padding: 10px 20px;
        }
        .nav-pills .nav-link.active {
            background: #3fb7fe;
            color: white;
        }
        .action-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        .modal-dialog {
            max-width: 500px;
        }
    </style>
</head>
<body>

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

<div class="container py-5">
    <!-- Profile Header -->
    <div class="profile-header">
        <div class="row align-items-center">
            <div class="col-md-2 text-center mb-3 mb-md-0">
                <img src="<?= htmlspecialchars($student['profile_photo'] ?: 'img/profile-placeholder.jpg') ?>" 
                     alt="<?= htmlspecialchars($student['first_name']) ?>" class="profile-img">
            </div>
            <div class="col-md-7">
                <h1><?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?></h1>
                <p class="mb-1"><i class="fas fa-envelope"></i> <?= htmlspecialchars($student['email']) ?></p>
                <p class="mb-1"><i class="fas fa-phone"></i> <?= htmlspecialchars($student['phone'] ?? 'Not provided') ?></p>
                <p><i class="fas fa-map-marker-alt"></i> <?= htmlspecialchars($student['city'] . ', ' . $student['country']) ?></p>
            </div>
            <div class="col-md-3 text-md-right">
                <span class="status-badge status-<?= $student['status'] ?>">
                    <?= ucfirst($student['status']) ?>
                </span>
                <p class="mt-2">Last Login: <?= $student['last_login'] ? date('M j, Y', strtotime($student['last_login'])) : 'Never' ?></p>
            </div>
        </div>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <!-- Tabs -->
    <ul class="nav nav-pills mb-4" id="studentTabs" role="tablist">
        <li class="nav-item">
            <a class="nav-link active" id="profile-tab" data-toggle="pill" href="#profile" role="tab">Profile</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="applications-tab" data-toggle="pill" href="#applications" role="tab">Applications</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="documents-tab" data-toggle="pill" href="#documents" role="tab">Documents</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="visa-tab" data-toggle="pill" href="#visa" role="tab">Visa</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="messages-tab" data-toggle="pill" href="#messages" role="tab">Messages</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="appointments-tab" data-toggle="pill" href="#appointments" role="tab">Appointments</a>
        </li>
    </ul>

    <div class="tab-content">
        <!-- Profile Tab -->
        <div class="tab-pane fade show active" id="profile" role="tabpanel">
            <div class="action-buttons">
                <!-- Update Status Form -->
                <form method="POST" style="display: inline;">
                    <div class="input-group">
                        <select name="status" class="form-control">
                            <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 class="input-group-append">
                            <button type="submit" name="update_status" class="btn btn-primary">Update Status</button>
                        </div>
                    </div>
                </form>
                
                <a href="counselor-messages.php?student_id=<?= $student_id ?>" class="btn btn-outline-primary">
                    <i class="fas fa-comments"></i> Message
                </a>
                
                <a href="counselor-appointments.php?student_id=<?= $student_id ?>" class="btn btn-outline-primary">
                    <i class="fas fa-calendar"></i> Schedule Appointment
                </a>
            </div>
            
            <div class="row">
                <div class="col-lg-8">
                    <h5 class="section-title">Personal Information</h5>
                    <div class="info-card">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="info-item">
                                    <div class="info-label">Full Name</div>
                                    <div><?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Date of Birth</div>
                                    <div><?= $student['date_of_birth'] ? date('F j, Y', strtotime($student['date_of_birth'])) : 'Not provided' ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Gender</div>
                                    <div><?= htmlspecialchars($student['gender'] ?? 'Not provided') ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Phone</div>
                                    <div><?= htmlspecialchars($student['phone'] ?? 'Not provided') ?></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="info-item">
                                    <div class="info-label">Email</div>
                                    <div><?= htmlspecialchars($student['email']) ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Address</div>
                                    <div><?= htmlspecialchars($student['address'] ?? 'Not provided') ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">City</div>
                                    <div><?= htmlspecialchars($student['city'] ?? 'Not provided') ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Country</div>
                                    <div><?= htmlspecialchars($student['country'] ?? 'Not provided') ?></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <h5 class="section-title mt-4">Academic Information</h5>
                    <div class="info-card">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="info-item">
                                    <div class="info-label">Education Level</div>
                                    <div><?= htmlspecialchars($student['education_level'] ?? 'Not provided') ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Current Institution</div>
                                    <div><?= htmlspecialchars($student['current_institution'] ?? 'Not provided') ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Graduation Year</div>
                                    <div><?= $student['graduation_year'] ?? 'Not provided' ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">GPA</div>
                                    <div><?= $student['gpa'] ? number_format($student['gpa'], 2) : 'Not provided' ?></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="info-item">
                                    <div class="info-label">Preferred Countries</div>
                                    <div>
                                        <?php 
                                        $countries = json_decode($student['preferred_countries'] ?? '[]', true);
                                        echo $countries ? implode(', ', $countries) : 'Not specified';
                                        ?>
                                    </div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Preferred Courses</div>
                                    <div>
                                        <?php 
                                        $courses = json_decode($student['preferred_courses'] ?? '[]', true);
                                        echo $courses ? implode(', ', $courses) : 'Not specified';
                                        ?>
                                    </div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Budget</div>
                                    <div><?= $student['budget'] ? '$' . number_format($student['budget']) : 'Not specified' ?></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-lg-4">
                    <h5 class="section-title">Counselor Information</h5>
                    <div class="info-card">
                        <div class="info-item">
                            <div class="info-label">Assigned Counselor</div>
                            <div><?= htmlspecialchars($student['counselor_name'] ?? 'Not assigned') ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Account Created</div>
                            <div><?= date('F j, Y', strtotime($student['created_at'])) ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Last Updated</div>
                            <div><?= date('F j, Y', strtotime($student['updated_at'])) ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Notes</div>
                            <div><?= htmlspecialchars($student['notes'] ?? 'No notes') ?></div>
                        </div>
                    </div>
                    
                    <h5 class="section-title mt-4">Quick Actions</h5>
                    <div class="list-group">
                        <a href="counselor-messages.php?student_id=<?= $student_id ?>" class="list-group-item list-group-item-action">
                            <i class="fas fa-comments mr-2"></i> Send Message
                        </a>
                        <a href="counselor-appointments.php?student_id=<?= $student_id ?>" class="list-group-item list-group-item-action">
                            <i class="fas fa-calendar mr-2"></i> Schedule Appointment
                        </a>
                        <a href="counselor-applications.php" class="list-group-item list-group-item-action">
                            <i class="fas fa-file-alt mr-2"></i> Manage Applications
                        </a>
                        <a href="counselor-document-upload.php?student_id=<?= $student_id ?>" class="list-group-item list-group-item-action">
                            <i class="fas fa-upload mr-2"></i> Request Documents
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Applications Tab -->
        <div class="tab-pane fade" id="applications" role="tabpanel">
            <div class="action-buttons">
                <a href="counselor-applications.php" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Add Application
                </a>
            </div>
            
            <?php if (empty($applications)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-file-alt fa-3x text-muted mb-3"></i>
                    <p>No applications yet. Click "Add Application" to get started.</p>
                </div>
            <?php else: ?>
                <?php foreach ($applications as $app): ?>
                <div class="application-card">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6><?= htmlspecialchars($app['university_name']) ?></h6>
                            <p class="text-muted mb-1"><?= htmlspecialchars($app['program_name']) ?> (<?= htmlspecialchars($app['degree_level']) ?>)</p>
                            <small class="text-muted">Applied <?= date('M j, Y', strtotime($app['created_at'])) ?></small>
                        </div>
                        <div class="text-right">
                            <span class="status-badge" style="background: 
                                <?= $app['application_status'] === 'submitted' ? '#fff3cd; color: #856404' : 
                                   ($app['application_status'] === 'under_review' ? '#d1ecf1; color: #0c5460' :
                                   ($app['application_status'] === 'accepted' ? '#d4edda; color: #155724' :
                                   ($app['application_status'] === 'rejected' ? '#f8d7da; color: #721c24' : '#e9ecef; color: #495057'))) ?>">
                                <?= ucfirst($app['application_status']) ?>
                            </span>
                            <p class="mt-2">
                                <a href="counselor-application-review.php?id=<?= $app['id'] ?>" class="btn btn-sm btn-outline-primary">Review</a>
                            </p>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- Documents Tab -->
        <div class="tab-pane fade" id="documents" role="tabpanel">
            <div class="action-buttons">
                <a href="counselor-document-upload.php?student_id=<?= $student_id ?>" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Request Document
                </a>
            </div>
            
            <?php if (empty($documents)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-folder-open fa-3x text-muted mb-3"></i>
                    <p>No documents uploaded yet.</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Document</th>
                                <th>Status</th>
                                <th>Uploaded</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($documents as $doc): ?>
                            <tr>
                                <td><?= $doc['document_type'] ?></td>
                                <td>
                                    <span class="status-badge status-<?= $doc['status'] ?>">
                                        <?= ucfirst($doc['status']) ?>
                                    </span>
                                </td>
                                <td><?= date('M j, Y', strtotime($doc['created_at'])) ?></td>
                                <td>
                                    <a href="<?= htmlspecialchars($doc['file_path']) ?>" 
                                       class="btn btn-sm btn-primary" target="_blank">
                                        <i class="fas fa-eye"></i> View
                                    </a>
                                    <?php if ($doc['status'] === 'rejected'): ?>
                                    <button class="btn btn-sm btn-warning">
                                        <i class="fas fa-redo"></i> Re-request
                                    </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <!-- Visa Tab -->
        <div class="tab-pane fade" id="visa" role="tabpanel">
            <div class="action-buttons">
                <a href="counselor-visa-applications.php?student_id=<?= $student_id ?>" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Start Visa Application
                </a>
            </div>
            
            <?php if (empty($visa_applications)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-passport fa-3x text-muted mb-3"></i>
                    <p>No visa applications yet.</p>
                </div>
            <?php else: ?>
                <?php foreach ($visa_applications as $visa): ?>
                <div class="application-card">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6><?= htmlspecialchars($visa['country_name']) ?></h6>
                            <p class="text-muted mb-1">Application Status: <?= ucfirst($visa['status']) ?></p>
                            <?php if ($visa['decision_date']): ?>
                            <p class="text-muted mb-1">Decision Date: <?= date('M j, Y', strtotime($visa['decision_date'])) ?></p>
                            <?php endif; ?>
                            <small class="text-muted">Started <?= date('M j, Y', strtotime($visa['created_at'])) ?></small>
                        </div>
                        <div class="text-right">
                            <span class="status-badge" style="background: 
                                <?= $visa['status'] === 'approved' ? '#d4edda; color: #155724' : 
                                   ($visa['status'] === 'rejected' ? '#f8d7da; color: #721c24' :
                                   ($visa['status'] === 'under_review' ? '#d1ecf1; color: #0c5460' : '#fff3cd; color: #856404')) ?>">
                                <?= ucfirst($visa['status']) ?>
                            </span>
                            <p class="mt-2">
                                <a href="counselor-visa-review.php?id=<?= $visa['id'] ?>" class="btn btn-sm btn-outline-primary">Review</a>
                            </p>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- Messages Tab -->
        <div class="tab-pane fade" id="messages" role="tabpanel">
            <div class="action-buttons">
                <!-- Message Form -->
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#messageModal">
                    <i class="fas fa-paper-plane"></i> Send Message
                </button>
            </div>
            
            <?php if (empty($messages)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-comments fa-3x text-muted mb-3"></i>
                    <p>No messages yet. Send a message to start the conversation.</p>
                </div>
            <?php else: ?>
                <div class="message-container" style="height: 500px; overflow-y: auto; border: 1px solid #eee; border-radius: 10px; padding: 20px; background: #f8f9fa;">
                    <?php foreach (array_reverse($messages) as $msg): ?>
                        <div class="message-item message-<?= $msg['message_direction'] ?>">
                            <div class="<?= $msg['message_direction'] === 'sent' ? 'text-right' : 'text-left' ?>">
                                <strong><?= htmlspecialchars($msg['sender_first'] . ' ' . $msg['sender_last']) ?></strong>
                                <div style="background: <?= $msg['message_direction'] === 'sent' ? '#3fb7fe' : '#28a745' ?>; color: white; padding: 10px; border-radius: 10px; display: inline-block; margin: 5px 0; max-width: 80%;">
                                    <?= htmlspecialchars($msg['content']) ?>
                                </div>
                                <div class="message-meta">
                                    <?= date('M j, Y H:i', strtotime($msg['created_at'])) ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- Appointments Tab -->
        <div class="tab-pane fade" id="appointments" role="tabpanel">
            <div class="action-buttons">
                <a href="counselor-appointments.php?student_id=<?= $student_id ?>" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Schedule Appointment
                </a>
            </div>
            
            <?php if (empty($appointments)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-calendar-alt fa-3x text-muted mb-3"></i>
                    <p>No appointments scheduled yet.</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Date & Time</th>
                                <th>Type</th>
                                <th>With</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($appointments as $appt): ?>
                            <tr>
                                <td><?= date('M j, Y H:i', strtotime($appt['scheduled_time'])) ?></td>
                                <td><?= ucfirst($appt['appointment_type']) ?></td>
                                <td><?= htmlspecialchars($appt['counselor_name']) ?></td>
                                <td>
                                    <span class="status-badge <?= $appt['status'] === 'confirmed' ? 'status-active' : 'status-inactive' ?>">
                                        <?= ucfirst($appt['status']) ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if ($appt['google_meet_link']): ?>
                                    <a href="<?= htmlspecialchars($appt['google_meet_link']) ?>" class="btn btn-sm btn-primary" target="_blank">
                                        <i class="fas fa-video"></i> Join
                                    </a>
                                    <?php endif; ?>
                                    <a href="#" class="btn btn-sm btn-outline-primary">Details</a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Message Modal -->
<div class="modal fade" id="messageModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title">Send Message to <?= htmlspecialchars($student['first_name']) ?></h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>Message *</label>
                        <textarea name="message_content" class="form-control" rows="5" required 
                                  placeholder="Type your message here..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="send_message" class="btn btn-primary">Send Message</button>
                </div>
            </form>
        </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>
    // Auto-scroll to bottom of messages
    $(document).ready(function() {
        $('.message-container').scrollTop($('.message-container')[0].scrollHeight);
    });
    
    // Form submission confirmation
    $('form').on('submit', function(e) {
        if ($(this).find('[name="send_message"]').length) {
            if (!confirm('Send this message to the student?')) {
                e.preventDefault();
            }
        }
    });
</script>
</body>
</html>