<?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 -->
    <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 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;">Role</label>
                    <select id="filterRole" style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.9rem;">
                        <option value="">All Roles</option>
                        <option value="Super Admin Officer">Super Admin Officer</option>
                        <option value="Armourer">Armourer</option>
                        <option value="Command Armourer">Command Armourer</option>
                        <option value="Command Approval Officer">Command Approval Officer</option>
                        <option value="Command Data Entry Officer">Command Data Entry Officer</option>
                        <option value="HQ Sectional Supervisor">HQ Sectional Supervisor</option>
                        <option value="HQ Vetting Officer">HQ Vetting Officer</option>
                        <option value="Sectional Head Transport">Sectional Head Transport</option>
                        <option value="Sectional Head ICT">Sectional Head ICT</option>
                        <option value="Staff">Staff</option>
                    </select>
                </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;">Roles</th>
                        <th style="padding: 12px; text-align: left;">Command/Zone</th>
                        <th style="padding: 12px; text-align: left;">Status</th>
                        <th style="padding: 12px; text-align: left;">Last Login</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;">
                            <strong><?php echo htmlspecialchars($user['username'] ?? ''); ?></strong>
                            <br><small style="color: #999;"><?php echo htmlspecialchars($user['email'] ?? ''); ?></small>
                        </td>
                        <td style="padding: 12px;">
                            <?php echo htmlspecialchars($user['full_name'] ?? ''); ?>
                            <br><small style="color: #999;"><?php echo htmlspecialchars($user['phone'] ?? ''); ?></small>
                        </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'] ?? 'N/A'); ?>
                            </span>
                        </td>
                        <td style="padding: 12px;">
                            <?php 
                            if (!empty($user['role_names'])) {
                                $roleNames = explode(', ', $user['role_names']);
                                foreach ($roleNames as $role):
                                    $badgeClass = 'badge-primary';
                                    $badgeStyle = '';
                                    if (strpos($role, 'Super Admin') !== false) {
                                        $badgeStyle = 'background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;';
                                    } elseif (strpos($role, 'Armourer') !== false && strpos($role, 'Command') === false) {
                                        $badgeStyle = 'background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%); color: white;';
                                    } elseif ($role == 'Command Armourer') {
                                        $badgeStyle = 'background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%); color: white;';
                                    } elseif ($role == 'Command Approval Officer') {
                                        $badgeStyle = 'background: linear-gradient(135deg, #3498db 0%, #2980b9 100%); color: white;';
                                    } elseif ($role == 'HQ Vetting Officer') {
                                        $badgeStyle = 'background: linear-gradient(135deg, #9b59b6 0%, #8e44ad 100%); color: white;';
                                    } elseif ($role == 'Sectional Head Transport') {
                                        $badgeStyle = 'background: linear-gradient(135deg, #1abc9c 0%, #16a085 100%); color: white;';
                                    } elseif ($role == 'Sectional Head ICT') {
                                        $badgeStyle = 'background: linear-gradient(135deg, #34495e 0%, #2c3e50 100%); color: white;';
                                    } elseif ($role == 'Command Data Entry Officer') {
                                        $badgeStyle = 'background: linear-gradient(135deg, #27ae60 0%, #219a52 100%); color: white;';
                                    } elseif ($role == 'HQ Sectional Supervisor') {
                                        $badgeStyle = 'background: linear-gradient(135deg, #16a085 0%, #1abc9c 100%); color: white;';
                                    } else {
                                        $badgeStyle = 'background: #e0e0e0; color: #616161;';
                                    }
                            ?>
                                <span class="role-badge" style="display: inline-block; padding: 4px 10px; border-radius: 20px; font-size: 0.7rem; font-weight: 600; margin: 2px; <?php echo $badgeStyle; ?>">
                                    <?php echo htmlspecialchars($role); ?>
                                </span>
                            <?php 
                                endforeach;
                            } else {
                                echo '<span class="role-badge" style="display: inline-block; padding: 4px 10px; border-radius: 20px; font-size: 0.7rem; font-weight: 600; margin: 2px; background: #e0e0e0; color: #616161;">No roles assigned</span>';
                            }
                            ?>
                        </td>
                        <td style="padding: 12px;">
                            <div>
                                <i class="fas fa-map-marker-alt" style="color: #27ae60; font-size: 0.7rem;"></i>
                                <?php echo htmlspecialchars($user['command_name'] ?? 'N/A'); ?>
                            </div>
                            <div style="margin-top: 4px;">
                                <i class="fas fa-globe" style="color: #3498db; font-size: 0.7rem;"></i>
                                <?php echo htmlspecialchars($user['zone_name'] ?? 'N/A'); ?>
                            </div>
                        </td>
                        <td style="padding: 12px;">
                            <?php if ($user['is_active'] ?? false): ?>
                                <span class="status-badge status-active" style="background: #e8f5e9; color: #2e7d32; padding: 4px 10px; border-radius: 20px; font-size: 0.7rem; font-weight: 600;">
                                    <i class="fas fa-check-circle"></i> Active
                                </span>
                            <?php else: ?>
                                <span class="status-badge status-inactive" style="background: #ffebee; color: #c62828; padding: 4px 10px; border-radius: 20px; font-size: 0.7rem; font-weight: 600;">
                                    <i class="fas fa-ban"></i> Inactive
                                </span>
                            <?php endif; ?>
                        </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: ?>
                                <span style="color: #999;">Never</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; background: #f0f0f0; 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; background: #f0f0f0; 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; background: #f0f0f0; 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; background: #f0f0f0; 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: #27ae60 !important;
    color: white !important;
}

.btn-icon.delete:hover {
    background: #e53e3e !important;
    color: white !important;
}

.btn-icon.warning:hover {
    background: #f39c12 !important;
    color: white !important;
}

.btn-icon.success:hover {
    background: #27ae60 !important;
    color: white !important;
}

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

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

/* Role badge styles */
.role-badge {
    transition: transform 0.2s;
}

.role-badge:hover {
    transform: scale(1.05);
}

/* Responsive design */
@media (max-width: 1024px) {
    .table-responsive {
        overflow-x: auto;
    }
    
    #usersTable {
        min-width: 800px;
    }
}

@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('filterRole').value = '';
    document.getElementById('filterStatus').value = '';
    filterTable();
}

// Search and filter functionality
function filterTable() {
    const searchInput = document.getElementById('searchUsers');
    const roleFilter = document.getElementById('filterRole');
    const statusFilter = document.getElementById('filterStatus');
    const table = document.getElementById('usersTable');
    if (!table) return;
    
    const searchTerm = searchInput?.value.toLowerCase() || '';
    const selectedRole = roleFilter?.value || '';
    const selectedStatus = statusFilter?.value || '';
    const rows = table.querySelectorAll('tbody tr');
    
    rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        const roleCell = row.querySelector('td:nth-child(6)');
        const roleText = roleCell?.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;
        }
        
        // Role filter
        if (selectedRole && show) {
            if (!roleText.includes(selectedRole.toLowerCase())) {
                show = false;
            }
        }
        
        // Status filter
        if (selectedStatus && show) {
            if (selectedStatus === 'active' && !isActive) show = false;
            if (selectedStatus === 'inactive' && isActive) show = false;
        }
        
        row.style.display = show ? '' : 'none';
    });
    
    // Update visible count
    const visibleRows = Array.from(rows).filter(row => row.style.display !== 'none');
    const totalSpan = document.querySelector('.section-title span');
    if (totalSpan) {
        totalSpan.innerHTML = `Showing: ${visibleRows.length} of <?php echo count($users); ?> users`;
    }
}

document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('searchUsers');
    const roleFilter = document.getElementById('filterRole');
    const statusFilter = document.getElementById('filterStatus');
    
    if (searchInput) {
        searchInput.addEventListener('input', filterTable);
    }
    
    if (roleFilter) {
        roleFilter.addEventListener('change', filterTable);
    }
    
    if (statusFilter) {
        statusFilter.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';
?>