<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if user is admin
$user_role = $_SESSION['role_name'] ?? '';
if ($user_role !== 'Super Admin') {
    header('Location: index.php');
    exit();
}

$search = $_GET['search'] ?? '';
$role_filter = $_GET['role_id'] ?? '';
$status_filter = $_GET['status'] ?? '';

// Build the user query with correct table and column names
$sql = "SELECT u.*, r.role_name,
        CONCAT(u.first_name, ' ', COALESCE(u.middle_name, ''), ' ', u.last_name) as full_name
        FROM users u
        INNER JOIN roles r ON u.role_id = r.id
        WHERE 1=1";

$params = [];
$types = '';

if (!empty($search)) {
    $sql .= " AND (u.email LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ? OR u.phone LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'ssss';
}

if (!empty($role_filter)) {
    $sql .= " AND u.role_id = ?";
    $params[] = $role_filter;
    $types .= 'i';
}

if (!empty($status_filter)) {
    $sql .= " AND u.status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

$sql .= " ORDER BY u.first_name ASC, u.last_name ASC";

// Get roles for filter
$sql_roles = "SELECT id, role_name FROM roles ORDER BY role_name";
$result_roles = $conn->query($sql_roles);

// Execute the main query
if (!empty($params)) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query($sql);
}

// Get total count for display
$count_sql = "SELECT COUNT(*) as total FROM users";
$count_result = $conn->query($count_sql);
$total_users = $count_result ? $count_result->fetch_assoc()['total'] : 0;
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Users & Roles')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .user-avatar {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .stats-card {
            border-left: 3px solid;
        }
        
        .stats-card.active {
            border-left-color: #0ab39c;
        }
        
        .stats-card.inactive {
            border-left-color: #f06548;
        }
        
        .stats-card.pending {
            border-left-color: #f7b84b;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'System', 'title' => 'Users & Roles')); ?>

                    <!-- Success/Error Messages -->
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="ri-checkbox-circle-line me-2"></i>
                            <?php 
                                echo $_SESSION['success_message']; 
                                unset($_SESSION['success_message']);
                            ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Statistics Cards -->
                    <div class="row mb-3">
                        <?php
                        // Get user statistics
                        $stats_sql = "SELECT 
                            COUNT(*) as total,
                            SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
                            SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) as inactive,
                            SUM(CASE WHEN status = 'pending_verification' THEN 1 ELSE 0 END) as pending
                            FROM users";
                        $stats_result = $conn->query($stats_sql);
                        $stats = $stats_result ? $stats_result->fetch_assoc() : ['total' => 0, 'active' => 0, 'inactive' => 0, 'pending' => 0];
                        ?>
                        
                        <div class="col-md-3">
                            <div class="card stats-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-primary text-primary rounded-circle fs-3">
                                                <i class="ri-group-line"></i>
                                            </span>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-uppercase fw-semibold fs-12 text-muted mb-1">Total Users</p>
                                            <h4 class=" mb-0"><?php echo number_format($stats['total']); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="card stats-card active">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-success text-success rounded-circle fs-3">
                                                <i class="ri-user-line"></i>
                                            </span>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-uppercase fw-semibold fs-12 text-muted mb-1">Active Users</p>
                                            <h4 class=" mb-0"><?php echo number_format($stats['active']); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="card stats-card inactive">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-danger text-danger rounded-circle fs-3">
                                                <i class="ri-user-unfollow-line"></i>
                                            </span>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-uppercase fw-semibold fs-12 text-muted mb-1">Inactive Users</p>
                                            <h4 class=" mb-0"><?php echo number_format($stats['inactive']); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="card stats-card pending">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-warning text-warning rounded-circle fs-3">
                                                <i class="ri-time-line"></i>
                                            </span>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-uppercase fw-semibold fs-12 text-muted mb-1">Pending</p>
                                            <h4 class=" mb-0"><?php echo number_format($stats['pending']); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Card -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-4">
                                            <label class="form-label">Search</label>
                                            <input type="text" class="form-control" name="search" 
                                                   value="<?php echo htmlspecialchars($search); ?>" 
                                                   placeholder="Search by name, email, or phone">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Role</label>
                                            <select class="form-select" name="role_id">
                                                <option value="">All Roles</option>
                                                <?php 
                                                // Reset pointer for roles
                                                $result_roles->data_seek(0);
                                                while($role = $result_roles->fetch_assoc()): 
                                                ?>
                                                    <option value="<?php echo $role['id']; ?>" 
                                                            <?php echo $role_filter == $role['id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($role['role_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Status</label>
                                            <select class="form-select" name="status">
                                                <option value="">All Status</option>
                                                <option value="active" <?php echo $status_filter == 'active' ? 'selected' : ''; ?>>Active</option>
                                                <option value="inactive" <?php echo $status_filter == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                                <option value="pending_verification" <?php echo $status_filter == 'pending_verification' ? 'selected' : ''; ?>>Pending Verification</option>
                                                <option value="banned" <?php echo $status_filter == 'banned' ? 'selected' : ''; ?>>Banned</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">&nbsp;</label>
                                            <div class="d-flex gap-2">
                                                <button type="submit" class="btn btn-primary flex-fill">
                                                    <i class="ri-search-line me-1"></i>Filter
                                                </button>
                                                <a href="list_users.php" class="btn btn-secondary">
                                                    <i class="ri-refresh-line"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Users Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">
                                        <i class="ri-group-line me-2"></i>All Users 
                                        <span class="badge bg-primary"><?php echo $result ? $result->num_rows : 0; ?></span>
                                    </h4>
                                    <div class="flex-shrink-0">
                                        <a href="add_user.php" class="btn btn-primary">
                                            <i class="ri-add-line align-bottom me-1"></i>Add User
                                        </a>
                                        <a href="roles_permissions.php" class="btn btn-soft-secondary ms-2">
                                            <i class="ri-shield-user-line align-bottom me-1"></i>Manage Roles
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover table-nowrap align-middle mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>User</th>
                                                    <th>Email</th>
                                                    <th>Phone</th>
                                                    <th>Role</th>
                                                    <th>Status</th>
                                                    <th>Last Login</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($user = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <div class="d-flex align-items-center">
                                                                    <div class="flex-shrink-0 me-2">
                                                                        <?php if ($user['profile_photo_url']): ?>
                                                                            <img src="<?php echo htmlspecialchars($user['profile_photo_url']); ?>" 
                                                                                 alt="<?php echo htmlspecialchars($user['full_name']); ?>" 
                                                                                 class="avatar-xs rounded-circle">
                                                                        <?php else: ?>
                                                                            <div class="avatar-xs">
                                                                                <span class="avatar-title rounded-circle bg-soft-primary text-primary">
                                                                                    <?php 
                                                                                    $name = trim($user['full_name']);
                                                                                    $initials = '';
                                                                                    $parts = explode(' ', $name);
                                                                                    foreach($parts as $part) {
                                                                                        if (!empty($part)) {
                                                                                            $initials .= strtoupper(substr($part, 0, 1));
                                                                                            if (strlen($initials) >= 2) break;
                                                                                        }
                                                                                    }
                                                                                    echo $initials ?: 'U';
                                                                                    ?>
                                                                                </span>
                                                                            </div>
                                                                        <?php endif; ?>
                                                                    </div>
                                                                    <div class="flex-grow-1">
                                                                        <h5 class="fs-14 mb-0">
                                                                            <?php echo htmlspecialchars($user['full_name']); ?>
                                                                        </h5>
                                                                        <small class="text-muted">ID: <?php echo $user['id']; ?></small>
                                                                    </div>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <a href="mailto:<?php echo htmlspecialchars($user['email']); ?>" class="text-body">
                                                                    <?php echo htmlspecialchars($user['email']); ?>
                                                                </a>
                                                            </td>
                                                            <td>
                                                                <?php if ($user['phone']): ?>
                                                                    <a href="tel:<?php echo htmlspecialchars($user['phone']); ?>" class="text-body">
                                                                        <?php echo htmlspecialchars($user['phone']); ?>
                                                                    </a>
                                                                <?php else: ?>
                                                                    <span class="text-muted">Not provided</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo htmlspecialchars($user['role_name']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $status = $user['status'] ?? 'active';
                                                                $status_display = ucfirst(str_replace('_', ' ', $status));
                                                                $status_colors = [
                                                                    'active' => 'success',
                                                                    'inactive' => 'secondary',
                                                                    'pending_verification' => 'warning',
                                                                    'banned' => 'danger'
                                                                ];
                                                                $status_color = $status_colors[$status] ?? 'secondary';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $status_color; ?> text-<?php echo $status_color; ?>">
                                                                    <?php echo $status_display; ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php if ($user['last_login']): ?>
                                                                    <small class="text-muted" title="<?php echo date('Y-m-d H:i:s', strtotime($user['last_login'])); ?>">
                                                                        <?php echo date('M d, Y', strtotime($user['last_login'])); ?>
                                                                        <br>
                                                                        <span class="text-muted"><?php echo date('h:i A', strtotime($user['last_login'])); ?></span>
                                                                    </small>
                                                                <?php else: ?>
                                                                    <span class="badge bg-soft-secondary text-secondary">Never</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <div class="dropdown">
                                                                    <button class="btn btn-soft-secondary btn-sm dropdown-toggle" 
                                                                            type="button" id="dropdownMenuButton<?php echo $user['id']; ?>"
                                                                            data-bs-toggle="dropdown" aria-expanded="false">
                                                                        <i class="ri-more-fill"></i>
                                                                    </button>
                                                                    <ul class="dropdown-menu dropdown-menu-end" 
                                                                        aria-labelledby="dropdownMenuButton<?php echo $user['id']; ?>">
                                                                        <li>
                                                                            <a class="dropdown-item" href="view_user.php?id=<?php echo $user['id']; ?>">
                                                                                <i class="ri-eye-line align-bottom me-2 text-muted"></i>View Details
                                                                            </a>
                                                                        </li>
                                                                        <li>
                                                                            <a class="dropdown-item" href="edit_user.php?id=<?php echo $user['id']; ?>">
                                                                                <i class="ri-pencil-line align-bottom me-2 text-muted"></i>Edit User
                                                                            </a>
                                                                        </li>
                                                                        <li><hr class="dropdown-divider"></li>
                                                                        <li>
                                                                            <a class="dropdown-item" href="reset_password.php?id=<?php echo $user['id']; ?>">
                                                                                <i class="ri-lock-password-line align-bottom me-2 text-muted"></i>Reset Password
                                                                            </a>
                                                                        </li>
                                                                        <?php if ($status == 'active'): ?>
                                                                        <li>
                                                                            <a class="dropdown-item text-warning" 
                                                                               href="deactivate_user.php?id=<?php echo $user['id']; ?>"
                                                                               onclick="return confirm('Are you sure you want to deactivate this user?')">
                                                                                <i class="ri-user-unfollow-line align-bottom me-2"></i>Deactivate
                                                                            </a>
                                                                        </li>
                                                                        <?php else: ?>
                                                                        <li>
                                                                            <a class="dropdown-item text-success" 
                                                                               href="activate_user.php?id=<?php echo $user['id']; ?>"
                                                                               onclick="return confirm('Are you sure you want to activate this user?')">
                                                                                <i class="ri-user-add-line align-bottom me-2"></i>Activate
                                                                            </a>
                                                                        </li>
                                                                        <?php endif; ?>
                                                                        <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                                                        <li><hr class="dropdown-divider"></li>
                                                                        <li>
                                                                            <a class="dropdown-item text-danger" 
                                                                               href="delete_user.php?id=<?php echo $user['id']; ?>"
                                                                               onclick="return confirm('Are you sure you want to delete this user? This action cannot be undone.')">
                                                                                <i class="ri-delete-bin-line align-bottom me-2"></i>Delete User
                                                                            </a>
                                                                        </li>
                                                                        <?php endif; ?>
                                                                    </ul>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="7" class="text-center py-5">
                                                            <div class="text-muted">
                                                                <i class="ri-group-line fs-1 d-block mb-3"></i>
                                                                <h5>No users found</h5>
                                                                <p class="mb-3">
                                                                    <?php if (!empty($search) || !empty($role_filter) || !empty($status_filter)): ?>
                                                                        Try adjusting your filters
                                                                    <?php else: ?>
                                                                        Get started by adding your first user
                                                                    <?php endif; ?>
                                                                </p>
                                                                <a href="add_user.php" class="btn btn-primary">
                                                                    <i class="ri-add-line me-1"></i>Add User
                                                                </a>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        // Auto-dismiss success messages after 5 seconds
        setTimeout(function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                const bsAlert = new bootstrap.Alert(alert);
                bsAlert.close();
            });
        }, 5000);

        // Add loading state to form submission
        document.querySelector('form')?.addEventListener('submit', function() {
            const btn = this.querySelector('button[type="submit"]');
            if (btn) {
                btn.disabled = true;
                btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Loading...';
            }
        });
    </script>
</body>
</html>