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

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

$message = '';
$error = '';

// Handle renumber IDs
if (isset($_GET['renumber_ids'])) {
    $count = renumberUserIds();
    $message = "✅ User IDs have been renumbered sequentially! Total users: $count";
}

// Handle delete user
if (isset($_GET['delete_id'])) {
    $userId = $_GET['delete_id'];
    $users = readJson('users');
    $newUsers = [];
    $deletedUser = null;
    
    foreach ($users as $user) {
        if ($user['id'] == $userId) {
            $deletedUser = $user;
        } else {
            $newUsers[] = $user;
        }
    }
    
    if ($deletedUser) {
        writeJson('users', $newUsers);
        // Renumber IDs after deletion to keep sequential
        renumberUserIds();
        $message = "✅ User '{$deletedUser['full_name']}' has been deleted and IDs renumbered!";
    }
}

// Handle activate/deactivate user
if (isset($_GET['toggle_status']) && isset($_GET['user_id'])) {
    $userId = $_GET['user_id'];
    $users = readJson('users');
    
    foreach ($users as &$user) {
        if ($user['id'] == $userId) {
            $currentStatus = isset($user['is_active']) ? $user['is_active'] : true;
            $user['is_active'] = !$currentStatus;
            $statusText = $user['is_active'] ? 'activated' : 'deactivated';
            $message = "✅ User '{$user['full_name']}' has been {$statusText}!";
            break;
        }
    }
    writeJson('users', $users);
}

// Get all employees
$employees = getAllEmployees();

// Search functionality
$search = isset($_GET['search']) ? $_GET['search'] : '';
if ($search) {
    $employees = array_filter($employees, function($emp) use ($search) {
        return stripos($emp['full_name'], $search) !== false || 
               stripos($emp['email'], $search) !== false ||
               stripos($emp['username'], $search) !== false;
    });
}

// Sort employees by name
usort($employees, function($a, $b) {
    return strcmp($a['full_name'], $b['full_name']);
});

// Get counts
$totalEmployees = count($employees);
$activeCount = count(array_filter($employees, function($e) { 
    return isset($e['is_active']) ? $e['is_active'] : true; 
}));
$inactiveCount = $totalEmployees - $activeCount;
$endorsementCount = count(array_filter($employees, function($e) { 
    return !empty(getEmployeeEndorsements($e['id'])); 
}));
?>
<?php include('../includes/header.php'); ?>
<style>
    .status-badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 11px;
        font-weight: bold;
    }
    .status-active {
        background: #d4edda;
        color: #155724;
    }
    .status-inactive {
        background: #f8d7da;
        color: #721c24;
    }
    .action-buttons {
        display: flex;
        gap: 5px;
        flex-wrap: wrap;
    }
    .btn-sm {
        padding: 5px 10px;
        font-size: 11px;
        margin: 0;
    }
    .btn-edit {
        background: #3498db;
    }
    .btn-endorse {
        background: #9b59b6;
    }
    .btn-toggle {
        background: #f39c12;
    }
    .btn-delete {
        background: #e74c3c;
    }
    .btn-renumber {
        background: #1abc9c;
    }
    .search-box {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
        flex-wrap: wrap;
    }
    .search-box input {
        flex: 1;
        min-width: 200px;
    }
    .stats-bar {
        display: flex;
        gap: 15px;
        margin-bottom: 20px;
        flex-wrap: wrap;
    }
    .stat {
        background: #f8f9fa;
        padding: 10px 15px;
        border-radius: 8px;
        font-size: 14px;
    }
    .stat strong {
        color: #667eea;
        font-size: 18px;
    }
    .employee-table {
        width: 100%;
        overflow-x: auto;
    }
    .employee-table table {
        width: 100%;
        min-width: 1000px;
    }
    .employee-table th {
        background: #f8f9fa;
        padding: 12px;
        text-align: left;
        font-weight: bold;
    }
    .employee-table td {
        padding: 12px;
        border-bottom: 1px solid #eee;
        vertical-align: middle;
    }
    .employee-table tr:hover {
        background: #f8f9fa;
    }
    .endorsement-badge {
        display: inline-block;
        background: #27ae60;
        color: white;
        padding: 2px 6px;
        border-radius: 12px;
        font-size: 9px;
        margin: 1px;
    }
    .no-data {
        text-align: center;
        padding: 40px;
        color: #999;
    }
    .id-column {
        font-family: monospace;
        font-weight: bold;
        color: #667eea;
    }
    .warning-note {
        background: #fff3cd;
        border-left: 4px solid #ffc107;
        padding: 10px 15px;
        margin-bottom: 20px;
        border-radius: 5px;
        font-size: 13px;
    }
</style>
<div class="sidebar">
    <h3>📋 Admin Menu</h3>
    <a href="dashboard.php" class="btn" style="display: block;">📊 Dashboard</a>
    <a href="add_user.php" class="btn" style="display: block;">👤 Add Employee</a>
    <a href="manage_users.php" class="btn" style="display: block; background: #667eea;">📋 Manage Users</a>
    <a href="edit_user.php" class="btn" style="display: block;">✏️ Edit User</a>
    <a href="manage_endorsements.php" class="btn" style="display: block;">✈️ Endorsements</a>
    <a href="add_memo.php" class="btn" style="display: block;">📝 Add Memo</a>
    <a href="add_quiz.php" class="btn" style="display: block;">📚 Add Quiz</a>
    <a href="inbox.php" class="btn" style="display: block;">📥 Safety Reports</a>
    <a href="upload_manual.php" class="btn" style="display: block;">📘 Upload Manual</a>
</div>
<div class="content">
    <h2>📋 Manage Employees</h2>
    
    <?php if($message): ?>
        <div class="alert alert-info" style="background: #d4edda; border-left: 4px solid #27ae60; padding: 15px; margin-bottom: 20px; border-radius: 5px;">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>
    
    <!-- Warning about ID gaps -->
    <div class="warning-note">
        💡 <strong>Tip:</strong> If you see gaps in user IDs, click the "Renumber IDs" button to make them sequential (1, 2, 3, etc.).
    </div>
    
    <!-- Stats Bar -->
    <div class="stats-bar">
        <div class="stat">🆔 <strong><?php echo $totalEmployees; ?></strong> Total Employees</div>
        <div class="stat">✅ <strong><?php echo $activeCount; ?></strong> Active</div>
        <div class="stat">⛔ <strong><?php echo $inactiveCount; ?></strong> Inactive</div>
        <div class="stat">✈️ <strong><?php echo $endorsementCount; ?></strong> Have Endorsements</div>
    </div>
    
    <!-- Search Box and Actions -->
    <div class="search-box">
        <form method="GET" style="display: flex; gap: 10px; width: 100%; flex-wrap: wrap;">
            <input type="text" name="search" placeholder="Search by name, email, or username..." value="<?php echo htmlspecialchars($search); ?>" style="flex: 1;">
            <button type="submit" class="btn" style="background: #667eea;">🔍 Search</button>
            <?php if($search): ?>
                <a href="manage_users.php" class="btn" style="background: #95a5a6;">Clear</a>
            <?php endif; ?>
            <a href="?renumber_ids=1" class="btn btn-renumber" onclick="return confirm('Renumber all user IDs sequentially? This will reassign IDs starting from 1. All existing links will still work because we use usernames for login.');">🔄 Renumber IDs</a>
        </form>
    </div>
    
    <!-- Employee Table -->
    <div class="card">
        <div class="employee-table">
            <table>
                <thead>
                    <tr style="background: #f8f9fa;">
                        <th style="width: 50px;">ID</th>
                        <th>Employee</th>
                        <th>Contact</th>
                        <th>Licenses</th>
                        <th>✈️ Endorsements</th>
                        <th>Status</th>
                        <th style="width: 280px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($employees)): ?>
                        <tr>
                            <td colspan="7" class="no-data">No employees found. <a href="add_user.php">Click here to add one</a></td>
                        </tr>
                    <?php else: ?>
                        <?php foreach($employees as $emp): 
                            $endorsements = getEmployeeEndorsements($emp['id']);
                            $isActive = isset($emp['is_active']) ? $emp['is_active'] : true;
                            $hasExpiry = false;
                            foreach(['ame_expiry', 'raic_expiry', 'da_expiry', 'amo_stamp_expiry'] as $expiry) {
                                if(isset($emp[$expiry]) && $emp[$expiry] && $emp[$expiry] < date('Y-m-d', strtotime('+30 days'))) {
                                    $hasExpiry = true;
                                    break;
                                }
                            }
                        ?>
                            <tr style="<?php echo !$isActive ? 'opacity: 0.6;' : ''; ?>">
                                <td class="id-column">#<?php echo $emp['id']; ?></td>
                                <td>
                                    <strong><?php echo htmlspecialchars($emp['full_name']); ?></strong><br>
                                    <small style="color: #666;">@<?php echo htmlspecialchars($emp['username']); ?></small>
                                </td>
                                <td>
                                    📧 <?php echo htmlspecialchars($emp['email']); ?><br>
                                    📱 <?php echo htmlspecialchars($emp['phone']); ?>
                                </td>
                                <td style="font-size: 12px;">
                                    <?php if($emp['ame_license']): ?>AME: <?php echo htmlspecialchars($emp['ame_license']); ?><br><?php endif; ?>
                                    <?php if($emp['raic_number']): ?>RAIC: <?php echo htmlspecialchars($emp['raic_number']); ?><br><?php endif; ?>
                                    <?php if($emp['da_number']): ?>DA: <?php echo htmlspecialchars($emp['da_number']); ?><br><?php endif; ?>
                                    <?php if($emp['amo_stamp_number']): ?>AMO: <?php echo htmlspecialchars($emp['amo_stamp_number']); ?><?php endif; ?>
                                    <?php if($hasExpiry): ?>
                                        <br><span style="color: #e74c3c;">⚠️ Expiring soon</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if(!empty($endorsements)): ?>
                                        <?php foreach(array_slice($endorsements, 0, 4) as $code): ?>
                                            <span class="endorsement-badge">✈️ <?php echo $code; ?></span>
                                        <?php endforeach; ?>
                                        <?php if(count($endorsements) > 4): ?>
                                            <span class="endorsement-badge">+<?php echo count($endorsements) - 4; ?></span>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 11px;">No endorsements</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="status-badge <?php echo $isActive ? 'status-active' : 'status-inactive'; ?>">
                                        <?php echo $isActive ? '✓ Active' : '⛔ Inactive'; ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="action-buttons">
                                        <a href="edit_user.php?user_id=<?php echo $emp['id']; ?>" class="btn btn-sm btn-edit" title="Edit User">✏️ Edit</a>
                                        <a href="manage_endorsements.php?user_id=<?php echo $emp['id']; ?>" class="btn btn-sm btn-endorse" title="Manage Endorsements">✈️ Endorse</a>
                                        <a href="?toggle_status=1&user_id=<?php echo $emp['id']; ?>" class="btn btn-sm btn-toggle" title="<?php echo $isActive ? 'Deactivate' : 'Activate'; ?>" onclick="return confirm('<?php echo $isActive ? 'Deactivate' : 'Activate'; ?> <?php echo htmlspecialchars($emp['full_name']); ?>?')">
                                            <?php echo $isActive ? '🔴 Deactivate' : '🟢 Activate'; ?>
                                        </a>
                                        <a href="?delete_id=<?php echo $emp['id']; ?>" class="btn btn-sm btn-delete" title="Delete User" onclick="return confirm('⚠️ WARNING: Are you sure you want to delete <?php echo htmlspecialchars($emp['full_name']); ?>?\n\nThis action cannot be undone!');">🗑️ Delete</a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- Export Options -->
    <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
        <button onclick="window.print()" class="btn" style="background: #3498db;">🖨️ Print List</button>
    </div>
</div>

<script>
// Add confirmation for delete buttons
document.querySelectorAll('.btn-delete').forEach(btn => {
    btn.addEventListener('click', function(e) {
        if (!confirm('⚠️ WARNING: Are you sure you want to delete this user?\n\nThis action cannot be undone!')) {
            e.preventDefault();
        }
    });
});
</script>

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