<?php
require_once('../includes/functions.php');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header("Location: ../login.php");
    exit();
}

$employees = getAllEmployees();
$reports = readJson('reports');
$unreadReports = count(array_filter($reports, function($r) { return $r['status'] == 'unread'; }));
$quizzes = readJson('quizzes');
$memos = readJson('memos');
$manual = readJson('maintenance_manual');

$allExpiring = getAllExpiringLicenses();

if (isset($_SESSION['admin_expiry_popup_date']) && $_SESSION['admin_expiry_popup_date'] != date('Y-m-d')) {
    $_SESSION['admin_expiry_popup_shown'] = false;
}
$_SESSION['admin_expiry_popup_date'] = date('Y-m-d');
if (!isset($_SESSION['admin_expiry_popup_shown'])) {
    $_SESSION['admin_expiry_popup_shown'] = false;
}

$totalAssignments = 0;
$totalRead = 0;
foreach ($memos as $memo) {
    $totalAssignments += count($memo['assigned_to']);
    $totalRead += count($memo['read_by'] ?? []);
}
$acknowledgementRate = $totalAssignments > 0 ? round(($totalRead / $totalAssignments) * 100) : 0;
?>
<?php include('../includes/header.php'); ?>

<style>
    /* Mobile menu toggle button */
    .menu-toggle {
        display: none;
        background: #6b1d2f;
        color: #f9e4c2;
        border: none;
        padding: 10px 16px;
        border-radius: 40px;
        cursor: pointer;
        margin-bottom: 15px;
        font-size: 1rem;
        width: 100%;
        text-align: center;
    }
    @media (max-width: 768px) {
        .menu-toggle {
            display: block;
        }
        .sidebar {
            display: none;
        }
        .sidebar.show {
            display: block;
        }
        .content {
            width: 100%;
            float: none;
        }
    }
</style>

<!-- Admin Expiry Notification Popup -->
<?php if (!empty($allExpiring) && !$_SESSION['admin_expiry_popup_shown']): 
    $_SESSION['admin_expiry_popup_shown'] = true;
    $totalExpiringItems = 0;
    foreach ($allExpiring as $exp) {
        $totalExpiringItems += count($exp['expiring_items']);
    }
?>
<div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); display: flex; align-items: center; justify-content: center; z-index: 2000; overflow-y: auto;">
    <div style="background: #faf3e8; border-radius: 24px; max-width: 90%; width: 500px; padding: 20px; border-top: 6px solid #c9a87c;">
        <h3 style="color: #6b1d2f;">⚠️ License Expiry Alerts (90 days)</h3>
        <?php foreach($allExpiring as $exp): ?>
            <details><summary><?php echo htmlspecialchars($exp['user_name']); ?> (<?php echo count($exp['expiring_items']); ?> items)</summary>
            <?php foreach($exp['expiring_items'] as $item): ?>
                <p>• <?php echo $item['type']; ?>: expires <?php echo date('M j, Y', strtotime($item['expiry_date'])); ?> (<?php echo $item['days_left']; ?> days)</p>
            <?php endforeach; ?>
            </details>
        <?php endforeach; ?>
        <button onclick="this.parentElement.parentElement.style.display='none'" class="btn btn-primary" style="margin-top: 15px;">Dismiss</button>
    </div>
</div>
<?php endif; ?>

<!-- Mobile menu toggle button -->
<button class="menu-toggle" id="menuToggle">☰ Menu</button>

<div class="sidebar" id="sidebar">
    <h3>📋 Admin Console</h3>
    <a href="dashboard.php" class="btn active">📊 Dashboard</a>
    <a href="add_user.php" class="btn">👤 Add Crew</a>
    <a href="manage_users.php" class="btn">📋 Crew List</a>
    <a href="employee_list.php" class="btn">📋 Full Employee Data</a>
    <a href="edit_user.php" class="btn">✏️ Edit Crew</a>
    <a href="manage_endorsements.php" class="btn">✈️ Endorsements</a>
    <a href="add_memo.php" class="btn">📝 New Memo</a>
    <a href="add_quiz.php" class="btn">📚 New Quiz</a>
    <a href="inbox.php" class="btn">📥 Safety Reports <?php if($unreadReports > 0): ?> (<?php echo $unreadReports; ?>)<?php endif; ?></a>
    <a href="chat.php" class="btn">💬 Group Chat</a>
    <a href="tools.php" class="btn">🔧 Tools Management</a>
    <a href="upload_manual.php" class="btn">📘 Upload Manual</a>
</div>
<div class="content">
    <div class="flex-between" style="align-items: center;">
        <h2>Welcome, Captain <?php echo htmlspecialchars($_SESSION['full_name']); ?> ✈️</h2>
        <div class="propeller-loader" style="width: 32px; height: 32px;"></div>
    </div>
    
    <div class="grid-2">
        <div class="card radar-sweep">
            <h3>👥 Crew Members</h3>
            <p style="font-size: 2rem;"><?php echo count($employees); ?></p>
        </div>
        <div class="card radar-sweep">
            <h3>📥 Unread Reports</h3>
            <p style="font-size: 2rem;"><?php echo $unreadReports; ?></p>
        </div>
        <div class="card radar-sweep">
            <h3>📚 Quizzes</h3>
            <p style="font-size: 2rem;"><?php echo count($quizzes); ?></p>
        </div>
        <div class="card radar-sweep">
            <h3>📘 Manual v<?php echo !empty($manual) ? $manual['version'] : '1'; ?></h3>
        </div>
    </div>
    
    <div class="card">
        <h3>📊 Memo Acknowledgement Rate</h3>
        <div style="background:#e2cfb3; border-radius: 30px; overflow:hidden;">
            <div style="background:#6b1d2f; width:<?php echo $acknowledgementRate; ?>%; padding: 6px; text-align:center; color:white;"><?php echo $acknowledgementRate; ?>%</div>
        </div>
        <p class="mt-2"><?php echo $totalRead; ?> of <?php echo $totalAssignments; ?> acknowledged</p>
    </div>
    
    <div class="card">
        <h3>👥 Recent Employees</h3>
        <div class="table-responsive">
            <table style="width: 100%;">
                <thead>
                    <tr style="background: #f8efe5;">
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Endorsements</th>
                        <th>Status</th>
                     </tr>
                </thead>
                <tbody>
                    <?php foreach(array_slice($employees, 0, 10) as $emp): 
                        $endorsements = getEmployeeEndorsements($emp['id']);
                        $endorsementDisplay = !empty($endorsements) ? implode(', ', array_slice($endorsements, 0, 3)) . (count($endorsements) > 3 ? '…' : '') : '-';
                        $isActive = isset($emp['is_active']) ? $emp['is_active'] : true;
                    ?>
                    <tr>
                        <td>#<?php echo $emp['id']; ?></td>
                        <td><?php echo htmlspecialchars($emp['full_name']); ?></td>
                        <td><?php echo htmlspecialchars($emp['email']); ?></td>
                        <td><small><?php echo $endorsementDisplay; ?></small></td>
                        <td><?php echo $isActive ? '✓ Active' : '⛔ Inactive'; ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php if(count($employees) > 10): ?>
            <div class="text-center mt-2"><a href="employee_list.php" class="btn btn-sm">View all <?php echo count($employees); ?> crew →</a></div>
        <?php endif; ?>
    </div>
</div>

<script>
    // Mobile menu toggle
    const toggleBtn = document.getElementById('menuToggle');
    const sidebar = document.getElementById('sidebar');
    if (toggleBtn) {
        toggleBtn.addEventListener('click', () => {
            sidebar.classList.toggle('show');
        });
    }
</script>

<div class="clearfix"></div>
<?php include('../includes/footer.php'); ?>