<?php
$title = 'User Management';
$active = 'users';

// Define BASE_URL if not already defined
if (!defined('BASE_URL')) {
    // Try to determine BASE_URL from the current script path
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
    $host = $_SERVER['HTTP_HOST'];
    $scriptPath = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
    // Remove /views/users from the path to get the base URL
    $basePath = preg_replace('/\/views\/users$/', '', $scriptPath);
    define('BASE_URL', $protocol . $host . $basePath);
}

// If accessed directly without router, redirect to router URL
if (!isset($users)) {
    header('Location: ' . BASE_URL . '/users');
    exit;
}

require_once __DIR__ . '/../layouts/header.php';
require_once __DIR__ . '/../layouts/sidebar.php';

// Check if user should see Add New User button
$showAddButton = false;
if (isset($_SESSION['is_super_admin']) && $_SESSION['is_super_admin'] === true) {
    $showAddButton = true;
} elseif (function_exists('Auth') && Auth::can('users.manage')) {
    $showAddButton = true;
} elseif (isset($_SESSION['roles']) && is_array($_SESSION['roles'])) {
    foreach ($_SESSION['roles'] as $role) {
        if (stripos($role, 'Super Admin') !== false || stripos($role, 'SuperAdmin') !== false) {
            $showAddButton = true;
            break;
        }
    }
}
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-content">
            <h1>
                <i class="fas fa-users"></i>
                User Management
            </h1>
            <p>Manage system users, roles, and permissions</p>
        </div>
        <div class="header-actions">
            <?php if (function_exists('Auth') && Auth::can('reports.export')): ?>
            <button class="btn btn-outline" onclick="exportUsers()" style="background: transparent; border: 1px solid #27ae60; color: #27ae60; padding: 10px 20px; border-radius: 6px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; font-weight: 600;">
                <i class="fas fa-download"></i> Export
            </button>
            <?php endif; ?>
            
            <?php if ($showAddButton): ?>
            <a href="<?php echo BASE_URL; ?>/users/create" class="btn btn-success" style="background: #27ae60; color: white; padding: 10px 20px; border-radius: 6px; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; font-weight: 600;">
                <i class="fas fa-plus-circle"></i> Add New User
            </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Filter Section - NEW FEATURE -->
    <div class="filter-section" style="background: white; border-radius: 8px; margin-bottom: 20px; border: 1px solid #ddd; overflow: hidden;">
        <div class="filter-header" onclick="toggleFilters()" style="padding: 12px 15px; background: #f8f9fa; cursor: pointer; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #ddd;">
            <h3 style="margin: 0; font-size: 1rem; display: flex; align-items: center; gap: 8px;"><i class="fas fa-filter" style="color: #27ae60;"></i> Filter Users</h3>
            <i class="fas fa-chevron-down" id="filterChevron" style="transition: transform 0.3s;"></i>
        </div>
        <div class="filter-body" id="filterBody" style="padding: 15px; display: block;">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                <div>
                    <label style="display: block; font-size: 0.85rem; color: #666; margin-bottom: 5px;">Search</label>
                    <input type="text" id="searchUsers" placeholder="Search by name, email, rank..." style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.9rem;">
                </div>
                <div>
                    <label style="display: block; font-size: 0.85rem; color: #666; margin-bottom: 5px;">Status</label>
                    <select id="filterStatus" style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.9rem;">
                        <option value="">All Status</option>
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>
            </div>
            <div style="display: flex; justify-content: flex-end;">
                <button onclick="clearFilters()" style="padding: 6px 12px; font-size: 0.85rem; border: 1px solid #ddd; background: white; color: #666; border-radius: 4px; cursor: pointer; display: inline-flex; align-items: center; gap: 5px;">
                    <i class="fas fa-times"></i> Clear Filters
                </button>
            </div>
        </div>
    </div>

    <!-- Users Table -->
    <div class="content-card">
        <div class="section-title">
            <h2><i class="fas fa-list"></i> System Users</h2>
            <div style="display: flex; align-items: center; gap: 15px;">
                <span style="color: #666; font-size: 0.9rem;">Total: <?php echo count($users); ?> users</span>
            </div>
        </div>

        <div class="table-responsive">
            <?php if (empty($users)): ?>
                <div class="empty-state" style="text-align: center; padding: 50px; background: #f9f9f9; border-radius: 8px;">
                    <i class="fas fa-users" style="font-size: 48px; color: #ccc; margin-bottom: 15px;"></i>
                    <p style="color: #666; margin-bottom: 20px;">No users found</p>
                    <?php if ($showAddButton): ?>
                    <a href="<?php echo BASE_URL; ?>/users/create" class="btn btn-primary" style="background: #27ae60; color: white; padding: 10px 20px; border-radius: 6px; text-decoration: none; display: inline-flex; align-items: center; gap: 8px;">
                        <i class="fas fa-plus"></i> Add First User
                    </a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
            <table class="asset-table" id="usersTable" style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="background: #f4f6f9; border-bottom: 2px solid #27ae60;">
                        <th style="padding: 12px; text-align: left;">S/N</th>
                        <th style="padding: 12px; text-align: left;">Username</th>
                        <th style="padding: 12px; text-align: left;">Full Name</th>
                        <th style="padding: 12px; text-align: left;">NIS Number</th>
                        <th style="padding: 12px; text-align: left;">Rank</th>
                        <th style="padding: 12px; text-align: left;">Email</th>
                        <th style="padding: 12px; text-align: left;">Phone</th>
                        <th style="padding: 12px; text-align: left;">Command</th>
                        <th style="padding: 12px; text-align: left;">Zone</th>
                        <th style="padding: 12px; text-align: left;">Roles</th>
                        <th style="padding: 12px; text-align: left;">Last Login</th>
                        <th style="padding: 12px; text-align: left;">Status</th>
                        <th style="padding: 12px; text-align: left;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $index => $user): ?>
                    <tr style="border-bottom: 1px solid #eee;">
                        <td style="padding: 12px;"><?php echo $index + 1; ?></td>
                        <td style="padding: 12px;"><?php echo htmlspecialchars($user['username'] ?? ''); ?></td>
                        <td style="padding: 12px;"><?php echo htmlspecialchars($user['full_name'] ?? ''); ?></td>
                        <td style="padding: 12px;"><?php echo htmlspecialchars($user['nis_number'] ?? ''); ?></td>
                        <td style="padding: 12px;">
                            <span class="badge badge-primary" style="display: inline-block; padding: 4px 8px; background: #e3f2fd; color: #1565c0; border-radius: 12px; font-size: 0.75rem; font-weight: 600;">
                                <?php echo htmlspecialchars($user['rank'] ?? ''); ?>
                            </span>
                        </td>
                        <td style="padding: 12px;"><?php echo htmlspecialchars($user['email'] ?? ''); ?></td>
                        <td style="padding: 12px;"><?php echo htmlspecialchars($user['phone'] ?? ''); ?></td>
                        <td style="padding: 12px;"><?php echo htmlspecialchars($user['command_name'] ?? 'N/A'); ?></td>
                        <td style="padding: 12px;"><?php echo htmlspecialchars($user['zone_name'] ?? 'N/A'); ?></td>
                        <td style="padding: 12px;">
                            <?php 
                            if (!empty($user['role_names'])) {
                                $roleNames = explode(', ', $user['role_names']);
                                foreach (array_slice($roleNames, 0, 2) as $role):
                                    $badgeClass = 'badge-primary';
                                    if (strpos($role, 'Super Admin') !== false) $badgeClass = 'badge-danger';
                                    elseif (strpos($role, 'Sectional') !== false) $badgeClass = 'badge-warning';
                                    elseif (strpos($role, 'Vetting') !== false) $badgeClass = 'badge-info';
                            ?>
                                <span class="badge <?php echo $badgeClass; ?>" style="display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 0.75rem; font-weight: 600; margin: 2px; 
                                    <?php 
                                    if ($badgeClass == 'badge-primary') echo 'background: #e3f2fd; color: #1565c0;';
                                    elseif ($badgeClass == 'badge-danger') echo 'background: #ffebee; color: #c62828;';
                                    elseif ($badgeClass == 'badge-warning') echo 'background: #fff8e1; color: #ff8f00;';
                                    elseif ($badgeClass == 'badge-info') echo 'background: #e0f2f1; color: #00695c;';
                                    ?>">
                                    <?php echo htmlspecialchars($role); ?>
                                </span>
                            <?php 
                                endforeach;
                                if (count($roleNames) > 2) {
                                    echo '<span class="badge badge-secondary" style="display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 0.75rem; font-weight: 600; margin: 2px; background: #e0e0e0; color: #616161;">+' . (count($roleNames) - 2) . '</span>';
                                }
                            } else {
                                echo 'No roles';
                            }
                            ?>
                        </td>
                        <td style="padding: 12px;">
                            <?php if (!empty($user['last_login'])): ?>
                                <?php echo date('d/m/Y H:i', strtotime($user['last_login'])); ?>
                            <?php else: ?>
                                Never
                            <?php endif; ?>
                        </td>
                        <td style="padding: 12px;">
                            <?php if ($user['is_active'] ?? false): ?>
                                <span class="status-badge status-active" style="background: #e8f5e9; color: #2e7d32; padding: 4px 8px; border-radius: 12px; font-size: 0.75rem; font-weight: 600;">Active</span>
                            <?php else: ?>
                                <span class="status-badge status-inactive" style="background: #ffebee; color: #c62828; padding: 4px 8px; border-radius: 12px; font-size: 0.75rem; font-weight: 600;">Inactive</span>
                            <?php endif; ?>
                        </td>
                        <td style="padding: 12px;">
                            <div class="action-buttons" style="display: flex; gap: 5px;">
                                <a href="<?php echo BASE_URL; ?>/users/show/<?php echo $user['id']; ?>" 
                                   class="btn-icon" title="View Details" style="display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; border-radius: 4px; color: #666; text-decoration: none; transition: all 0.3s;">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <?php if ($showAddButton): ?>
                                <a href="<?php echo BASE_URL; ?>/users/edit/<?php echo $user['id']; ?>" 
                                   class="btn-icon" title="Edit" style="display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; border-radius: 4px; color: #666; text-decoration: none; transition: all 0.3s;">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <?php endif; ?>
                                <?php if ($showAddButton && ($user['id'] ?? 0) != ($_SESSION['user_id'] ?? 0)): ?>
                                    <a href="<?php echo BASE_URL; ?>/users/toggle-status/<?php echo $user['id']; ?>" 
                                       class="btn-icon <?php echo ($user['is_active'] ?? false) ? 'warning' : 'success'; ?>" 
                                       title="<?php echo ($user['is_active'] ?? false) ? 'Deactivate' : 'Activate'; ?>"
                                       onclick="return confirm('Are you sure you want to <?php echo ($user['is_active'] ?? false) ? 'deactivate' : 'activate'; ?> this user?')"
                                       style="display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; border-radius: 4px; color: #666; text-decoration: none; transition: all 0.3s;">
                                        <i class="fas fa-<?php echo ($user['is_active'] ?? false) ? 'ban' : 'check-circle'; ?>"></i>
                                    </a>
                                    <a href="<?php echo BASE_URL; ?>/users/delete/<?php echo $user['id']; ?>" 
                                       class="btn-icon delete" title="Delete"
                                       onclick="return confirm('Are you sure you want to delete this user? This action cannot be undone.')"
                                       style="display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; border-radius: 4px; color: #666; text-decoration: none; transition: all 0.3s;">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
/* Hover effects for action buttons */
.btn-icon:hover {
    background: #f0f0f0;
    color: #27ae60;
}

.btn-icon.delete:hover {
    background: #ffebee;
    color: #e53e3e;
}

.btn-icon.warning:hover {
    background: #fff8e1;
    color: #f39c12;
}

.btn-icon.success:hover {
    background: #e8f5e9;
    color: #27ae60;
}

/* Table row hover effect */
#usersTable tbody tr:hover {
    background: #f5f5f5;
}

/* Filter section styles */
.filter-header.active i {
    transform: rotate(180deg);
}

/* Badge styles */
.badge-secondary {
    background: #e0e0e0;
    color: #616161;
}

/* Responsive design */
@media (max-width: 768px) {
    .header-actions {
        flex-direction: column;
        gap: 10px;
    }
    
    .header-actions .btn {
        width: 100%;
        justify-content: center;
    }
    
    .filter-body > div:first-child {
        grid-template-columns: 1fr !important;
    }
}
</style>

<script>
function exportUsers() {
    window.location.href = '<?php echo BASE_URL; ?>/users/export';
}

function toggleFilters() {
    const body = document.getElementById('filterBody');
    const header = document.querySelector('.filter-header');
    const chevron = document.getElementById('filterChevron');
    
    if (body.style.display === 'none' || body.style.display === '') {
        body.style.display = 'block';
        header.classList.add('active');
        if (chevron) chevron.style.transform = 'rotate(180deg)';
    } else {
        body.style.display = 'none';
        header.classList.remove('active');
        if (chevron) chevron.style.transform = '';
    }
}

function clearFilters() {
    document.getElementById('searchUsers').value = '';
    document.getElementById('filterStatus').value = '';
    filterTable();
}

// Search and filter functionality
function filterTable() {
    const searchInput = document.getElementById('searchUsers');
    const filterSelect = document.getElementById('filterStatus');
    const table = document.getElementById('usersTable');
    if (!table) return;
    
    const searchTerm = searchInput?.value.toLowerCase() || '';
    const status = filterSelect?.value || '';
    const rows = table.querySelectorAll('tbody tr');
    
    rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        const statusCell = row.querySelector('.status-badge');
        const isActive = statusCell?.classList.contains('status-active') || false;
        
        let show = true;
        
        // Search filter
        if (searchTerm && !text.includes(searchTerm)) {
            show = false;
        }
        
        // Status filter
        if (status && show) {
            if (status === 'active' && !isActive) show = false;
            if (status === 'inactive' && isActive) show = false;
        }
        
        row.style.display = show ? '' : 'none';
    });
}

document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('searchUsers');
    const filterSelect = document.getElementById('filterStatus');
    
    if (searchInput) {
        searchInput.addEventListener('input', filterTable);
    }
    
    if (filterSelect) {
        filterSelect.addEventListener('change', filterTable);
    }
    
    // Set initial filter state for mobile
    if (window.innerWidth <= 768) {
        document.getElementById('filterBody').style.display = 'none';
    } else {
        document.getElementById('filterBody').style.display = 'block';
        document.querySelector('.filter-header').classList.add('active');
    }
});
</script>

<?php
require_once __DIR__ . '/../layouts/footer.php';
?>