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

// ==========================================
// 🛠️ AUTO-FIX DATABASE: Communication Tables
// ==========================================
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `notifications` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `student_id` int(11) NOT NULL,
        `text` text NOT NULL,
        `icon` varchar(50) DEFAULT 'fa-bell text-warning',
        `is_unread` tinyint(1) DEFAULT 1,
        `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    $pdo->exec("CREATE TABLE IF NOT EXISTS `messages` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `student_id` int(11) NOT NULL,
        `sender_role` enum('student','admin','teacher') NOT NULL,
        `message` text NOT NULL,
        `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
} catch(PDOException $e) {}

include 'includes/user_header.php'; 
if(file_exists('includes/sidebar.php')) { include 'includes/sidebar.php'; } 

$student_id = $_SESSION['student_id'] ?? null;
if (!$student_id) { echo "<script>window.location.href='login.php';</script>"; exit; }

// ==========================================
// ⚙️ HANDLE SEND MESSAGE
// ==========================================
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['send_msg'])) {
    $msg = trim($_POST['chat_message']);
    if (!empty($msg)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO messages (student_id, sender_role, message) VALUES (?, 'student', ?)");
            $stmt->execute([$student_id, $msg]);
            echo "<script>window.location.href='communication.php';</script>"; exit;
        } catch(Exception $e) {}
    }
}

// ==========================================
// ⚙️ SAFE DATA FETCHING (Fixed Column Error)
// ==========================================

// 1. WhatsApp Settings (Error-proof logic)
$whatsapp_number = "+8801700000000"; // Default
try {
    $set_check = $pdo->query("SELECT whatsapp FROM settings LIMIT 1");
    if($set_check) {
        $settings = $set_check->fetch();
        if($settings) { $whatsapp_number = $settings['whatsapp']; }
    }
} catch (Exception $e) { /* Column doesn't exist yet, using default */ }

// 2. Announcements
$announcements = [];
try {
    $announcements = $pdo->query("SELECT * FROM notices ORDER BY id DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {}

// 3. Notifications
$notifications = [];
try {
    $notif_stmt = $pdo->prepare("SELECT * FROM notifications WHERE student_id = ? ORDER BY id DESC LIMIT 10");
    $notif_stmt->execute([$student_id]);
    $notifications = $notif_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {}

// 4. Chat History
$chats = [];
try {
    $chat_stmt = $pdo->prepare("SELECT * FROM messages WHERE student_id = ? ORDER BY created_at ASC");
    $chat_stmt->execute([$student_id]);
    $chats = $chat_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {}
?>

<style>
    :root { --primary: #064e3b; --accent: #d4af37; --bg: #f8fafc; }
    .main-content { background-color: var(--bg); min-height: 100vh; padding-bottom: 50px; }
    .fade-up { animation: fadeInUp 0.5s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(20px); } 100% { opacity: 1; transform: translateY(0); } }

    /* Premium UI Elements */
    .wa-banner { background: linear-gradient(135deg, #128C7E 0%, #075E54 100%); border-radius: 20px; padding: 25px; color: white; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 10px 25px rgba(18, 140, 126, 0.2); margin-bottom: 25px; }
    .btn-wa { background: #25D366; color: white; border-radius: 12px; padding: 12px 25px; font-weight: 800; text-decoration: none; transition: 0.3s; }
    .btn-wa:hover { background: #fff; color: #075E54; transform: translateY(-3px); }

    .custom-tabs .nav-link { font-weight: 700; color: #64748b; border-radius: 12px; padding: 12px 20px; margin-right: 10px; transition: 0.3s; background: #fff; border: 1px solid #e2e8f0; }
    .custom-tabs .nav-link.active { background: var(--primary); color: #fff; border-color: var(--primary); box-shadow: 0 5px 15px rgba(6, 78, 59, 0.2); }

    /* Chat Styling */
    .chat-box { background: #f1f5f9; border-radius: 15px; height: 400px; overflow-y: auto; padding: 20px; border: 1px solid #e2e8f0; display: flex; flex-direction: column; }
    .chat-bubble { max-width: 80%; padding: 12px 18px; border-radius: 18px; margin-bottom: 12px; font-size: 14px; }
    .bubble-teacher { background: #fff; color: #1e293b; align-self: flex-start; border-bottom-left-radius: 2px; }
    .bubble-student { background: var(--primary); color: white; align-self: flex-end; border-bottom-right-radius: 2px; box-shadow: 0 4px 12px rgba(6, 78, 59, 0.15); }
    .time-stamp { font-size: 9px; opacity: 0.7; margin-top: 5px; display: block; }

    .notice-card { border-left: 5px solid var(--primary); background: #fff; padding: 20px; border-radius: 12px; margin-bottom: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.02); }

    #sidebarToggle { display: none; }
    @media (max-width: 991.98px) {
        #sidebarToggle { display: inline-flex; align-items: center; justify-content: center; width: 40px; height: 40px; background: #fff; border: 1px solid #ddd; border-radius: 10px; margin-right: 15px; cursor: pointer; color: var(--primary); }
        .wa-banner { flex-direction: column; text-align: center; gap: 20px; }
    }
</style>

<div class="main-content p-3 p-md-5">
    
    <div class="d-flex align-items-center mb-5 fade-up">
        <div>
            <h2 class="fw-bold text-dark mb-1">Communication Hub</h2>
            <p class="text-muted fw-semibold mb-0">Direct support from Ahmad Academy</p>
        </div>
    </div>

    <div class="wa-banner fade-up">
        <div>
            <h4 class="fw-bold mb-1"><i class="fab fa-whatsapp me-2"></i> WhatsApp Support</h4>
            <p class="mb-0 opacity-75">Connect instantly with our team for any queries.</p>
        </div>
        <a href="https://wa.me/<?= str_replace(['+', ' '], '', $whatsapp_number) ?>" target="_blank" class="btn-wa">
            CHAT NOW
        </a>
    </div>

    <ul class="nav nav-pills custom-tabs mb-4 fade-up">
        <li class="nav-item"><button class="nav-link active" data-bs-toggle="pill" data-bs-target="#chat-pane"><i class="fas fa-comment-alt me-2"></i>Teacher Chat</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#notice-pane"><i class="fas fa-bullhorn me-2"></i>Academy Notices</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#alert-pane"><i class="fas fa-bell me-2"></i>System Alerts</button></li>
    </ul>

    <div class="tab-content fade-up">
        
        <div class="tab-pane fade show active" id="chat-pane">
            <div class="card border-0 shadow-sm p-4" style="border-radius: 20px;">
                <div class="chat-box mb-4" id="chatScroll">
                    <?php if(empty($chats)): ?>
                        <div class="text-center my-auto opacity-50"><p class="fw-bold">No messages yet. Say Assalamu Alaikum!</p></div>
                    <?php else: foreach($chats as $msg): ?>
                        <div class="chat-bubble <?= ($msg['sender_role'] == 'student') ? 'bubble-student' : 'bubble-teacher' ?>">
                            <?= htmlspecialchars($msg['message']) ?>
                            <span class="time-stamp"><?= date('h:i A', strtotime($msg['created_at'])) ?></span>
                        </div>
                    <?php endforeach; endif; ?>
                </div>
                <form method="POST">
                    <div class="input-group">
                        <input type="text" name="chat_message" class="form-control border-0 bg-light p-3" style="border-radius: 15px 0 0 15px;" placeholder="Type a message..." required>
                        <button type="submit" name="send_msg" class="btn btn-success px-4" style="border-radius: 0 15px 15px 0;"><i class="fas fa-paper-plane"></i></button>
                    </div>
                </form>
            </div>
        </div>

        <div class="tab-pane fade" id="notice-pane">
            <div class="card border-0 shadow-sm p-4" style="border-radius: 20px;">
                <h5 class="fw-bold mb-4">Official Announcements</h5>
                <?php if(empty($announcements)): ?>
                    <p class="text-center py-5">No notices found.</p>
                <?php else: foreach($announcements as $n): ?>
                    <div class="notice-card">
                        <h6 class="fw-bold"><?= htmlspecialchars($n['title']) ?></h6>
                        <p class="text-muted small mb-0"><?= nl2br(htmlspecialchars($n['content'])) ?></p>
                        <small class="text-muted mt-2 d-block fw-bold"><?= date('d M, Y', strtotime($n['created_at'])) ?></small>
                    </div>
                <?php endforeach; endif; ?>
            </div>
        </div>

        <div class="tab-pane fade" id="alert-pane">
            <div class="card border-0 shadow-sm p-4" style="border-radius: 20px;">
                <h5 class="fw-bold mb-4">Your Recent Alerts</h5>
                <?php if(empty($notifications)): ?>
                    <p class="text-center py-5">You have no new notifications.</p>
                <?php else: foreach($notifications as $notif): ?>
                    <div class="d-flex gap-3 p-3 border-bottom">
                        <div class="bg-light rounded-circle p-3"><i class="fas <?= htmlspecialchars($notif['icon']) ?>"></i></div>
                        <div>
                            <p class="mb-0 text-dark fw-bold" style="font-size: 14px;"><?= htmlspecialchars($notif['text']) ?></p>
                            <small class="text-muted"><?= date('d M, h:i A', strtotime($notif['created_at'])) ?></small>
                        </div>
                    </div>
                <?php endforeach; endif; ?>
            </div>
        </div>

    </div>
</div>

<script>
    const chatScroll = document.getElementById('chatScroll');
    if(chatScroll) { chatScroll.scrollTop = chatScroll.scrollHeight; }
    document.getElementById('sidebarToggle')?.addEventListener('click', () => {
        document.getElementById('sidebarMenu').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/user_footer.php'; ?>