<?php
// Filename: public_directory.php
require 'config.php';
requireLogin();

// --- SECURITY: CSRF TOKEN ---
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// 1. FETCH DATA
// Added 'akp' to WHERE clause and adjusted ORDER BY
$sql = "SELECT u.id, u.full_name, u.email, u.phone_number, u.avatar, u.subjects, u.role, u.username, c.class_name 
        FROM users u 
        LEFT JOIN classes c ON c.class_teacher_id = u.id 
        WHERE u.role LIKE '%teacher%' 
           OR u.role LIKE '%principal%' 
           OR u.role LIKE '%assistant%'
           OR u.role LIKE '%admin%'
           OR u.role LIKE '%akp%' 
        ORDER BY 
            CASE 
                WHEN u.role LIKE '%principal%' THEN 1 
                WHEN u.role LIKE '%assistant%' THEN 2 
                WHEN u.role LIKE '%akp%' THEN 4 
                ELSE 3 
            END ASC,
            u.full_name ASC";
$teachers = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);

// Helper to sanitize phone for links
function sanitizePhone($phone) {
    $p = preg_replace('/[^0-9]/', '', $phone);
    if (substr($p, 0, 1) === '0' && strlen($p) > 9) {
        $p = '6' . $p;
    }
    return $p;
}

// Helper to format Role for Display logic
// Added AKP detection
function formatRole($role) {
    if (stripos($role, 'principal') !== false) return 'Principal';
    if (stripos($role, 'assistant') !== false) return 'Assistant Principal';
    if (stripos($role, 'akp') !== false) return 'AKP Staff';
    return 'Teacher';
}

// Current Month for comparison
$current_month_num = date('m'); 
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Staff Directory</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
        :root { 
            --primary-grad: <?= getHeaderTheme() ?>; 
            --primary-color: #8B5CF6;
            --bg-color: #f8f9fd; 
            --text-dark: #1e293b;
            --text-gray: #64748b;
        }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }
        
        /* HEADER */
        .app-header { background: var(--primary-grad); padding: 30px 20px 80px 20px; border-radius: 0 0 35px 35px; color: white; text-align: center; }
        
        /* FLOATING CARD */
        .floating-card { background: white; margin: -60px 20px 20px 20px; border-radius: 24px; padding: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.08); position: relative; z-index: 10; }
        
        .search-box { 
            border: none; 
            border-radius: 50px; 
            padding: 12px 20px 12px 45px; 
            width: 100%; 
            outline: none; 
            transition: 0.3s; 
            background: #f1f5f9; 
            font-size: 0.9rem;
            font-weight: 600;
        }
        .search-box:focus { border-color: transparent; box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.1); background: white; }

        .teacher-card { 
            background: white; 
            border-radius: 16px; 
            padding: 15px; 
            border: 1px solid #e2e8f0; 
            transition: transform 0.2s; 
            height: 100%; 
            display: flex; 
            flex-direction: column; 
            align-items: center; 
            text-align: center; 
            box-shadow: 0 4px 10px rgba(0,0,0,0.05);
            position: relative;
            overflow: hidden;
        }
        .teacher-card:hover { transform: translateY(-3px); box-shadow: 0 10px 20px rgba(0,0,0,0.08); border-color: #cbd5e1; }
        
        /* Birthday Highlighting */
        .teacher-card.is-birthday {
            border: 2px solid #f9a8d4; /* Pink border */
            background: linear-gradient(to bottom, #fff1f2, #ffffff);
        }

        /* Role Badge (Top Right) */
        .role-badge-corner {
            position: absolute;
            top: 0;
            right: 0;
            background: #fef3c7;
            color: #d97706;
            font-size: 0.6rem;
            font-weight: 800;
            padding: 3px 10px;
            border-bottom-left-radius: 10px;
            z-index: 2;
        }
        /* Added specific style for AKP badge */
        .role-badge-corner.akp {
            background: #f1f5f9;
            color: #64748b;
        }

        /* Birthday Badge (Top Left) */
        .bday-badge-corner {
            position: absolute;
            top: 0;
            left: 0;
            background: #db2777; /* Pink */
            color: white;
            font-size: 0.6rem;
            font-weight: 700;
            padding: 3px 10px;
            border-bottom-right-radius: 10px;
            z-index: 2;
        }

        .avatar-lg { 
            width: 70px; height: 70px; 
            border-radius: 50%; 
            object-fit: cover; 
            margin-bottom: 10px; 
            border: 4px solid #f8fafc; 
        }
        .avatar-placeholder { 
            width: 70px; height: 70px; 
            border-radius: 50%; 
            background: #f3e8ff; 
            color: var(--primary-color); 
            display: flex; align-items: center; 
            justify-content: center; 
            font-size: 1.8rem; 
            font-weight: 700; 
            margin-bottom: 10px; 
            border: 4px solid #f8fafc;
        }
        
        .subjects-meta { 
            font-size: 0.65rem; 
            color: var(--text-gray); 
            margin-bottom: 5px; 
            line-height: 1.2;
            height: 24px; 
            overflow: hidden;
        }
        
        .class-badge { 
            font-size: 0.65rem; 
            background: #e0f2fe; 
            color: #0284c7; 
            padding: 3px 8px; 
            border-radius: 10px; 
            font-weight: 700; 
            margin-top: 5px; 
            border: none;
            display: inline-block;
        }

        .no-class-text { 
            font-size: 0.65rem; 
            color: var(--text-gray); 
            margin-top: 5px; 
            display: inline-block;
        }
        
        .btn-contact { 
            width: 100%; 
            border-radius: 12px; 
            font-weight: 700; 
            font-size: 0.85rem; 
            margin-top: auto; 
            padding: 10px; 
            background: #f1f5f9; 
            color: var(--text-dark);
            border: 1px solid #e2e8f0;
        }
        .btn-contact:hover { 
             background: #e2e8f0;
             color: var(--primary-color);
        }
        
        /* Modal Styles */
        .modal-content { border-radius: 24px; border: none; overflow: hidden; }
        .modal-header-fancy { background: var(--primary-grad); padding: 30px; text-align: center; color: white; }
        .contact-option { display: flex; align-items: center; padding: 15px; border-radius: 16px; border: 1px solid #f1f5f9; margin-bottom: 10px; text-decoration: none; color: #1e293b; transition: 0.2s; }
        .contact-option:hover { background: #f8fafc; border-color: var(--primary-color); }
        .contact-icon { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; margin-right: 15px; }
    </style>
</head>
<body>

    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">Staff Directory</div>
            <div style="width: 24px;"></div>
        </div>
        <div class="opacity-75 small"><?= count($teachers) ?> registered colleagues</div>
    </div>

    <div class="floating-card">
        <div class="position-relative">
            <i class="bi bi-search position-absolute top-50 start-0 translate-middle-y ms-3 text-muted"></i>
            <input type="text" id="searchInput" class="search-box ps-5" placeholder="Search name, subject, or birthday month..." onkeyup="filterTeachers()">
        </div>
    </div>

    <div class="container px-3 pb-4">
        <div class="row g-3" id="teacherGrid">
            <?php foreach ($teachers as $t): 
                $has_phone = !empty($t['phone_number']);
                $clean_phone = $has_phone ? sanitizePhone($t['phone_number']) : '';
                $initial = strtoupper(substr($t['full_name'], 0, 1));
                $subjects = !empty($t['subjects']) ? explode(',', $t['subjects']) : [];
                $subjects_display = !empty($subjects) ? htmlspecialchars(trim($subjects[0])) . (count($subjects) > 1 ? ' + ' . (count($subjects) - 1) : '') : 'N/A';
                
                // Role Logic
                $role_display = formatRole($t['role']);
                $is_exec = ($role_display !== 'Teacher');
                $is_akp = ($role_display === 'AKP Staff'); // Check if AKP

                // --- BIRTHDAY LOGIC ---
                $is_bday_month = false;
                $month_name_text = "";
                // Assuming Malaysian IC in username (e.g., 851012-...)
                if (!empty($t['username']) && is_numeric(substr($t['username'], 0, 6))) {
                    $month_str = substr($t['username'], 2, 2);
                    if ($month_str === $current_month_num) {
                        $is_bday_month = true;
                    }
                    // Get full month name for search (e.g. "October")
                    $month_name_text = date("F", mktime(0, 0, 0, $month_str, 10));
                }

                // Add month name to search string
                $search_data = strtolower($t['full_name'] . ' ' . $t['class_name'] . ' ' . $t['subjects'] . ' ' . $role_display . ' ' . $month_name_text . ' birthday');
            ?>
            <div class="col-6 col-md-4 teacher-item" data-search="<?= $search_data ?>">
                <div class="teacher-card <?= $is_bday_month ? 'is-birthday' : '' ?>">
                    
                    <?php if($is_bday_month): ?>
                        <div class="bday-badge-corner animate__animated animate__pulse animate__infinite">
                            <i class="bi bi-cake2-fill me-1"></i> B'Day
                        </div>
                    <?php endif; ?>

                    <?php if($is_exec): ?>
                        <div class="role-badge-corner <?= $is_akp ? 'akp' : '' ?>">
                            <?php 
                                if($role_display === 'Principal') echo 'PGB';
                                elseif($role_display === 'Assistant Principal') echo 'GPK';
                                elseif($role_display === 'AKP Staff') echo 'AKP';
                                else echo $role_display;
                            ?>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($t['avatar']) && file_exists($t['avatar'])): ?>
                        <img src="<?= htmlspecialchars($t['avatar']) ?>" class="avatar-lg">
                    <?php else: ?>
                        <div class="avatar-placeholder"><i class="bi bi-person-fill"></i></div>
                    <?php endif; ?>
                    
                    <h6 class="fw-bold mb-1 text-dark small text-truncate w-100 teacher-name"><?= htmlspecialchars($t['full_name']) ?></h6>
                    
                    <div class="subjects-meta text-truncate w-100">
                        <?php if(!$is_akp): ?>
                        <i class="bi bi-book small me-1"></i>
                        <?= $subjects_display ?>
                        <?php else: ?>
                        <span class="opacity-50">Support Staff</span>
                        <?php endif; ?>
                    </div>
                    
                    <?php if (!empty($t['class_name'])): ?>
                        <span class="class-badge teacher-class"><i class="bi bi-house-door-fill me-1"></i><?= htmlspecialchars($t['class_name']) ?></span>
                    <?php else: ?>
                        <span class="no-class-text"><?= $role_display !== 'Teacher' ? $role_display : '--' ?></span>
                    <?php endif; ?>

                    <button class="btn btn-light btn-contact mt-3 shadow-sm" 
                        onclick="openContactModal(
                            '<?= addslashes($t['full_name']) ?>', 
                            '<?= $clean_phone ?>', 
                            '<?= $t['email'] ?>', 
                            '<?= $t['class_name'] ?? '' ?>',
                            '<?= htmlspecialchars(implode(', ', $subjects)) ?>',
                            '<?= $role_display ?>'
                        )">
                        <i class="bi bi-chat-text-fill me-1"></i> Contact
                    </button>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
        <div id="noResults" class="text-center py-5 text-muted small" style="display: none;">
            <i class="bi bi-emoji-frown display-4 opacity-50"></i><br><br>No results found.
        </div>
    </div>

    <div class="modal fade" id="contactModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered modal-sm">
            <div class="modal-content">
                <div class="modal-header-fancy">
                    <div class="bg-white text-primary rounded-circle d-flex align-items-center justify-content-center mx-auto mb-3 shadow-sm" style="width: 60px; height: 60px; font-size: 1.8rem;">
                        <i class="bi bi-person-lines-fill"></i>
                    </div>
                    <h5 class="fw-bold mb-0" id="modalName">Teacher Name</h5>
                    <small class="opacity-75 d-block" id="modalClassRole">Role</small>
                    <small class="opacity-75 d-block" id="modalSubjects">Subjects</small>
                </div>
                <div class="modal-body p-3">
                    <div id="phoneOptions">
                        <a href="#" id="linkWhatsapp" class="contact-option" target="_blank">
                            <div class="contact-icon bg-success bg-opacity-10 text-success"><i class="bi bi-whatsapp"></i></div>
                            <div>
                                <div class="fw-bold small">WhatsApp</div>
                                <div class="text-muted" style="font-size:0.7rem;">Send message</div>
                            </div>
                            <i class="bi bi-chevron-right ms-auto text-muted small"></i>
                        </a>
                        
                        <a href="#" id="linkCall" class="contact-option">
                            <div class="contact-icon bg-primary bg-opacity-10 text-primary"><i class="bi bi-telephone-fill"></i></div>
                            <div>
                                <div class="fw-bold small">Phone Call</div>
                                <div class="text-muted" style="font-size:0.7rem;">Voice call</div>
                            </div>
                            <i class="bi bi-chevron-right ms-auto text-muted small"></i>
                        </a>
                    </div>

                    <div id="noPhoneMsg" class="text-center py-3 text-muted small" style="display:none;">
                        <i class="bi bi-telephone-x fs-1 opacity-25"></i><br>No phone number available.
                    </div>

                    <hr class="my-3 opacity-10">
                    
                    <a href="#" id="linkEmail" class="contact-option">
                        <div class="contact-icon bg-warning bg-opacity-10 text-warning"><i class="bi bi-envelope-fill"></i></div>
                        <div>
                            <div class="fw-bold small">Email</div>
                            <div class="text-muted text-truncate" style="font-size:0.7rem; max-width: 150px;" id="displayEmail">...</div>
                        </div>
                    </a>
                    
                    <button class="btn btn-light w-100 rounded-pill fw-bold mt-2" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <?php include 'menu.php'; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const modal = new bootstrap.Modal(document.getElementById('contactModal'));

        function openContactModal(name, phone, email, className, subjects, role) {
            document.getElementById('modalName').innerText = name;
            
            if (className) {
                document.getElementById('modalClassRole').innerText = 'Class Teacher: ' + className;
            } else {
                document.getElementById('modalClassRole').innerText = role;
            }
            
            document.getElementById('modalSubjects').innerText = 'Subjects: ' + (subjects || 'N/A');

            document.getElementById('displayEmail').innerText = email || 'N/A';
            document.getElementById('linkEmail').href = email ? 'mailto:' + email : '#';

            if (phone) {
                document.getElementById('phoneOptions').style.display = 'block';
                document.getElementById('noPhoneMsg').style.display = 'none';
                document.getElementById('linkWhatsapp').href = 'https://wa.me/' + phone;
                document.getElementById('linkCall').href = 'tel:+' + phone;
            } else {
                document.getElementById('phoneOptions').style.display = 'none';
                document.getElementById('noPhoneMsg').style.display = 'block';
            }

            modal.show();
        }

        function filterTeachers() {
            const input = document.getElementById('searchInput').value.toLowerCase();
            const items = document.getElementsByClassName('teacher-item');
            let visibleCount = 0;

            for (let i = 0; i < items.length; i++) {
                const searchData = items[i].getAttribute('data-search');
                
                if (searchData.includes(input)) {
                    items[i].style.display = "";
                    visibleCount++;
                } else {
                    items[i].style.display = "none";
                }
            }
            
            document.getElementById('noResults').style.display = (visibleCount === 0) ? 'block' : 'none';
        }
    </script>
</body>
</html>