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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

// Get notices based on user role
$user_role = $_SESSION['user_role'];
$user_id = $_SESSION['user_id'];

// Build query based on user role
$where_conditions = ["n.status = 'active'", "n.publish_date <= CURDATE()"];
$params = [];

if ($user_role == 'student') {
    // Students can see notices for all, students, or their specific class
    $stmt = $pdo->prepare("SELECT class_id FROM students WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $student_class = $stmt->fetchColumn();
    
    if ($student_class) {
        $where_conditions[] = "(n.target_audience IN ('all', 'students') OR (n.target_audience = 'specific_class' AND n.class_id = ?))";
        $params[] = $student_class;
    } else {
        $where_conditions[] = "n.target_audience IN ('all', 'students')";
    }
} elseif ($user_role == 'teacher') {
    // Teachers can see notices for all, teachers, or students
    $where_conditions[] = "n.target_audience IN ('all', 'teachers', 'students')";
} elseif ($user_role == 'parent') {
    // Parents can see notices for all, parents, or students
    $where_conditions[] = "n.target_audience IN ('all', 'parents', 'students')";
}
// Admin can see all notices (no additional conditions)

$where_clause = implode(' AND ', $where_conditions);

// Get notices
$sql = "
    SELECT n.*, c.name as class_name, c.section as class_section,
           u.username as created_by_name
    FROM notices n
    LEFT JOIN classes c ON n.class_id = c.id
    LEFT JOIN users u ON n.created_by = u.id
    WHERE $where_clause
    ORDER BY n.priority DESC, n.created_at DESC
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$notices = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>নোটিশ বোর্ড - স্কুল ম্যানেজমেন্ট সিস্টেম</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        /* Reduce flicker when opening modal and hovering */
        .modal .modal-dialog, .modal .modal-content { transform: translateZ(0); backface-visibility: hidden; }
        .notice-card { will-change: auto; }
        .notice-card:hover { transform: none !important; }
        /* Disable hover transform on this page to avoid flicker */
        .card:hover { transform: none !important; }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="../index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
                <a class="nav-link" href="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> লগআউট
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5><i class="fas fa-bullhorn"></i> নোটিশ বোর্ড</h5>
                        <?php if ($_SESSION['user_role'] == 'admin' || $_SESSION['user_role'] == 'teacher'): ?>
                        <a href="add.php" class="btn btn-success btn-sm">
                            <i class="fas fa-plus"></i> নতুন নোটিশ
                        </a>
                        <?php endif; ?>
                    </div>
                    <div class="card-body">
                        <?php if (empty($notices)): ?>
                            <div class="text-center py-5">
                                <i class="fas fa-bullhorn fa-4x text-muted mb-3"></i>
                                <h4 class="text-muted">কোন নোটিশ নেই</h4>
                                <p class="text-muted">এই মুহূর্তে কোন নোটিশ প্রকাশিত নেই।</p>
                            </div>
                        <?php else: ?>
                            <div class="row">
                                <?php foreach ($notices as $notice): ?>
                                    <div class="col-md-6 col-lg-4 mb-4">
                                        <div class="card h-100 notice-card">
                                            <div class="card-header d-flex justify-content-between align-items-start">
                                                <div>
                                                    <?php
                                                    $priority_class = '';
                                                    $priority_text = '';
                                                    switch ($notice['priority']) {
                                                        case 'urgent':
                                                            $priority_class = 'bg-danger';
                                                            $priority_text = 'জরুরি';
                                                            break;
                                                        case 'high':
                                                            $priority_class = 'bg-warning';
                                                            $priority_text = 'উচ্চ';
                                                            break;
                                                        case 'medium':
                                                            $priority_class = 'bg-info';
                                                            $priority_text = 'মাধ্যম';
                                                            break;
                                                        case 'low':
                                                            $priority_class = 'bg-secondary';
                                                            $priority_text = 'নিম্ন';
                                                            break;
                                                    }
                                                    ?>
                                                    <span class="badge <?php echo $priority_class; ?>"><?php echo $priority_text; ?></span>
                                                </div>
                                                <small class="text-muted">
                                                    <?php echo date('d/m/Y', strtotime($notice['publish_date'])); ?>
                                                </small>
                                            </div>
                                            <div class="card-body">
                                                <h6 class="card-title"><?php echo htmlspecialchars($notice['title']); ?></h6>
                                                <p class="card-text">
                                                    <?php 
                                                    $content = strip_tags($notice['content']);
                                                    echo strlen($content) > 150 ? substr($content, 0, 150) . '...' : $content; 
                                                    ?>
                                                </p>
                                                
                                                <!-- Target Audience -->
                                                <div class="mb-2">
                                                    <small class="text-muted">
                                                        <i class="fas fa-users"></i> 
                                                        <?php
                                                        switch ($notice['target_audience']) {
                                                            case 'all':
                                                                echo 'সবার জন্য';
                                                                break;
                                                            case 'students':
                                                                echo 'ছাত্র-ছাত্রীদের জন্য';
                                                                break;
                                                            case 'teachers':
                                                                echo 'শিক্ষকদের জন্য';
                                                                break;
                                                            case 'parents':
                                                                echo 'অভিভাবকদের জন্য';
                                                                break;
                                                            case 'specific_class':
                                                                echo $notice['class_name'] . ' - ' . $notice['class_section'] . ' এর জন্য';
                                                                break;
                                                        }
                                                        ?>
                                                    </small>
                                                </div>
                                                
                                                <?php if ($notice['expiry_date'] && strtotime($notice['expiry_date']) > time()): ?>
                                                    <div class="mb-2">
                                                        <small class="text-warning">
                                                            <i class="fas fa-clock"></i> 
                                                            মেয়াদ: <?php echo date('d/m/Y', strtotime($notice['expiry_date'])); ?>
                                                        </small>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                            <div class="card-footer">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <small class="text-muted">
                                                        <?php echo $notice['created_by_name'] ?: 'অজানা'; ?>
                                                    </small>
                                                    <div class="btn-group">
                                                        <button class="btn btn-sm btn-primary" 
                                                                data-bs-toggle="modal" 
                                                                data-bs-target="#noticeModal<?php echo $notice['id']; ?>">
                                                            <i class="fas fa-eye"></i> বিস্তারিত
                                                        </button>
                                                        <?php if (in_array($_SESSION['user_role'], ['admin','teacher'])): ?>
                                                        <a href="edit.php?id=<?=$notice['id']?>" class="btn btn-sm btn-warning">
                                                            <i class="fas fa-edit"></i> এডিট
                                                        </a>
                                                        <form method="POST" action="delete.php" onsubmit="return confirm('নোটিশ ডিলিট করবেন?');" style="display:inline-block;">
                                                            <input type="hidden" name="id" value="<?=$notice['id']?>">
                                                            <button type="submit" class="btn btn-sm btn-danger">
                                                                <i class="fas fa-trash"></i> ডিলিট
                                                            </button>
                                                        </form>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Notice Modal -->
                                    <div class="modal fade" id="noticeModal<?php echo $notice['id']; ?>" tabindex="-1">
                                        <div class="modal-dialog modal-lg">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title"><?php echo htmlspecialchars($notice['title']); ?></h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                </div>
                                                <div class="modal-body">
                                                    <div class="mb-3">
                                                        <div class="row">
                                                            <div class="col-md-6">
                                                                <strong>প্রকাশের তারিখ:</strong> 
                                                                <?php echo date('d/m/Y', strtotime($notice['publish_date'])); ?>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <strong>অগ্রাধিকার:</strong> 
                                                                <span class="badge <?php echo $priority_class; ?>"><?php echo $priority_text; ?></span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="mb-3">
                                                        <strong>লক্ষ্য দর্শক:</strong>
                                                        <?php
                                                        switch ($notice['target_audience']) {
                                                            case 'all':
                                                                echo 'সবার জন্য';
                                                                break;
                                                            case 'students':
                                                                echo 'ছাত্র-ছাত্রীদের জন্য';
                                                                break;
                                                            case 'teachers':
                                                                echo 'শিক্ষকদের জন্য';
                                                                break;
                                                            case 'parents':
                                                                echo 'অভিভাবকদের জন্য';
                                                                break;
                                                            case 'specific_class':
                                                                echo $notice['class_name'] . ' - ' . $notice['class_section'] . ' এর জন্য';
                                                                break;
                                                        }
                                                        ?>
                                                    </div>
                                                    
                                                    <?php if ($notice['expiry_date']): ?>
                                                    <div class="mb-3">
                                                        <strong>মেয়াদ উত্তীর্ণ:</strong> 
                                                        <?php echo date('d/m/Y', strtotime($notice['expiry_date'])); ?>
                                                    </div>
                                                    <?php endif; ?>
                                                    
                                                    <div class="mb-3">
                                                        <strong>বিস্তারিত:</strong>
                                                        <div class="mt-2">
                                                            <?php echo nl2br(htmlspecialchars($notice['content'])); ?>
                                                        </div>
                                                    </div>
                                                    
                                                    <?php if ($notice['attachment']): ?>
                                                    <div class="mb-3">
                                                        <strong>সংযুক্তি:</strong>
                                                        <a href="../<?php echo $notice['attachment']; ?>" 
                                                           class="btn btn-sm btn-outline-primary" 
                                                           target="_blank">
                                                            <i class="fas fa-download"></i> ডাউনলোড
                                                        </a>
                                                    </div>
                                                    <?php endif; ?>
                                                </div>
                                                <div class="modal-footer">
                                                    <small class="text-muted me-auto">
                                                        প্রকাশক: <?php echo $notice['created_by_name'] ?: 'অজানা'; ?>
                                                    </small>
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ করুন</button>
                                                    <button type="button" class="btn btn-primary" onclick="printNotice(<?php echo $notice['id']; ?>)">
                                                        <i class="fas fa-print"></i> প্রিন্ট
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/js/script.js"></script>
    <script>
        function printNotice(noticeId) {
            const modal = document.getElementById('noticeModal' + noticeId);
            const modalContent = modal.querySelector('.modal-content').innerHTML;
            
            const printWindow = window.open('', '_blank');
            if (!printWindow) { alert('পপআপ ব্লক হয়েছে। ব্রাউজারের পপআপ অনুমতি দিন।'); return; }
            printWindow.document.open();
            printWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>নোটিশ প্রিন্ট</title>
                    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
                    <style>
                        @media print {
                            .modal-header, .modal-footer { display: none !important; }
                            .btn-close { display: none !important; }
                        }
                    </style>
                </head>
                <body>
                    <div class="container mt-4">
                        <div class="modal-content">
                            ${modalContent}
                        </div>
                    </div>
                    <script>
                        window.onload = function() {
                            window.print();
                            window.onafterprint = function() {
                                window.close();
                            }
                        }
                    <\/script>
                </body>
                </html>
            `);
            try { printWindow.document.close(); } catch(e){}
        }
        
        // Add animation to notice cards
        document.addEventListener('DOMContentLoaded', function() {
            const noticeCards = document.querySelectorAll('.notice-card');
            // Add animation only once; avoid re-adding on mouse move
            noticeCards.forEach((card, index) => {
                if (!card.dataset.animated) {
                    card.style.animationDelay = `${index * 0.1}s`;
                    card.classList.add('fade-in-up');
                    card.dataset.animated = '1';
                }
            });
        });
    </script>
</body>
</html>