<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'User Management';

// Check permissions
if (!$auth->hasPermission('can_manage_users') && !$auth->hasRole('super_admin')) {
    $_SESSION['error'] = "You don't have permission to access this page";
    header('Location: dashboard.php');
    exit;
}

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    
    $action = $_POST['action'] ?? '';
    $user_id = (int)($_POST['user_id'] ?? 0);
    
    if ($action === 'suspend') {
        if ($auth->suspendUser($user_id, $auth->getCurrentUser()['id'])) {
            echo json_encode(['success' => true, 'message' => 'User suspended successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to suspend user']);
        }
        exit;
    }
    
    if ($action === 'activate') {
        if ($auth->activateUser($user_id, $auth->getCurrentUser()['id'])) {
            echo json_encode(['success' => true, 'message' => 'User activated successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to activate user']);
        }
        exit;
    }
    
    if ($action === 'delete' && $auth->hasRole('super_admin')) {
        if ($auth->deleteUser($user_id, $auth->getCurrentUser()['id'])) {
            echo json_encode(['success' => true, 'message' => 'User deleted successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to delete user']);
        }
        exit;
    }
}

// Get filter parameters
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$role_filter = $_GET['role'] ?? '';
$sort = $_GET['sort'] ?? 'created_at';
$order = $_GET['order'] ?? 'DESC';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 15;
$offset = ($page - 1) * $limit;

// Build query
$where = ["role = 'user'"];
$params = [];

if ($search) {
    $where[] = "(first_name LIKE ? OR last_name LIKE ? OR email LIKE ? OR phone LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status_filter) {
    $where[] = "status = ?";
    $params[] = $status_filter;
}

$where_sql = 'WHERE ' . implode(' AND ', $where);

// Get total count
$count_sql = "SELECT COUNT(*) as total FROM users $where_sql";
$total = $db->fetchOne($count_sql, $params)['total'];
$total_pages = ceil($total / $limit);

// Get users
$sql = "SELECT * FROM users $where_sql ORDER BY $sort $order LIMIT $limit OFFSET $offset";
$users = $db->fetchAll($sql, $params);

// Get statistics
$stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'suspended' THEN 1 ELSE 0 END) as suspended
    FROM users WHERE role = 'user'";
$stats = $db->fetchOne($stats_sql);

include 'includes/header.php';
?>

<div class="page-header">
    <h1>User Management</h1>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
            <li class="breadcrumb-item active">Users</li>
        </ol>
    </nav>
</div>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card stat-card">
            <div>
                <div class="stat-icon" style="background: rgba(0, 123, 255, 0.1); color: #007bff;">
                    <i class="fas fa-users"></i>
                </div>
            </div>
            <div class="stat-info text-end">
                <h3><?php echo number_format($stats['total']); ?></h3>
                <p>Total Users</p>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card stat-card">
            <div>
                <div class="stat-icon" style="background: rgba(40, 167, 69, 0.1); color: #28a745;">
                    <i class="fas fa-check-circle"></i>
                </div>
            </div>
            <div class="stat-info text-end">
                <h3><?php echo number_format($stats['active']); ?></h3>
                <p>Active Users</p>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card stat-card">
            <div>
                <div class="stat-icon" style="background: rgba(255, 193, 7, 0.1); color: #ffc107;">
                    <i class="fas fa-clock"></i>
                </div>
            </div>
            <div class="stat-info text-end">
                <h3><?php echo number_format($stats['pending']); ?></h3>
                <p>Pending Users</p>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card stat-card">
            <div>
                <div class="stat-icon" style="background: rgba(220, 53, 69, 0.1); color: #dc3545;">
                    <i class="fas fa-ban"></i>
                </div>
            </div>
            <div class="stat-info text-end">
                <h3><?php echo number_format($stats['suspended']); ?></h3>
                <p>Suspended Users</p>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="fas fa-users"></i> All Users
        </h5>
    </div>
    
    <div class="card-body">
        <!-- Filters -->
        <form method="GET" class="mb-4">
            <div class="row g-3">
                <div class="col-md-6">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                        <input type="text" name="search" class="form-control" placeholder="Search by name, email, or phone..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                </div>
                
                <div class="col-md-3">
                    <select name="status" class="form-select">
                        <option value="">All Status</option>
                        <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="suspended" <?php echo $status_filter === 'suspended' ? 'selected' : ''; ?>>Suspended</option>
                        <option value="banned" <?php echo $status_filter === 'banned' ? 'selected' : ''; ?>>Banned</option>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter"></i> Filter
                    </button>
                </div>
                
                <div class="col-md-1">
                    <a href="users.php" class="btn btn-outline-secondary w-100" data-bs-toggle="tooltip" title="Reset">
                        <i class="fas fa-redo"></i>
                    </a>
                </div>
            </div>
        </form>
        
        <!-- Users Table -->
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>User</th>
                        <th>Contact</th>
                        <th>Status</th>
                        <th>Email Verified</th>
                        <th>Last Login</th>
                        <th>Registered</th>
                        <th style="width: 200px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($users)): ?>
                    <tr>
                        <td colspan="7" class="text-center py-4">
                            <i class="fas fa-user-slash fa-3x text-muted mb-3 d-block"></i>
                            <p class="text-muted">No users found</p>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($users as $user): ?>
                        <tr>
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="user-avatar me-3" style="width: 45px; height: 45px; font-size: 1rem;">
                                        <?php echo strtoupper(substr($user['first_name'], 0, 1) . substr($user['last_name'], 0, 1)); ?>
                                    </div>
                                    <div>
                                        <strong><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></strong>
                                        <br>
                                        <small class="text-muted">ID: <?php echo $user['id']; ?></small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <i class="fas fa-envelope"></i> <?php echo htmlspecialchars($user['email']); ?>
                                <br>
                                <i class="fas fa-phone"></i> <?php echo htmlspecialchars($user['phone']); ?>
                            </td>
                            <td>
                                <?php
                                $badge_class = [
                                    'active' => 'success',
                                    'pending' => 'warning',
                                    'suspended' => 'danger',
                                    'banned' => 'dark'
                                ][$user['status']] ?? 'secondary';
                                ?>
                                <span class="badge bg-<?php echo $badge_class; ?>">
                                    <?php echo ucfirst($user['status']); ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($user['email_verified']): ?>
                                    <span class="badge bg-success"><i class="fas fa-check"></i> Verified</span>
                                <?php else: ?>
                                    <span class="badge bg-warning"><i class="fas fa-clock"></i> Unverified</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($user['last_login']): ?>
                                    <?php echo date('M d, Y H:i', strtotime($user['last_login'])); ?>
                                <?php else: ?>
                                    <span class="text-muted">Never</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php echo date('M d, Y', strtotime($user['created_at'])); ?>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-outline-primary view-user" 
                                            data-id="<?php echo $user['id']; ?>"
                                            data-bs-toggle="tooltip" title="View Details">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    
                                    <?php if ($user['status'] === 'active'): ?>
                                    <button type="button" class="btn btn-outline-warning suspend-user" 
                                            data-id="<?php echo $user['id']; ?>"
                                            data-name="<?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?>"
                                            data-bs-toggle="tooltip" title="Suspend User">
                                        <i class="fas fa-ban"></i>
                                    </button>
                                    <?php else: ?>
                                    <button type="button" class="btn btn-outline-success activate-user" 
                                            data-id="<?php echo $user['id']; ?>"
                                            data-name="<?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?>"
                                            data-bs-toggle="tooltip" title="Activate User">
                                        <i class="fas fa-check"></i>
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if ($auth->hasRole('super_admin')): ?>
                                    <button type="button" class="btn btn-outline-danger delete-user" 
                                            data-id="<?php echo $user['id']; ?>"
                                            data-name="<?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?>"
                                            data-bs-toggle="tooltip" title="Delete User">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <nav aria-label="Users pagination">
            <ul class="pagination justify-content-center">
                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">
                        Previous
                    </a>
                </li>
                
                <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>">
                        <?php echo $i; ?>
                    </a>
                </li>
                <?php endfor; ?>
                
                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">
                        Next
                    </a>
                </li>
            </ul>
        </nav>
        
        <p class="text-center text-muted">
            Showing <?php echo min($offset + 1, $total); ?> to <?php echo min($offset + $limit, $total); ?> 
            of <?php echo number_format($total); ?> users
        </p>
        <?php endif; ?>
    </div>
</div>

<!-- User Details Modal -->
<div class="modal fade" id="userModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">User Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="userModalBody">
                <div class="text-center">
                    <i class="fas fa-spinner fa-spin fa-3x"></i>
                    <p>Loading...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function() {
        // View user details
        $('.view-user').click(function() {
            const userId = $(this).data('id');
            
            $('#userModal').modal('show');
            $('#userModalBody').html('<div class="text-center"><i class="fas fa-spinner fa-spin fa-3x"></i></div>');
            
            $.get('ajax/get-user-details.php', { id: userId }, function(data) {
                $('#userModalBody').html(data);
            });
        });
        
        // Suspend user
        $('.suspend-user').click(function() {
            const userId = $(this).data('id');
            const userName = $(this).data('name');
            
            Swal.fire({
                title: 'Suspend User?',
                html: `Are you sure you want to suspend <strong>${userName}</strong>?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ffc107',
                confirmButtonText: 'Yes, suspend'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.post('users.php', {
                        action: 'suspend',
                        user_id: userId,
                        csrf_token: '<?php echo Security::generateCSRFToken(); ?>'
                    }, function(response) {
                        if (response.success) {
                            Swal.fire('Suspended!', response.message, 'success')
                                .then(() => location.reload());
                        } else {
                            Swal.fire('Error', response.message, 'error');
                        }
                    }, 'json');
                }
            });
        });
        
        // Activate user
        $('.activate-user').click(function() {
            const userId = $(this).data('id');
            const userName = $(this).data('name');
            
            Swal.fire({
                title: 'Activate User?',
                html: `Are you sure you want to activate <strong>${userName}</strong>?`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                confirmButtonText: 'Yes, activate'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.post('users.php', {
                        action: 'activate',
                        user_id: userId,
                        csrf_token: '<?php echo Security::generateCSRFToken(); ?>'
                    }, function(response) {
                        if (response.success) {
                            Swal.fire('Activated!', response.message, 'success')
                                .then(() => location.reload());
                        } else {
                            Swal.fire('Error', response.message, 'error');
                        }
                    }, 'json');
                }
            });
        });
        
        // Delete user
        $('.delete-user').click(function() {
            const userId = $(this).data('id');
            const userName = $(this).data('name');
            
            Swal.fire({
                title: 'Delete User?',
                html: `Are you sure you want to permanently delete <strong>${userName}</strong>?<br><br>This action cannot be undone!`,
                icon: 'error',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                confirmButtonText: 'Yes, delete permanently',
                input: 'text',
                inputPlaceholder: 'Type DELETE to confirm',
                inputValidator: (value) => {
                    if (value !== 'DELETE') {
                        return 'You must type DELETE to confirm!';
                    }
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    $.post('users.php', {
                        action: 'delete',
                        user_id: userId,
                        csrf_token: '<?php echo Security::generateCSRFToken(); ?>'
                    }, function(response) {
                        if (response.success) {
                            Swal.fire('Deleted!', response.message, 'success')
                                .then(() => location.reload());
                        } else {
                            Swal.fire('Error', response.message, 'error');
                        }
                    }, 'json');
                }
            });
        });
        
        // Initialize tooltips
        $('[data-bs-toggle="tooltip"]').tooltip();
    });
</script>

<?php include 'includes/footer.php'; ?>