<?php
// This is the first line of ANY secure admin page.
require_once 'includes/auth_check.php';

// Generate a CSRF token for the delete forms on this page
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

// Set the current page for the sidebar active state
$page = 'users';

// Include your database and functions
require_once '../config/database.php';
require_once '../includes/functions.php';

// Create a database connection
$database = new Database();
$db = $database->getConnection();

// --- User Management Logic (same as before) ---
try {
    // Base query
    $query = "SELECT id, first_name, last_name, email, created_at, status, last_login FROM users WHERE role = 'user'";
    $params = [];

    // Search functionality
    $searchTerm = $_GET['search'] ?? '';
    if (!empty($searchTerm)) {
        $query .= " AND (first_name LIKE :search OR last_name LIKE :search OR email LIKE :search OR id = :search_id)";
        $params[':search'] = "%$searchTerm%";
        $params[':search_id'] = $searchTerm;
    }

    // Filter by status
    $statusFilter = $_GET['status'] ?? '';
    if (!empty($statusFilter) && in_array($statusFilter, ['active', 'pending', 'suspended', 'closed'])) {
        $query .= " AND status = :status";
        $params[':status'] = $statusFilter;
    }

    // Sorting
    $sort_by = $_GET['sort_by'] ?? 'created_at';
    $sort_order = $_GET['sort_order'] ?? 'DESC';
    $valid_sort_columns = ['id', 'first_name', 'email', 'created_at', 'status', 'last_login'];
    if (in_array($sort_by, $valid_sort_columns)) {
        $query .= " ORDER BY $sort_by " . ($sort_order === 'ASC' ? 'ASC' : 'DESC');
    }

    // Pagination
    $page_num = isset($_GET['page_num']) ? (int)$_GET['page_num'] : 1;
    $records_per_page = 15;
    $offset = ($page_num - 1) * $records_per_page;

    // Get total number of records for pagination
    $count_query = preg_replace('/SELECT .* FROM/', 'SELECT COUNT(id) FROM', $query);
    $total_rows_stmt = $db->prepare($count_query);
    $total_rows_stmt->execute($params);
    $total_rows = $total_rows_stmt->fetchColumn();
    $total_pages = ceil($total_rows / $records_per_page);

    // Add limit for pagination
    $query .= " LIMIT :limit OFFSET :offset";
    
    // Prepare and execute the final query
    $stmt = $db->prepare($query);
    $stmt->bindValue(':limit', $records_per_page, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    foreach ($params as $key => &$val) {
        $stmt->bindParam($key, $val);
    }
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    error_log("Manage Users DB Error: " . $e->getMessage());
    $users = [];
    $pageError = "Could not load user data. Please check the system logs.";
}

// Include the header for the admin page
include 'includes/header.php';
?>

<style>
:root {
    --primary-color: #4f46e5;
    --primary-light: rgba(79, 70, 229, 0.1);
    --primary-dark: #4338ca;
    --success-color: #10b981;
    --success-light: rgba(16, 185, 129, 0.1);
    --danger-color: #ef4444;
    --danger-light: rgba(239, 68, 68, 0.1);
    --warning-color: #f59e0b;
    --warning-light: rgba(245, 158, 11, 0.1);
    --info-color: #0ea5e9;
    --info-light: rgba(14, 165, 233, 0.1);
    --secondary-color: #6b7280;
    --secondary-light: rgba(107, 114, 128, 0.1);
    --border-color: #e2e8f0;
    --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    --transition-base: all 0.3s ease;
}

/* Main Container Styles */
.content-wrapper {
    padding: 2rem;
    background-color: #f9fafb;
    min-height: calc(100vh - 60px);
}

/* Page Header */
.page-header {
    margin-bottom: 2rem;
}

.page-title {
    font-size: 1.75rem;
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
}

.page-title i {
    margin-right: 0.75rem;
    font-size: 2rem;
    color: var(--primary-color);
}

.page-subtitle {
    color: #64748b;
    font-size: 1rem;
    margin-bottom: 0;
}

/* Card Styles */
.app-card {
    background: white;
    border-radius: 1rem;
    box-shadow: var(--card-shadow);
    border: none;
    overflow: hidden;
    margin-bottom: 2rem;
}

.app-card-header {
    padding: 1.5rem;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.app-card-title {
    font-size: 1.25rem;
    font-weight: 600;
    color: #1e293b;
    margin: 0;
    display: flex;
    align-items: center;
}

.app-card-title i {
    font-size: 1.5rem;
    margin-right: 0.75rem;
    color: var(--primary-color);
}

.app-card-body {
    padding: 1.5rem;
}

.app-card-footer {
    padding: 1.25rem 1.5rem;
    background-color: #f8fafc;
    border-top: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* Table Styles */
.app-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
}

.app-table th {
    font-weight: 600;
    text-transform: uppercase;
    font-size: 0.75rem;
    letter-spacing: 0.5px;
    color: #64748b;
    padding: 1rem;
    background-color: #f8fafc;
    border-bottom: 1px solid var(--border-color);
}

.app-table td {
    padding: 1rem;
    vertical-align: middle;
    border-bottom: 1px solid var(--border-color);
    color: #1e293b;
}

.app-table tr:last-child td {
    border-bottom: none;
}

.app-table tr:hover {
    background-color: #f9fafb;
}

/* User Avatar */
.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--primary-light);
    color: var(--primary-color);
    font-weight: 600;
    margin-right: 0.75rem;
    flex-shrink: 0;
}

/* Status Badges */
.status-badge {
    display: inline-flex;
    align-items: center;
    padding: 0.35rem 0.75rem;
    border-radius: 2rem;
    font-weight: 500;
    font-size: 0.75rem;
}

.status-badge i {
    margin-right: 0.375rem;
    font-size: 0.875rem;
}

/* Search and Filter */
.search-box {
    position: relative;
}

.search-box .form-control {
    padding-left: 2.75rem;
    height: 2.75rem;
    border-radius: 0.5rem;
    border: 1px solid var(--border-color);
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.search-box .search-icon {
    position: absolute;
    left: 1rem;
    top: 50%;
    transform: translateY(-50%);
    color: #94a3b8;
    font-size: 1.25rem;
    pointer-events: none;
}

.filter-select {
    height: 2.75rem;
    border-radius: 0.5rem;
    border: 1px solid var(--border-color);
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    padding-left: 1rem;
    padding-right: 2.5rem;
    appearance: none;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right 1rem center;
    background-size: 16px 12px;
}

/* Action Buttons */
.action-btn {
    width: 32px;
    height: 32px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 0.375rem;
    transition: var(--transition-base);
    border: 1px solid var(--border-color);
    background-color: white;
    color: #64748b;
}

.action-btn:hover {
    background-color: #f1f5f9;
    color: #1e293b;
}

.action-btn-primary {
    background-color: var(--primary-light);
    color: var(--primary-color);
    border-color: var(--primary-light);
}

.action-btn-primary:hover {
    background-color: var(--primary-color);
    color: white;
}

.action-btn-danger {
    background-color: var(--danger-light);
    color: var(--danger-color);
    border-color: var(--danger-light);
}

.action-btn-danger:hover {
    background-color: var(--danger-color);
    color: white;
}

/* Pagination */
.app-pagination {
    display: flex;
    list-style: none;
    padding: 0;
    margin: 0;
}

.app-pagination li {
    margin: 0 0.25rem;
}

.app-pagination .page-link {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border-radius: 0.375rem;
    border: 1px solid var(--border-color);
    color: #64748b;
    text-decoration: none;
    transition: var(--transition-base);
}

.app-pagination .page-link:hover {
    background-color: #f1f5f9;
    color: #1e293b;
}

.app-pagination .active .page-link {
    background-color: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}

.app-pagination .disabled .page-link {
    color: #cbd5e1;
    pointer-events: none;
    background-color: #f8fafc;
}

/* Empty State */
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 3rem 1rem;
    text-align: center;
}

.empty-state i {
    font-size: 3rem;
    margin-bottom: 1rem;
    opacity: 0.2;
}

.empty-state p {
    color: var(--secondary-color);
    max-width: 300px;
    margin: 0 auto 1rem;
}

/* Alert Styles */
.app-alert {
    padding: 1rem 1.25rem;
    border-radius: 0.5rem;
    margin-bottom: 1.5rem;
    display: flex;
    align-items: flex-start;
}

.app-alert-icon {
    margin-right: 0.75rem;
    font-size: 1.25rem;
    padding-top: 0.125rem;
}

.app-alert-content {
    flex: 1;
}

.app-alert-title {
    font-weight: 600;
    margin-bottom: 0.25rem;
}

.app-alert-success {
    background-color: var(--success-light);
    border-left: 4px solid var(--success-color);
    color: #065f46;
}

.app-alert-danger {
    background-color: var(--danger-light);
    border-left: 4px solid var(--danger-color);
    color: #991b1b;
}

/* Responsive Adjustments */
@media (max-width: 768px) {
    .content-wrapper {
        padding: 1.5rem;
    }
    
    .app-card-header {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .app-card-header .btn {
        margin-top: 1rem;
        align-self: flex-start;
    }
    
    .filter-row {
        flex-direction: column;
    }
    
    .filter-row > div {
        margin-bottom: 1rem;
        width: 100%;
    }
    
    .action-buttons {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .action-buttons .btn {
        margin-bottom: 0.5rem;
    }
}
</style>

<div class="content-wrapper">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="page-title">
                    <i class="bx bx-user-circle"></i>
                    Manage Users
                </h1>
                <p class="page-subtitle">View, search, and manage all customer accounts in the system</p>
            </div>
            <div>
                <a href="add_user.php" class="btn btn-primary">
                    <i class='bx bx-plus me-1'></i> Add New User
                </a>
            </div>
        </div>

        <!-- Display any success/error messages from redirects -->
        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="app-alert app-alert-success mb-4">
                <div class="app-alert-icon">
                    <i class="bx bx-check-circle"></i>
                </div>
                <div class="app-alert-content">
                    <div class="app-alert-title">Success</div>
                    <div><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?></div>
                </div>
                <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="app-alert app-alert-danger mb-4">
                <div class="app-alert-icon">
                    <i class="bx bx-error-circle"></i>
                </div>
                <div class="app-alert-content">
                    <div class="app-alert-title">Error</div>
                    <div><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?></div>
                </div>
                <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- User Management Card -->
        <div class="app-card">
            <div class="app-card-header">
                <h5 class="app-card-title">
                    <i class="bx bx-user-circle"></i>
                    All Users
                    <span class="badge bg-secondary ms-2"><?php echo $total_rows; ?></span>
                </h5>
                <div class="dropdown">
                    <button class="btn btn-outline-secondary btn-sm dropdown-toggle" type="button" id="exportDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class='bx bx-export me-1'></i> Export
                    </button>
                    <ul class="dropdown-menu" aria-labelledby="exportDropdown">
                        <li><a class="dropdown-item" href="#"><i class='bx bx-file me-2'></i>CSV</a></li>
                        <li><a class="dropdown-item" href="#"><i class='bx bxs-file-pdf me-2'></i>PDF</a></li>
                        <li><a class="dropdown-item" href="#"><i class='bx bx-printer me-2'></i>Print</a></li>
                    </ul>
                </div>
            </div>
            <div class="app-card-body">
                <!-- Search and Filter Form -->
                <form method="GET" action="manage_users.php" class="mb-4">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <div class="search-box">
                                <i class="bx bx-search search-icon"></i>
                                <input type="text" name="search" class="form-control" placeholder="Search by Name, Email, or ID..." value="<?php echo htmlspecialchars($searchTerm); ?>">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <select name="status" class="form-select filter-select" onchange="this.form.submit()">
                                <option value="">All Statuses</option>
                                <option value="active" <?php if ($statusFilter == 'active') echo 'selected'; ?>>Active</option>
                                <option value="pending" <?php if ($statusFilter == 'pending') echo 'selected'; ?>>Pending</option>
                                <option value="suspended" <?php if ($statusFilter == 'suspended') echo 'selected'; ?>>Suspended</option>
                                <option value="closed" <?php if ($statusFilter == 'closed') echo 'selected'; ?>>Closed</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select name="sort_by" class="form-select filter-select" onchange="this.form.submit()">
                                <option value="created_at" <?php if ($sort_by == 'created_at') echo 'selected'; ?>>Sort by: Date</option>
                                <option value="first_name" <?php if ($sort_by == 'first_name') echo 'selected'; ?>>Sort by: Name</option>
                                <option value="id" <?php if ($sort_by == 'id') echo 'selected'; ?>>Sort by: ID</option>
                            </select>
                        </div>
                        <div class="col-md-1">
                            <a href="manage_users.php" class="btn btn-outline-secondary w-100" title="Reset Filters">
                                <i class='bx bx-reset'></i>
                            </a>
                        </div>
                    </div>
                </form>

                <!-- Users Table -->
                <div class="table-responsive">
                    <table class="app-table">
                        <thead>
                            <tr>
                                <th style="width: 60px;">ID</th>
                                <th>User</th>
                                <th>Email</th>
                                <th>Status</th>
                                <th>Registered</th>
                                <th>Last Login</th>
                                <th style="width: 120px; text-align: center;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($users)): ?>
                                <tr>
                                    <td colspan="7">
                                        <div class="empty-state">
                                            <i class="bx bx-search"></i>
                                            <p>No users found matching your criteria.</p>
                                            <a href="manage_users.php" class="btn btn-sm btn-outline-primary">Clear filters</a>
                                        </div>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($users as $user): ?>
                                    <tr>
                                        <td><?php echo $user['id']; ?></td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="user-avatar">
                                                    <?php echo strtoupper(substr($user['first_name'], 0, 1)); ?>
                                                </div>
                                                <div>
                                                    <div class="fw-medium"><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></div>
                                                </div>
                                            </div>
                                        </td>
                                        <td><?php echo htmlspecialchars($user['email']); ?></td>
                                        <td>
                                            <?php
                                                $statusClass = [
                                                    'active' => 'success',
                                                    'pending' => 'warning',
                                                    'suspended' => 'danger',
                                                    'closed' => 'secondary'
                                                ];
                                                $badgeClass = $statusClass[$user['status']] ?? 'secondary';
                                                $statusIcon = [
                                                    'active' => 'bx-check-circle',
                                                    'pending' => 'bx-time',
                                                    'suspended' => 'bx-block',
                                                    'closed' => 'bx-x-circle'
                                                ];
                                                $icon = $statusIcon[$user['status']] ?? 'bx-question-mark';
                                            ?>
                                            <span class="status-badge bg-<?php echo $badgeClass; ?>-light text-<?php echo $badgeClass; ?>">
                                                <i class='bx <?php echo $icon; ?>'></i>
                                                <?php echo ucfirst($user['status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="d-flex align-items-center text-muted">
                                                <i class='bx bx-calendar me-1'></i>
                                                <?php echo date('d M Y', strtotime($user['created_at'])); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <?php 
                                            if (!empty($user['last_login']) && $user['last_login'] != '0000-00-00 00:00:00') {
                                                echo '<div class="d-flex align-items-center text-muted">';
                                                echo '<i class="bx bx-log-in me-1"></i>';
                                                echo date('d M Y, H:i', strtotime($user['last_login']));
                                                echo '</div>';
                                            } else {
                                                echo '<span class="text-muted"><i class="bx bx-minus"></i> Never</span>';
                                            }
                                            ?>
                                        </td>
                                        <td>
                                            <div class="d-flex justify-content-center gap-2">
                                                <a href="view_user.php?id=<?php echo $user['id']; ?>" class="action-btn action-btn-primary" title="View Details">
                                                    <i class='bx bx-show'></i>
                                                </a>
                                                <a href="edit_user.php?id=<?php echo $user['id']; ?>" class="action-btn action-btn-primary" title="Edit User">
                                                    <i class='bx bx-edit'></i>
                                                </a>
                                                <button type="button" class="action-btn action-btn-danger" 
                                                        onclick="confirmDelete(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars(addslashes($user['first_name'] . ' ' . $user['last_name'])); ?>')" 
                                                        title="Delete User">
                                                    <i class='bx bx-trash'></i>
                                                </button>
                                            </div>
                                            <form id="delete-form-<?php echo $user['id']; ?>" action="delete_user.php" method="POST" class="d-none">
                                                <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination Controls -->
                <?php if ($total_pages > 1): ?>
                <div class="app-card-footer">
                    <div class="text-muted small">
                        Showing <?php echo min(($page_num - 1) * $records_per_page + 1, $total_rows); ?> to 
                        <?php echo min($page_num * $records_per_page, $total_rows); ?> of 
                        <?php echo $total_rows; ?> users
                    </div>
                    <nav aria-label="Page navigation">
                        <ul class="app-pagination">
                            <?php if ($page_num > 1): ?>
                                <li>
                                    <a class="page-link" href="?page_num=<?php echo $page_num - 1; ?>&search=<?php echo urlencode($searchTerm); ?>&status=<?php echo urlencode($statusFilter); ?>&sort_by=<?php echo urlencode($sort_by); ?>&sort_order=<?php echo urlencode($sort_order); ?>" aria-label="Previous">
                                        <i class='bx bx-chevron-left'></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                            
                            <?php
                            // Show limited page numbers with ellipsis
                            $start_page = max(1, $page_num - 2);
                            $end_page = min($total_pages, $page_num + 2);
                            
                            if ($start_page > 1) {
                                echo '<li><a class="page-link" href="?page_num=1&search=' . urlencode($searchTerm) . '&status=' . urlencode($statusFilter) . '&sort_by=' . urlencode($sort_by) . '&sort_order=' . urlencode($sort_order) . '">1</a></li>';
                                if ($start_page > 2) {
                                    echo '<li class="disabled"><span class="page-link">...</span></li>';
                                }
                            }
                            
                            for ($i = $start_page; $i <= $end_page; $i++): ?>
                                <li class="<?php if ($i == $page_num) echo 'active'; ?>">
                                    <a class="page-link" href="?page_num=<?php echo $i; ?>&search=<?php echo urlencode($searchTerm); ?>&status=<?php echo urlencode($statusFilter); ?>&sort_by=<?php echo urlencode($sort_by); ?>&sort_order=<?php echo urlencode($sort_order); ?>"><?php echo $i; ?></a>
                                </li>
                            <?php endfor;
                            
                            if ($end_page < $total_pages) {
                                if ($end_page < $total_pages - 1) {
                                    echo '<li class="disabled"><span class="page-link">...</span></li>';
                                }
                                echo '<li><a class="page-link" href="?page_num=' . $total_pages . '&search=' . urlencode($searchTerm) . '&status=' . urlencode($statusFilter) . '&sort_by=' . urlencode($sort_by) . '&sort_order=' . urlencode($sort_order) . '">' . $total_pages . '</a></li>';
                            }
                            ?>
                            
                            <?php if ($page_num < $total_pages): ?>
                                <li>
                                    <a class="page-link" href="?page_num=<?php echo $page_num + 1; ?>&search=<?php echo urlencode($searchTerm); ?>&status=<?php echo urlencode($statusFilter); ?>&sort_by=<?php echo urlencode($sort_by); ?>&sort_order=<?php echo urlencode($sort_order); ?>" aria-label="Next">
                                        <i class='bx bx-chevron-right'></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Updated JavaScript for Delete Confirmation -->
<script>
function confirmDelete(userId, userName) {
    Swal.fire({
        title: 'Delete User Account',
        html: `Are you sure you want to delete <strong>${userName}</strong>?<br><br><span class="text-danger">This action cannot be undone.</span>`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#6b7280',
                confirmButtonText: 'Yes, delete user',
        cancelButtonText: 'Cancel',
        reverseButtons: true,
        focusCancel: true
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById(`delete-form-${userId}`).submit();
        }
    });
}

// Add sorting functionality
document.addEventListener('DOMContentLoaded', function() {
    const sortSelect = document.querySelector('select[name="sort_by"]');
    if (sortSelect) {
        sortSelect.addEventListener('change', function() {
            this.form.submit();
        });
    }
    
    // Initialize tooltips if Bootstrap is available
    if (typeof bootstrap !== 'undefined' && typeof bootstrap.Tooltip !== 'undefined') {
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[title]'));
        tooltipTriggerList.map(function(tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }
});
</script>

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