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

// Get student data
$stmt = $pdo->prepare("SELECT s.*, u.email, 
                      CONCAT(c.first_name, ' ', c.last_name) as counselor_name,
                      c.id as counselor_id
                      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(array($_SESSION['user_id']));
$student = $stmt->fetch(PDO::FETCH_ASSOC);

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

$error = '';
$success = '';

// Get recipient ID from URL
$recipient_id = isset($_GET['recipient_id']) ? $_GET['recipient_id'] : null;
$recipient_type = isset($_GET['recipient_type']) ? $_GET['recipient_type'] : null;

// Get specific recipient information if provided
$recipient = null;
if ($recipient_id && $recipient_type) {
    if ($recipient_type === 'counselor') {
        $stmt = $pdo->prepare("SELECT c.id, c.first_name, c.last_name, u.email 
                              FROM counselors c 
                              JOIN users u ON c.id = u.id 
                              WHERE c.id = ? AND u.is_active = 1");
        $stmt->execute(array($recipient_id));
        $recipient = $stmt->fetch();
    } elseif ($recipient_type === 'admin') {
        $stmt = $pdo->prepare("SELECT a.id, a.first_name, a.last_name, u.email 
                              FROM admins a 
                              JOIN users u ON a.id = u.id 
                              WHERE a.id = ? AND u.is_active = 1");
        $stmt->execute(array($recipient_id));
        $recipient = $stmt->fetch();
    }
}

// Handle message sending
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_message'])) {
    $subject = isset($_POST['subject']) ? trim($_POST['subject']) : '';
    $content = isset($_POST['content']) ? trim($_POST['content']) : '';
    $receiver_id = isset($_POST['receiver_id']) ? $_POST['receiver_id'] : null;
    $receiver_type = isset($_POST['receiver_type']) ? $_POST['receiver_type'] : null;
    
    // Validate form data
    if (empty($subject) || empty($content) || !$receiver_id || !$receiver_type) {
        $error = "Subject, message content, and recipient are required.";
    } else {
        try {
            // Determine receiver user ID based on type
            $receiver_user_id = null;
            
            if ($receiver_type === 'counselor') {
                $stmt = $pdo->prepare("SELECT u.id FROM users u JOIN counselors c ON u.id = c.id WHERE c.id = ? AND u.is_active = 1");
                $stmt->execute(array($receiver_id));
                $receiver_user = $stmt->fetch();
                $receiver_user_id = $receiver_user ? $receiver_user['id'] : null;
            } elseif ($receiver_type === 'admin') {
                $stmt = $pdo->prepare("SELECT u.id FROM users u JOIN admins a ON u.id = a.id WHERE a.id = ? AND u.is_active = 1");
                $stmt->execute(array($receiver_id));
                $receiver_user = $stmt->fetch();
                $receiver_user_id = $receiver_user ? $receiver_user['id'] : null;
            }
            
            if (!$receiver_user_id) {
                $error = "Invalid recipient.";
            } else {
                // Start transaction
                $pdo->beginTransaction();
                
                // Create message
                $stmt = $pdo->prepare("INSERT INTO messages (sender_id, receiver_id, subject, content, created_at) 
                                      VALUES (?, ?, ?, ?, NOW())");
                $stmt->execute(array($_SESSION['user_id'], $receiver_user_id, $subject, $content));
                
                $message_id = $pdo->lastInsertId();
                
                // Handle file attachments
                if (isset($_FILES['attachments']) && !empty($_FILES['attachments']['name'][0])) {
                    $upload_dir = 'uploads/messages/';
                    if (!file_exists($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }
                    
                    $total_files = count($_FILES['attachments']['name']);
                    for ($i = 0; $i < $total_files; $i++) {
                        if ($_FILES['attachments']['error'][$i] === UPLOAD_ERR_OK) {
                            $file_name = $_FILES['attachments']['name'][$i];
                            $file_tmp = $_FILES['attachments']['tmp_name'][$i];
                            $file_size = $_FILES['attachments']['size'][$i];
                            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                            
                            // Validate file
                            $allowed_exts = array('jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx');
                            if (in_array($file_ext, $allowed_exts) && $file_size <= 10 * 1024 * 1024) {
                                $unique_name = $message_id . '_attachment_' . time() . '_' . $i . '.' . $file_ext;
                                $file_path = $upload_dir . $unique_name;
                                
                                if (move_uploaded_file($file_tmp, $file_path)) {
                                    // Insert attachment record
                                    $pdo->prepare("INSERT INTO message_attachments (message_id, file_path, file_name, file_size, created_at) 
                                                  VALUES (?, ?, ?, ?, NOW())")
                                       ->execute(array($message_id, $file_path, $file_name, $file_size));
                                }
                            }
                        }
                    }
                }
                
                // Create notification for recipient
                $sender_name = $student['first_name'] . ' ' . $student['last_name'];
                $pdo->prepare("INSERT INTO notifications (
                    user_id, title, message, is_read, notification_type, related_id, related_type, created_at
                ) VALUES (?, ?, ?, 0, 'message', ?, 'message', NOW())")->execute(array(
                    $receiver_user_id,
                    "New Message from Student",
                    "You have received a new message from {$sender_name}: {$subject}",
                    $message_id
                ));
                
                // Log the activity
                $pdo->prepare("INSERT INTO activities (
                    user_id, activity_type, description, created_at
                ) VALUES (?, ?, ?, NOW())")->execute(array(
                    $_SESSION['user_id'],
                    "message_sent",
                    "Student " . $student['first_name'] . " " . $student['last_name'] . " sent message to {$receiver_type} {$receiver_id}"
                ));
                
                // Commit transaction
                $pdo->commit();
                
                $success = "Message sent successfully!";
                
                // Clear form data
                $_POST = array();
                
                // Redirect to avoid resubmission
                header("Location: student-messages.php?recipient_id={$receiver_id}&recipient_type={$receiver_type}&sent=1");
                exit;
            }
        } catch (Exception $e) {
            $pdo->rollback();
            $error = "Failed to send message. Please try again.";
        }
    }
}

// Get conversation messages if recipient is selected
$messages = array();
if ($recipient) {
    // Get the user ID for the recipient from the users table
    $stmt = $pdo->prepare("SELECT u.id FROM users u 
                          WHERE ((u.id IN (SELECT id FROM counselors WHERE id = ?) AND ? = 'counselor') OR
                                (u.id IN (SELECT id FROM admins WHERE id = ?) AND ? = 'admin'))
                          AND u.is_active = 1");
    $stmt->execute(array($recipient_id, $recipient_type, $recipient_id, $recipient_type));
    $recipient_user = $stmt->fetch();
    
    if ($recipient_user) {
        $recipient_user_id = $recipient_user['id'];
        
        // Updated query to properly handle messages from both sides
        $stmt = $pdo->prepare("SELECT m.*, 
                              CASE 
                                  WHEN m.sender_id = ? THEN 'sent'
                                  ELSE 'received'
                              END as message_direction,
                              CASE
                                  WHEN m.sender_id = ? THEN CONCAT(s.first_name, ' ', s.last_name)
                                  WHEN m.sender_id = u.id AND ? = 'counselor' THEN CONCAT(c.first_name, ' ', c.last_name)
                                  WHEN m.sender_id = u.id AND ? = 'admin' THEN CONCAT(a.first_name, ' ', a.last_name)
                              END as sender_name,
                              u.email as sender_email
                              FROM messages m
                              LEFT JOIN students s ON m.sender_id = s.id
                              LEFT JOIN counselors c ON m.sender_id = c.id
                              LEFT JOIN admins a ON m.sender_id = a.id
                              LEFT JOIN users u ON m.sender_id = u.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(array(
            $_SESSION['user_id'],
            $_SESSION['user_id'],
            $recipient_type,
            $recipient_type,
            $_SESSION['user_id'], 
            $recipient_user_id, 
            $recipient_user_id, 
            $_SESSION['user_id']
        ));
        $messages = $stmt->fetchAll();
        
        // Mark received messages as read
        $pdo->prepare("UPDATE messages SET is_read = 1, read_at = NOW() WHERE receiver_id = ? AND sender_id = ? AND is_read = 0")
            ->execute(array($_SESSION['user_id'], $recipient_user_id));
    }
}

// Get recent conversations for sidebar
$recent_conversations = array();

// Get all potential recipients (counselors and admins)
$potential_recipients = array();

// 1. Always include assigned counselor if exists
if ($student['counselor_id']) {
    $stmt = $pdo->prepare("SELECT c.id, c.first_name, c.last_name, u.email, 'counselor' as type 
                          FROM counselors c 
                          JOIN users u ON c.id = u.id 
                          WHERE c.id = ? AND u.is_active = 1");
    $stmt->execute(array($student['counselor_id']));
    $assigned_counselor = $stmt->fetch();
    if ($assigned_counselor) {
        $potential_recipients[] = $assigned_counselor;
    }
}

// 2. Get all active counselors
$stmt = $pdo->prepare("SELECT c.id, c.first_name, c.last_name, u.email, 'counselor' as type 
                      FROM counselors c 
                      JOIN users u ON c.id = u.id 
                      WHERE u.is_active = 1");
$stmt->execute();
$counselors = $stmt->fetchAll();
foreach ($counselors as $counselor) {
    $found = false;
    foreach ($potential_recipients as $recip) {
        if ($recip['id'] == $counselor['id']) {
            $found = true;
            break;
        }
    }
    if (!$found) {
        $potential_recipients[] = $counselor;
    }
}

// 3. Get all active admins
$stmt = $pdo->prepare("SELECT a.id, a.first_name, a.last_name, u.email, 'admin' as type 
                      FROM admins a 
                      JOIN users u ON a.id = u.id 
                      WHERE u.is_active = 1");
$stmt->execute();
$admins = $stmt->fetchAll();
foreach ($admins as $admin) {
    $potential_recipients[] = $admin;
}

// Get last message timestamps for each recipient
foreach ($potential_recipients as &$recip) {
    $stmt = $pdo->prepare("SELECT MAX(created_at) as last_message_time 
                          FROM messages 
                          WHERE (sender_id = ? AND receiver_id = ?) 
                          OR (sender_id = ? AND receiver_id = ?)");
    $stmt->execute(array(
        $_SESSION['user_id'],
        $recip['id'],
        $recip['id'],
        $_SESSION['user_id']
    ));
    $last_msg = $stmt->fetch();
    $recip['last_message_time'] = $last_msg['last_message_time'] ? $last_msg['last_message_time'] : date('Y-m-d H:i:s', strtotime('-1 year'));
}

// Sort by last message time (most recent first)
usort($potential_recipients, function($a, $b) {
    return strtotime($b['last_message_time']) - strtotime($a['last_message_time']);
});

// Mark notifications as read when viewing messages
$pdo->prepare("UPDATE notifications SET is_read = 1 WHERE user_id = ? AND notification_type = 'message'")
    ->execute(array($_SESSION['user_id']));

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

<!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 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>
        .message-container {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #eee;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 10px;
            max-width: 70%;
        }
        .message.sent {
            background: #3fb7fe;
            color: white;
            align-self: flex-end;
            margin-left: auto;
        }
        .message.received {
            background: #f8f9fa;
            color: #333;
            align-self: flex-start;
        }
        .message-header {
            font-size: 0.9em;
            margin-bottom: 5px;
        }
        .message-content {
            margin-bottom: 5px;
        }
        .message-time {
            font-size: 0.8em;
            opacity: 0.7;
        }
        .attachment {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 8px;
            margin: 5px 0;
            display: flex;
            align-items: center;
        }
        .attachment i {
            margin-right: 10px;
            color: #3fb7fe;
        }
        .sidebar {
            border-right: 1px solid #eee;
            height: 500px;
            overflow-y: auto;
        }
        .conversation-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
        }
        .conversation-item:hover {
            background: #f8f9fa;
        }
        .conversation-name {
            font-weight: 600;
        }
        .conversation-email {
            font-size: 0.8em;
            color: #6c757d;
        }
        .conversation-time {
            font-size: 0.8em;
            color: #6c757d;
        }
        .recipient-selector {
            margin-bottom: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
        }
        .recipient-option {
            cursor: pointer;
            padding: 10px;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            margin-bottom: 10px;
        }
        .recipient-option:hover {
            background: #e9ecef;
        }
        .recipient-option.selected {
            background: #3fb7fe;
            color: white;
            border-color: #3fb7fe;
        }
        .no-messages {
            text-align: center;
            padding: 20px;
            color: #6c757d;
        }
        .badge-counselor {
            background-color: #17a2b8;
        }
        .badge-admin {
            background-color: #6c757d;
        }
    </style>
</head>
<body>

<?php include 'student-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">Communication</h6>
        <h1 class="display-5">Messages</h1>
    </div>

    <?php if (!empty($error)): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>
    
    <?php if (!empty($success)): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
    <?php endif; ?>
    
    <?php if (isset($_GET['sent'])): ?>
        <div class="alert alert-success">Message sent successfully!</div>
    <?php endif; ?>

    <div class="row">
        <!-- Sidebar with recent conversations -->
        <div class="col-lg-3">
            <div class="sidebar">
                <h6>Available Recipients</h6>
                <?php if (empty($potential_recipients)): ?>
                <p class="text-muted">No recipients available.</p>
                <?php else: ?>
                <?php foreach ($potential_recipients as $recip): ?>
                <div class="conversation-item" 
                     onclick="window.location='student-messages.php?recipient_id=<?php echo $recip['id']; ?>&recipient_type=<?php echo $recip['type']; ?>'">
                    <div class="conversation-name">
                        <?php echo htmlspecialchars($recip['first_name'] . ' ' . $recip['last_name']); ?>
                        <span class="badge badge-<?php echo $recip['type'] === 'counselor' ? 'counselor' : 'admin'; ?> ml-2">
                            <?php echo ucfirst($recip['type']); ?>
                        </span>
                        <?php if ($student['counselor_id'] == $recip['id']): ?>
                        <span class="badge badge-primary ml-1">Assigned</span>
                        <?php endif; ?>
                    </div>
                    <div class="conversation-email">
                        <?php echo htmlspecialchars($recip['email']); ?>
                    </div>
                    <div class="conversation-time">
                        <?php 
                        if ($recip['last_message_time'] && $recip['last_message_time'] > date('Y-m-d H:i:s', strtotime('-1 year'))) {
                            echo date('M j, H:i', strtotime($recip['last_message_time']));
                        } else {
                            echo 'No messages yet';
                        }
                        ?>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <div class="col-lg-9">
            <?php if ($recipient): ?>
            <!-- Conversation header -->
            <div class="card mb-4">
                <div class="card-body">
                    <h5>Conversation with <?php echo htmlspecialchars($recipient['first_name'] . ' ' . $recipient['last_name']); ?></h5>
                    <p class="text-muted"><?php echo htmlspecialchars($recipient['email']); ?></p>
                    <p class="text-muted"><strong>Type:</strong> <?php echo ucfirst($recipient_type); ?></p>
                    <?php if ($student['counselor_id'] == $recipient['id'] && $recipient_type == 'counselor'): ?>
                    <p class="text-muted"><strong>This is your assigned counselor</strong></p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Messages -->
            <div class="message-container">
                <?php if (empty($messages)): ?>
                <div class="no-messages">
                    <i class="fas fa-comments fa-3x mb-3"></i>
                    <p>No messages yet. Send the first message!</p>
                </div>
                <?php else: ?>
                <?php foreach ($messages as $msg): ?>
                <div class="message <?php echo $msg['message_direction']; ?>">
                    <div class="message-header">
                        <?php echo htmlspecialchars($msg['sender_name']); ?>
                        <?php if ($msg['message_direction'] === 'received'): ?>
                        <span class="badge <?php echo $recipient_type === 'counselor' ? 'badge-counselor' : 'badge-admin'; ?> ml-2">
                            <?php echo ucfirst($recipient_type); ?>
                        </span>
                        <?php else: ?>
                        <span class="badge badge-primary ml-2">You</span>
                        <?php endif; ?>
                    </div>
                    <div class="message-content">
                        <strong><?php echo htmlspecialchars($msg['subject']); ?></strong><br>
                        <?php echo nl2br(htmlspecialchars($msg['content'])); ?>
                    </div>
                    <?php 
                    // Get attachments for this message
                    $attachments = $pdo->prepare("SELECT * FROM message_attachments WHERE message_id = ?");
                    $attachments->execute(array($msg['id']));
                    $attachments = $attachments->fetchAll();
                    
                    foreach ($attachments as $att): ?>
                    <div class="attachment">
                        <i class="fas fa-paperclip"></i>
                        <a href="<?php echo htmlspecialchars($att['file_path']); ?>" target="_blank">
                            <?php echo htmlspecialchars($att['file_name']); ?>
                            (<?php echo number_format($att['file_size'] / 1024, 1); ?> KB)
                        </a>
                    </div>
                    <?php endforeach; ?>
                    <div class="message-time">
                        <?php echo date('M j, H:i', strtotime($msg['created_at'])); ?>
                        <?php if ($msg['message_direction'] === 'received' && $msg['is_read']): ?>
                        <span class="ml-2"><i class="fas fa-check-double text-muted"></i> Read</span>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <!-- Message form -->
            <div class="card">
                <div class="card-body">
                    <h5>Send New Message</h5>
                    <form method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="receiver_id" value="<?php echo $recipient_id; ?>">
                        <input type="hidden" name="receiver_type" value="<?php echo $recipient_type; ?>">
                        
                        <div class="form-group">
                            <label>Subject *</label>
                            <input type="text" name="subject" class="form-control" 
                                   value="<?php echo isset($_POST['subject']) ? htmlspecialchars($_POST['subject']) : ''; ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Message *</label>
                            <textarea name="content" class="form-control" rows="5" required><?php echo isset($_POST['content']) ? htmlspecialchars($_POST['content']) : ''; ?></textarea>
                        </div>
                        <div class="form-group">
                            <label>Attachments</label>
                            <input type="file" name="attachments[]" class="form-control" multiple>
                            <small class="form-text text-muted">You can attach multiple files (JPG, PNG, PDF, DOC, etc., max 10MB each)</small>
                        </div>
                        <button type="submit" name="send_message" class="btn btn-primary">Send Message</button>
                    </form>
                </div>
            </div>
            <?php else: ?>
            <div class="card">
                <div class="card-body text-center">
                    <i class="fas fa-comments fa-3x text-muted mb-3"></i>
                    <h5>Select a conversation from the sidebar</h5>
                    <p class="text-muted">Choose a counselor or admin from the list to start a conversation.</p>
                    <?php if ($student['counselor_id']): ?>
                    <p class="text-muted">You can start a conversation with your assigned counselor.</p>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </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 message container
    $(document).ready(function() {
        $('.message-container').scrollTop($('.message-container')[0].scrollHeight);
    });
    
    // Confirm before leaving if there's unsaved message
    $('form').on('submit', function(e) {
        const subject = $('input[name="subject"]').val();
        const content = $('textarea[name="content"]').val();
        
        if (subject || content) {
            return true;
        } else {
            e.preventDefault();
        }
    });
</script>
</body>
</html>