<?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';
?>

<div class="container-fluid">
    <h1 class="h3 mb-2 text-gray-800">Manage Users</h1>
    <p class="mb-4">View, search, and manage all customer accounts in the system.</p>

    <!-- Display any success/error messages from redirects -->
    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <!-- User Management Card -->
    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-primary">All Users (<?php echo $total_rows; ?>)</h6>
            <a href="add_user.php" class="btn btn-primary btn-sm"><i class='bx bx-plus me-1'></i> Add New User</a>
        </div>
        <div class="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="input-group">
                            <input type="text" name="search" class="form-control" placeholder="Search by Name, Email, or ID..." value="<?php echo htmlspecialchars($searchTerm); ?>">
                            <button class="btn btn-outline-primary" type="submit"><i class='bx bx-search'></i></button>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <select name="status" class="form-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-2">
                        <a href="manage_users.php" class="btn btn-outline-secondary w-100">Reset</a>
                    </div>
                </div>
            </form>

            <!-- Users Table -->
            <div class="table-responsive">
                <table class="table table-bordered table-hover" width="100%" cellspacing="0">
                    <thead class="table-light">
                        <tr>
                            <th>ID</th>
                            <th>User</th>
                            <th>Email</th>
                            <th>Status</th>
                            <th>Registered On</th>
                            <th>Last Login</th>
                            <th class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($users)): ?>
                            <tr>
                                <td colspan="7" class="text-center text-muted py-5">
                                    <p class="mb-0">No users found matching your criteria.</p>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($users as $user): ?>
                                <tr>
                                    <td><?php echo $user['id']; ?></td>
                                    <td><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></td>
                                    <td><?php echo htmlspecialchars($user['email']); ?></td>
                                    <td>
                                        <?php
                                            $statusClass = ['active' => 'success', 'pending' => 'warning', 'suspended' => 'danger', 'closed' => 'secondary'];
                                            $badgeClass = $statusClass[$user['status']] ?? 'secondary';
                                        ?>
                                        <span class="badge rounded-pill text-bg-<?php echo $badgeClass; ?>"><?php echo ucfirst($user['status']); ?></span>
                                    </td>
                                    <td><?php echo date('d M Y', strtotime($user['created_at'])); ?></td>
                                   <td>
    <?php 
    if (!empty($user['last_login']) && $user['last_login'] != '0000-00-00 00:00:00') {
        echo date('d M Y, H:i', strtotime($user['last_login']));
    } else {
        echo 'Never';
    }
    ?>
</td>

                                    <td class="text-center">
                                        <a href="view_user.php?id=<?php echo $user['id']; ?>" class="btn btn-sm btn-info" title="View Details"><i class='bx bx-show'></i></a>
                                        <a href="edit_user.php?id=<?php echo $user['id']; ?>" class="btn btn-sm btn-warning" title="Edit User"><i class='bx bx-pencil'></i></a>
                                        
                                        <!-- *** MODIFICATION: Delete button is now a form with an onsubmit event *** -->
                                        <form action="delete_user.php" method="POST" class="d-inline" onsubmit="confirmDelete(event, '<?php echo htmlspecialchars(addslashes($user['first_name'] . ' ' . $user['last_name'])); ?>');">
                                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                                            <button type="submit" class="btn btn-sm btn-danger" title="Delete User"><i class='bx bx-trash'></i></button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination Controls (no changes needed here) -->
            <?php if ($total_pages > 1): ?>
            <nav class="mt-4">
                <ul class="pagination justify-content-center">
                    <?php if ($page_num > 1): ?>
                        <li class="page-item"><a class="page-link" href="?page_num=<?php echo $page_num - 1; ?>&search=<?php echo $searchTerm; ?>&status=<?php echo $statusFilter; ?>">Previous</a></li>
                    <?php endif; ?>
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?php if ($i == $page_num) echo 'active'; ?>">
                            <a class="page-link" href="?page_num=<?php echo $i; ?>&search=<?php echo $searchTerm; ?>&status=<?php echo $statusFilter; ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                    <?php if ($page_num < $total_pages): ?>
                        <li class="page-item"><a class="page-link" href="?page_num=<?php echo $page_num + 1; ?>&search=<?php echo $searchTerm; ?>&status=<?php echo $statusFilter; ?>">Next</a></li>
                    <?php endif; ?>
                </ul>
            </nav>
            <?php endif; ?>

        </div>
    </div>
</div>

<!-- *** MODIFICATION: Added SweetAlert JavaScript function *** -->
<script>
function confirmDelete(event, userName) {
    // Prevent the form from submitting immediately
    event.preventDefault();
    
    // The form that was submitted
    const form = event.target;

    Swal.fire({
        title: 'Are you absolutely sure?',
        html: `You are about to permanently delete the user: <br><b>${userName}</b>.<br><br><strong class='text-danger'>This action cannot be undone.</strong>`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete them!',
        reverseButtons: true
    }).then((result) => {
        // If the admin confirms, then we submit the form
        if (result.isConfirmed) {
            form.submit();
        }
    });
}
</script>

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