<?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 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(array($_SESSION['user_id']));
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

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

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

// Get student ID if provided in URL
$student_id = isset($_GET['student_id']) ? $_GET['student_id'] : null;
$counselor_id = isset($_GET['counselor_id']) ? $_GET['counselor_id'] : null;

// Get recipient information
$recipient = null;
$recipient_type = null;

if ($student_id) {
    $stmt = $pdo->prepare("SELECT s.id, s.first_name, s.last_name, u.email FROM students s JOIN users u ON s.id = u.id WHERE s.id = ?");
    $stmt->execute(array($student_id));
    $recipient = $stmt->fetch();
    $recipient_type = 'student';
} elseif ($counselor_id) {
    $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 = ?");
    $stmt->execute(array($counselor_id));
    $recipient = $stmt->fetch();
    $recipient_type = 'counselor';
}

// 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']) : '';
    
    // Validate form data
    if (empty($subject) || empty($content)) {
        $error = "Subject and message content are required.";
    } else {
        try {
            // Determine recipient ID and type
            $receiver_id = null;
            if ($student_id) {
                $receiver_id = $student_id;
            } elseif ($counselor_id) {
                $receiver_id = $counselor_id;
            }
            
            if (!$receiver_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_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
                if ($recipient) {
                    $recipient_name = $recipient['first_name'] . ' ' . $recipient['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_id,
                        "New Message from Admin",
                        "You have received a new message from " . $admin['first_name'] . " " . $admin['last_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",
                    "Admin " . $admin['first_name'] . " " . $admin['last_name'] . " sent message to " . ($recipient ? $recipient_name : 'unknown recipient')
                ));
                
                // Commit transaction
                $pdo->commit();
                
                $success = "Message sent successfully!";
                
                // Clear form data
                $_POST = array();
                
                // Redirect to avoid resubmission
                if ($student_id) {
                    header("Location: admin-messages.php?student_id=" . $student_id . "&sent=1");
                } elseif ($counselor_id) {
                    header("Location: admin-messages.php?counselor_id=" . $counselor_id . "&sent=1");
                } else {
                    header("Location: admin-messages.php?sent=1");
                }
                exit;
            }
        } catch (Exception $e) {
            $pdo->rollback();
            $error = "Failed to send message. Please try again.";
        }
    }
}

// Get conversation messages
$messages = array();
if ($student_id || $counselor_id) {
    $receiver_id = $student_id ? $student_id : $counselor_id;
    
    $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, aa.first_name) as sender_first,
                          COALESCE(cs.last_name, ca.last_name, aa.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 aa ON m.sender_id = aa.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'], $receiver_id, $receiver_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($receiver_id, $_SESSION['user_id']));
}

// Get recent conversations for sidebar
$recent_conversations = $pdo->prepare("SELECT DISTINCT 
                                    CASE 
                                        WHEN m.sender_id = ? THEN m.receiver_id 
                                        ELSE m.sender_id 
                                    END as user_id,
                                    CASE 
                                        WHEN m.sender_id = ? THEN 'student' 
                                        ELSE 'counselor' 
                                    END as user_type,
                                    MAX(m.created_at) as last_message_time
                                    FROM messages m
                                    WHERE m.sender_id = ? OR m.receiver_id = ?
                                    GROUP BY user_id, user_type
                                    ORDER BY last_message_time DESC LIMIT 10");
$recent_conversations->execute(array($_SESSION['user_id'], $_SESSION['user_id'], $_SESSION['user_id'], $_SESSION['user_id']));
$recent_conversations = $recent_conversations->fetchAll();

// Process recent conversations to get user details
$conversation_details = array();
foreach ($recent_conversations as $conv) {
    if ($conv['user_type'] === 'student') {
        $stmt = $pdo->prepare("SELECT s.id, s.first_name, s.last_name, u.email FROM students s JOIN users u ON s.id = u.id WHERE s.id = ?");
        $stmt->execute(array($conv['user_id']));
        $user = $stmt->fetch();
        if ($user) {
            $conversation_details[] = array(
                'id' => $user['id'],
                'first_name' => $user['first_name'],
                'last_name' => $user['last_name'],
                'email' => $user['email'],
                'type' => 'student',
                'last_message_time' => $conv['last_message_time']
            );
        }
    } else {
        $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 = ?");
        $stmt->execute(array($conv['user_id']));
        $user = $stmt->fetch();
        if ($user) {
            $conversation_details[] = array(
                'id' => $user['id'],
                'first_name' => $user['first_name'],
                'last_name' => $user['last_name'],
                'email' => $user['email'],
                'type' => 'counselor',
                'last_message_time' => $conv['last_message_time']
            );
        }
    }
}

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-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;
        }
    </style>
</head>
<body>

<?php include 'admin-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>Recent Conversations</h6>
                <?php if (empty($conversation_details)): ?>
                <p class="text-muted">No conversations yet.</p>
                <?php else: ?>
                <?php foreach ($conversation_details as $conv): ?>
                <div class="conversation-item" 
                     onclick="window.location='admin-messages.php?<?php echo $conv['type'] === 'student' ? 'student_id' : 'counselor_id'; ?>=<?php echo $conv['id']; ?>'">
                    <div class="conversation-name">
                        <?php echo htmlspecialchars($conv['first_name'] . ' ' . $conv['last_name']); ?>
                    </div>
                    <div class="conversation-email">
                        <?php echo htmlspecialchars($conv['email']); ?>
                    </div>
                    <div class="conversation-time">
                        <?php echo date('M j, H:i', strtotime($conv['last_message_time'])); ?>
                    </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>
                </div>
            </div>

            <!-- Messages -->
            <div class="message-container">
                <?php if (empty($messages)): ?>
                <div class="text-center text-muted py-5">
                    <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_first'] . ' ' . $msg['sender_last']); ?>
                    </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'])); ?>
                    </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">
                        <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 student or counselor from the list to start a conversation.</p>
                </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>