<?php
session_start();
require_once 'config.php';

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

// Get counselor data
$stmt = $pdo->prepare("SELECT first_name, last_name FROM counselors WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$counselor = $stmt->fetch();

// Initialize variables
$students = [];
$student = null;
$messages = [];

// Get student ID if specified
$student_id = $_GET['student_id'] ?? null;

// Get messages
if ($student_id) {
    // Get messages with specific student
    $stmt = $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 ASC");
    $stmt->execute([$_SESSION['user_id'], $_SESSION['user_id'], $student_id, $student_id, $_SESSION['user_id']]);
    $messages = $stmt->fetchAll();
    
    // Get student info
    $stmt = $pdo->prepare("SELECT first_name, last_name FROM students WHERE id = ?");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();
    
    // Get all students the counselor is communicating with (for the sidebar)
    $stmt = $pdo->prepare("SELECT DISTINCT s.id, s.first_name, s.last_name, 
                          MAX(m.created_at) as last_message
                          FROM messages m
                          JOIN students s ON (m.sender_id = s.id OR m.receiver_id = s.id)
                          WHERE (m.sender_id = ? OR m.receiver_id = ?)
                          AND s.assigned_counselor_id = ?
                          GROUP BY s.id
                          ORDER BY last_message DESC");
    $stmt->execute([$_SESSION['user_id'], $_SESSION['user_id'], $_SESSION['user_id']]);
    $students = $stmt->fetchAll();
} else {
    // Get all students the counselor is communicating with
    $stmt = $pdo->prepare("SELECT DISTINCT s.id, s.first_name, s.last_name, 
                          MAX(m.created_at) as last_message
                          FROM messages m
                          JOIN students s ON (m.sender_id = s.id OR m.receiver_id = s.id)
                          WHERE (m.sender_id = ? OR m.receiver_id = ?)
                          AND s.assigned_counselor_id = ?
                          GROUP BY s.id
                          ORDER BY last_message DESC");
    $stmt->execute([$_SESSION['user_id'], $_SESSION['user_id'], $_SESSION['user_id']]);
    $students = $stmt->fetchAll();
}

// Handle message sending
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_message'])) {
    $message_content = trim($_POST['message_content'] ?? '');
    
    if (!empty($message_content) && $student_id) {
        try {
            // Start transaction
            $pdo->beginTransaction();
            
            // 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}"
            ]);
            
            // Commit transaction
            $pdo->commit();
            
            // Redirect to avoid resubmission
            header("Location: counselor-messages.php?student_id={$student_id}");
            exit;
            
        } catch (Exception $e) {
            $pdo->rollback();
            $error = "Failed to send message. Please try again.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Messages - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <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="css/style.css" rel="stylesheet">
    <style>
        .message-container {
            height: 600px;
            overflow-y: auto;
            border: 1px solid #eee;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            background: #f8f9fa;
        }
        .message {
            margin-bottom: 15px;
            max-width: 70%;
        }
        .message-sent {
            margin-left: auto;
        }
        .message-received {
            margin-right: auto;
        }
        .message-content {
            padding: 12px 18px;
            border-radius: 18px;
            font-size: 14px;
        }
        .message-sent .message-content {
            background: #3fb7fe;
            color: white;
            border-bottom-right-radius: 5px;
        }
        .message-received .message-content {
            background: white;
            color: #333;
            border-bottom-left-radius: 5px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .message-meta {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
            text-align: right;
        }
        .message-received .message-meta {
            text-align: left;
        }
        .sender-info {
            font-weight: 600;
            color: #3fb7fe;
            margin-bottom: 5px;
        }
        .students-list {
            max-height: 600px;
            overflow-y: auto;
            border: 1px solid #eee;
            border-radius: 10px;
        }
        .student-item {
            padding: 15px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
        }
        .student-item:hover {
            background: #f8f9fa;
        }
        .student-item.active {
            background: #e7f5ff;
            border-left: 4px solid #3fb7fe;
        }
        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 5px;
            margin: 10px 0;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>
<body>

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

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Messages</h6>
        <h1 class="display-5">Communicate with Students</h1>
    </div>

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

    <div class="row">
        <?php if (!$student_id): ?>
        <!-- Student List -->
        <div class="col-lg-4">
            <h5>Students</h5>
            <div class="students-list">
                <?php if (empty($students)): ?>
                    <div class="p-4 text-center text-muted">
                        <i class="fas fa-users fa-3x mb-3"></i>
                        <p>No students assigned or communicating yet.</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($students as $s): ?>
                    <a href="counselor-messages.php?student_id=<?= $s['id'] ?>" class="text-decoration-none">
                        <div class="student-item">
                            <div class="d-flex justify-content-between">
                                <strong><?= htmlspecialchars($s['first_name'] . ' ' . $s['last_name']) ?></strong>
                                <small><?= date('M j', strtotime($s['last_message'])) ?></small>
                            </div>
                            <div class="small text-muted">Click to message</div>
                        </div>
                    </a>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
        <div class="col-lg-8">
            <div class="bg-light p-4 rounded">
                <p class="text-center text-muted">Select a student to start messaging</p>
            </div>
        </div>
        <?php else: ?>
        <!-- Message Thread -->
        <div class="col-lg-4">
            <h5>Students</h5>
            <div class="students-list">
                <?php if (empty($students)): ?>
                    <div class="p-4 text-center text-muted">
                        <i class="fas fa-users fa-3x mb-3"></i>
                        <p>No students assigned or communicating yet.</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($students as $s): ?>
                    <a href="counselor-messages.php?student_id=<?= $s['id'] ?>" class="text-decoration-none">
                        <div class="student-item <?= $s['id'] == $student_id ? 'active' : '' ?>">
                            <div class="d-flex justify-content-between">
                                <strong><?= htmlspecialchars($s['first_name'] . ' ' . $s['last_name']) ?></strong>
                                <small><?= date('M j', strtotime($s['last_message'])) ?></small>
                            </div>
                        </div>
                    </a>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
        <div class="col-lg-8">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5><?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?></h5>
                <a href="counselor-appointments.php" class="btn btn-outline-primary btn-sm">
                    <i class="fas fa-calendar"></i> Schedule Appointment
                </a>
            </div>
            
            <div class="message-container" id="messageContainer">
                <?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: ?>
                    <?php foreach ($messages as $msg): ?>
                        <div class="message message-<?= $msg['message_direction'] ?>">
                            <?php if ($msg['message_direction'] === 'received'): ?>
                                <div class="sender-info">
                                    <?= htmlspecialchars($msg['sender_first'] . ' ' . $msg['sender_last']) ?>
                                </div>
                            <?php endif; ?>
                            <div class="message-content">
                                <?= htmlspecialchars($msg['content']) ?>
                            </div>
                            <div class="message-meta">
                                <?= 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" title="Read"></i>
                                <?php elseif ($msg['message_direction'] === 'sent'): ?>
                                    <i class="fas fa-check text-muted" title="Sent"></i>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <!-- Message Form -->
            <form method="POST">
                <div class="input-group">
                    <textarea name="message_content" class="form-control" placeholder="Type your message here..." 
                              rows="3" required style="resize: none;"></textarea>
                    <div class="input-group-append">
                        <button type="submit" name="send_message" class="btn btn-primary">
                            <i class="fas fa-paper-plane"></i> Send
                        </button>
                    </div>
                </div>
            </form>
        </div>
        <?php endif; ?>
    </div>
</div>


<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 message container
    document.getElementById('messageContainer').scrollTop = document.getElementById('messageContainer').scrollHeight;
    
    // Handle form submission
    $('form').on('submit', function(e) {
        const message = $('textarea[name="message_content"]').val().trim();
        if (!message) {
            e.preventDefault();
            alert('Please enter a message.');
        }
    });
</script>
</body>
</html>