<?php 
// Advanced Configuration
ini_set('display_errors', 1); error_reporting(E_ALL);
date_default_timezone_set('Asia/Dhaka');
require_once '../db_connect.php'; 

// Admin Security Check
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['admin_logged_in'])) { header("Location: login.php"); exit; }

$success_msg = ''; $error_msg = '';
$selected_student_id = isset($_GET['student_id']) ? (int)$_GET['student_id'] : 0;

// ==========================================
// ⚙️ HANDLE ADMIN REPLY
// ==========================================
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['send_reply'])) {
    $msg = trim($_POST['reply_message']);
    $stu_id = (int)$_POST['target_student'];
    
    if (!empty($msg) && $stu_id > 0) {
        try {
            $stmt = $pdo->prepare("INSERT INTO messages (student_id, sender_role, message) VALUES (?, 'admin', ?)");
            $stmt->execute([$stu_id, $msg]);
            
            // Mark notifications as read if applicable
            $pdo->prepare("UPDATE notifications SET is_unread = 0 WHERE student_id = ? AND icon LIKE '%comment%'")->execute([$stu_id]);
            
            header("Location: manage_messages.php?student_id=" . $stu_id); exit;
        } catch(Exception $e) { $error_msg = "Failed to send message."; }
    }
}

include 'includes/header.php'; 
include 'includes/sidebar.php'; 

// 1. Fetch Students who have initiated chat (Inbox List)
$inbox_query = "
    SELECT s.id, s.name, MAX(m.created_at) as last_msg_time,
    (SELECT message FROM messages WHERE student_id = s.id ORDER BY id DESC LIMIT 1) as last_message
    FROM students s
    JOIN messages m ON s.id = m.student_id
    GROUP BY s.id
    ORDER BY last_msg_time DESC
";
$inbox_list = $pdo->query($inbox_query)->fetchAll(PDO::FETCH_ASSOC);

// 2. Fetch specific conversation if a student is selected
$chats = [];
$target_student_name = "";
if ($selected_student_id > 0) {
    $chat_stmt = $pdo->prepare("SELECT * FROM messages WHERE student_id = ? ORDER BY created_at ASC");
    $chat_stmt->execute([$selected_student_id]);
    $chats = $chat_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $name_stmt = $pdo->prepare("SELECT name FROM students WHERE id = ?");
    $name_stmt->execute([$selected_student_id]);
    $target_student_name = $name_stmt->fetchColumn();
}
?>

<style>
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg-soft: #f8fafc; }
    .main-content { background-color: var(--bg-soft); height: 100vh; padding: 20px; overflow: hidden; font-family: 'Outfit', sans-serif; }
    
    /* Layout */
    .chat-layout { display: flex; background: #fff; border-radius: 24px; height: calc(100vh - 140px); box-shadow: 0 10px 40px rgba(0,0,0,0.05); overflow: hidden; border: 1px solid #e2e8f0; }
    
    /* Left Side: Inbox List */
    .inbox-list { width: 380px; border-right: 1px solid #f1f5f9; display: flex; flex-direction: column; background: #fff; }
    .inbox-header { padding: 25px; border-bottom: 1px solid #f1f5f9; }
    .student-items { flex-grow: 1; overflow-y: auto; }
    .student-link { display: flex; align-items: center; padding: 18px 25px; text-decoration: none; color: inherit; transition: 0.3s; border-bottom: 1px solid #fafafa; }
    .student-link:hover { background: #f8fafc; }
    .student-link.active { background: rgba(6, 78, 59, 0.05); border-left: 5px solid var(--theme-green); }
    
    .avatar { width: 50px; height: 50px; background: #f1f5f9; border-radius: 15px; display: flex; align-items: center; justify-content: center; font-weight: 800; color: var(--theme-green); margin-right: 15px; flex-shrink: 0; font-size: 18px; border: 1px solid #e2e8f0; }
    .active .avatar { background: var(--theme-green); color: #fff; border-color: var(--theme-green); }

    /* Right Side: Chat Window */
    .chat-window { flex-grow: 1; display: flex; flex-direction: column; background: #fff; position: relative; }
    .chat-header { padding: 15px 25px; border-bottom: 1px solid #f1f5f9; display: flex; align-items: center; justify-content: space-between; background: #fff; z-index: 10; }
    .chat-body { flex-grow: 1; padding: 25px; overflow-y: auto; background: #f4f7f6; display: flex; flex-direction: column; background-image: url('https://www.transparenttextures.com/patterns/cubes.png'); }
    
    /* Bubbles */
    .bubble { max-width: 75%; padding: 14px 20px; border-radius: 20px; margin-bottom: 15px; font-size: 14px; line-height: 1.6; position: relative; }
    .bubble-student { background: #fff; color: #1e293b; align-self: flex-start; border-bottom-left-radius: 4px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); border: 1px solid #e2e8f0; }
    .bubble-admin { background: var(--theme-green); color: #fff; align-self: flex-end; border-bottom-right-radius: 4px; box-shadow: 0 8px 20px rgba(6, 78, 59, 0.15); }
    .chat-time { font-size: 10px; opacity: 0.7; display: block; margin-top: 8px; font-weight: 600; }

    /* Footer */
    .chat-footer { padding: 20px 25px; background: #fff; border-top: 1px solid #f1f5f9; }
    .reply-input { border-radius: 15px; border: 2px solid #f1f5f9; padding: 14px 25px; background: #f8fafc; font-weight: 500; transition: 0.3s; }
    .reply-input:focus { border-color: var(--theme-green); background: #fff; box-shadow: 0 0 0 4px rgba(6, 78, 59, 0.05); }
    .send-btn { width: 50px; height: 50px; border-radius: 15px; background: var(--theme-dark); color: var(--theme-gold); border: none; transition: 0.3s; display: flex; align-items: center; justify-content: center; font-size: 18px; }
    .send-btn:hover { transform: scale(1.05); background: var(--theme-green); color: #fff; }

    /* Header Controls */
    #sidebarToggle { width: 45px; height: 45px; border-radius: 12px; background: #fff; border: 1px solid #e2e8f0; color: var(--theme-green); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; margin-right: 15px; }

    /* Mobile Responsive View System */
    @media (max-width: 991px) {
        .inbox-list { width: 100%; display: <?= ($selected_student_id > 0) ? 'none' : 'flex' ?>; }
        .chat-window { display: <?= ($selected_student_id > 0) ? 'flex' : 'none' ?>; }
        .main-content { padding: 10px; }
        .bubble { max-width: 85%; }
    }
</style>

<div class="main-content">
    <div class="d-flex align-items-center mb-3">
        <button id="sidebarToggle" class="shadow-sm"><i class="fas fa-bars"></i></button>
        <h4 class="fw-bold text-dark mb-0"><i class="fas fa-headset me-2 text-success"></i> Support Center</h4>
    </div>

    <div class="chat-layout fade-up">
        <div class="inbox-list">
            <div class="inbox-header">
                <h5 class="fw-bold mb-0 text-dark">Active Enquiries</h5>
                <small class="text-muted fw-bold">Students waiting for reply</small>
            </div>
            <div class="student-items">
                <?php foreach($inbox_list as $item): ?>
                    <a href="?student_id=<?= $item['id'] ?>" class="student-link <?= ($selected_student_id == $item['id']) ? 'active' : '' ?>">
                        <div class="avatar"><?= strtoupper(substr($item['name'], 0, 1)) ?></div>
                        <div class="name-preview flex-grow-1 overflow-hidden">
                            <div class="d-flex justify-content-between align-items-center mb-1">
                                <h6 class="fw-bold mb-0 text-dark" style="font-size: 14px;"><?= htmlspecialchars($item['name']) ?></h6>
                                <small class="text-muted" style="font-size: 10px;"><?= date('h:i A', strtotime($item['last_msg_time'])) ?></small>
                            </div>
                            <p class="text-muted mb-0 small text-truncate" style="font-size: 12px;"><?= htmlspecialchars($item['last_message']) ?></p>
                        </div>
                    </a>
                <?php endforeach; ?>
                <?php if(empty($inbox_list)): ?>
                    <div class="text-center mt-5 opacity-50">
                        <i class="fas fa-comment-slash fa-3x mb-3"></i>
                        <p class="small fw-bold">No message history found.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="chat-window">
            <?php if ($selected_student_id > 0): ?>
                <div class="chat-header">
                    <div class="d-flex align-items-center">
                        <a href="messages.php" class="btn btn-light rounded-pill me-3 d-lg-none shadow-sm"><i class="fas fa-arrow-left"></i></a>
                        
                        <div class="avatar" style="width: 40px; height: 40px; font-size: 14px;"><?= strtoupper(substr($target_student_name, 0, 1)) ?></div>
                        <div>
                            <h6 class="fw-bold mb-0 text-dark" style="font-size: 15px;"><?= htmlspecialchars($target_student_name) ?></h6>
                            <span class="badge bg-success-subtle text-success py-1 px-2" style="font-size: 9px; letter-spacing: 0.5px;">ONLINE STUDENT</span>
                        </div>
                    </div>
                    <div class="d-none d-sm-block">
                        <button class="btn btn-light btn-sm border rounded-pill px-3" onclick="location.reload();"><i class="fas fa-sync-alt"></i> Refresh</button>
                    </div>
                </div>

                <div class="chat-body" id="chatContainer">
                    <?php foreach($chats as $msg): ?>
                        <div class="bubble <?= ($msg['sender_role'] == 'admin') ? 'bubble-admin' : 'bubble-student' ?> fade-up">
                            <?= nl2br(htmlspecialchars($msg['message'])) ?>
                            <span class="chat-time <?= ($msg['sender_role'] == 'admin') ? 'text-white' : 'text-muted' ?>">
                                <?= date('h:i A | d M', strtotime($msg['created_at'])) ?>
                                <?php if($msg['sender_role'] == 'admin'): ?> <i class="fas fa-check-double ms-1"></i> <?php endif; ?>
                            </span>
                        </div>
                    <?php endforeach; ?>
                </div>

                <div class="chat-footer">
                    <form method="POST" class="d-flex gap-3 align-items-center">
                        <input type="hidden" name="target_student" value="<?= $selected_student_id ?>">
                        <input type="text" name="reply_message" class="form-control reply-input shadow-none" placeholder="Write your message to <?= explode(' ', $target_student_name)[0] ?>..." required autofocus autocomplete="off">
                        <button type="submit" name="send_reply" class="send-btn shadow">
                            <i class="fas fa-paper-plane"></i>
                        </button>
                    </form>
                </div>
            <?php else: ?>
                <div class="d-flex flex-column align-items-center justify-content-center h-100 bg-light text-center p-5">
                    <div class="mb-4" style="font-size: 80px; color: #cbd5e1;"><i class="fas fa-comments"></i></div>
                    <h5 class="fw-bold text-dark">Select a Student to Start</h5>
                    <p class="text-muted small" style="max-width: 300px;">Click on a student from the left list to view their messages and reply to their inquiries.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        // Auto Scroll to bottom of chat
        const chatBody = document.getElementById('chatContainer');
        if(chatBody) { 
            chatBody.scrollTop = chatBody.scrollHeight; 
        }

        // Sidebar Toggle for Mobile Hamburger
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                const sidebar = document.querySelector('.sidebar') || document.getElementById('sidebarMenu');
                if (sidebar) { sidebar.classList.toggle('active'); }
            });
        }
    });
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<?php include 'includes/footer.php'; ?>