<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
// This connects to DB, starts session, checks security, and sets up menu variables.
require_once 'admin-logic.php';


// --- Page-Specific Logic Starts Here ---

// 2. HANDLE ANY ACTIONS SUBMITTED TO THIS PAGE (e.g., status changes)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $user_id_to_update = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT);
    
    if ($user_id_to_update) {
        if ($_POST['action'] === 'toggle_status') {
            // Get current status to toggle it
            $stmt = $conn->prepare("SELECT status FROM users WHERE id = ?");
            $stmt->bind_param("i", $user_id_to_update);
            $stmt->execute();
            $current_status = $stmt->get_result()->fetch_assoc()['status'];
            $stmt->close();
            
            $new_status = ($current_status === 'active') ? 'suspended' : 'active';
            
            $stmt_update = $conn->prepare("UPDATE users SET status = ? WHERE id = ?");
            $stmt_update->bind_param("si", $new_status, $user_id_to_update);
            if ($stmt_update->execute()) {
                $_SESSION['success_message'] = "User status updated to " . ucfirst($new_status) . ".";
            } else {
                $_SESSION['error_message'] = "Failed to update user status.";
            }
            $stmt_update->close();
        }
    }
    header("Location: manage-users.php"); // Redirect to clean the URL
    exit();
}


// 3. FETCH USERS FOR DISPLAY
$records_per_page = 15;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

$where_clauses = ["role != 'admin'"];
$params = [];
$types = '';

// Search term for name or email
$search_term = $_GET['search'] ?? '';
if (!empty($search_term)) {
    $where_clauses[] = "(full_name LIKE ? OR email LIKE ?)";
    $like_term = "%{$search_term}%";
    array_push($params, $like_term, $like_term);
    $types .= 'ss';
}

// Filters
$role_filter = $_GET['role'] ?? '';
if (!empty($role_filter)) { $where_clauses[] = "role = ?"; $params[] = $role_filter; $types .= 's'; }

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

$verification_filter = $_GET['verification_status'] ?? '';
if (!empty($verification_filter)) { $where_clauses[] = "verification_status = ?"; $params[] = $verification_filter; $types .= 's'; }

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

// Count for pagination
$count_sql = "SELECT COUNT(id) as total FROM users $where_sql";
$stmt_count = $conn->prepare($count_sql);
if (count($params) > 0) { $stmt_count->bind_param($types, ...$params); }
$stmt_count->execute();
$total_records = $stmt_count->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);
$stmt_count->close();

// Fetch users for the current page
$fetch_sql = "SELECT id, full_name, email, role, status, verification_status, created_at FROM users 
              $where_sql 
              ORDER BY created_at DESC 
              LIMIT ? OFFSET ?";
$params[] = $records_per_page; $params[] = $offset; $types .= 'ii';
$stmt_fetch = $conn->prepare($fetch_sql);
if (count($params) > 0) { $stmt_fetch->bind_param($types, ...$params); }
$stmt_fetch->execute();
$users_result = $stmt_fetch->get_result();


// 4. INCLUDE THE HTML HEADER
include 'admin-header.php';
?>

<?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"></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"></button></div>
<?php endif; ?>

<div class="card mb-4 shadow-sm">
    <div class="card-header"><i class="bi bi-filter me-1"></i> Filter & Search Users</div>
    <div class="card-body">
        <form action="manage-users.php" method="GET" class="row g-3">
            <div class="col-lg-3 col-md-12"><input type="text" name="search" class="form-control" placeholder="Search by name or email..." value="<?php echo htmlspecialchars($search_term); ?>"></div>
            <div class="col-lg-2 col-md-4">
                <select name="role" class="form-select">
                    <option value="">All Roles</option>
                    <option value="customer" <?php if($role_filter == 'customer') echo 'selected'; ?>>Customer</option>
                    <option value="tour_partner" <?php if($role_filter == 'tour_partner') echo 'selected'; ?>>Tour Partner</option>
                    <option value="hotel_partner" <?php if($role_filter == 'hotel_partner') echo 'selected'; ?>>Hotel Partner</option>
                </select>
            </div>
            <div class="col-lg-2 col-md-4"><select name="verification_status" class="form-select"><option value="">All Verification</option><option value="pending" <?php if($verification_filter == 'pending') echo 'selected'; ?>>Pending</option><option value="verified" <?php if($verification_filter == 'verified') echo 'selected'; ?>>Verified</option><option value="rejected" <?php if($verification_filter == 'rejected') echo 'selected'; ?>>Rejected</option></select></div>
            <div class="col-lg-2 col-md-4"><select name="status" class="form-select"><option value="">All Statuses</option><option value="active" <?php if($status_filter == 'active') echo 'selected'; ?>>Active</option><option value="suspended" <?php if($status_filter == 'suspended') echo 'selected'; ?>>Suspended</option></select></div>
            <div class="col-lg-3 col-md-12 d-grid d-md-flex gap-2"><button type="submit" class="btn btn-primary flex-grow-1">Filter</button><a href="manage-users.php" class="btn btn-secondary flex-grow-1">Clear</a></div>
        </form>
    </div>
</div>

<div class="table-responsive">
    <table class="table table-striped table-hover">
        <thead class="table-dark align-middle">
            <tr>
                <th>User</th>
                <th>Role</th>
                <th>Verification</th>
                <th>Account Status</th>
                <th>Registered</th>
                <th class="text-end">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($users_result->num_rows > 0): ?>
                <?php while ($user = $users_result->fetch_assoc()): ?>
                    <tr>
                        <td>
                            <div class="fw-bold"><?php echo htmlspecialchars($user['full_name']); ?></div>
                            <small class="text-muted"><?php echo htmlspecialchars($user['email']); ?></small>
                        </td>
                        <td>
                            <?php $role_badge = ['customer' => 'primary', 'tour_partner' => 'info', 'hotel_partner' => 'info']; ?>
                            <span class="badge bg-<?php echo $role_badge[$user['role']] ?? 'secondary'; ?>"><?php echo htmlspecialchars(ucfirst(str_replace('_', ' ', $user['role']))); ?></span>
                        </td>
                        <td>
                            <?php if (str_contains($user['role'], '_partner')):
                                $ver_badge = ['pending' => 'warning', 'verified' => 'success', 'rejected' => 'danger']; ?>
                                <span class="badge bg-<?php echo $ver_badge[$user['verification_status']] ?? 'secondary'; ?>"><?php echo htmlspecialchars(ucfirst($user['verification_status'])); ?></span>
                            <?php else: ?>
                                <span class="text-muted small">N/A</span>
                            <?php endif; ?>
                        </td>
                        <td><span class="badge bg-<?php echo ($user['status'] == 'active') ? 'success' : 'danger'; ?>"><?php echo htmlspecialchars(ucfirst($user['status'])); ?></span></td>
                        <td><?php echo date('M d, Y', strtotime($user['created_at'])); ?></td>
                        <td class="text-end">
                            <div class="d-inline-flex gap-1">
                                <?php if ($user['verification_status'] == 'pending'): ?>
                                    <a href="actions/verify_user.php?id=<?php echo $user['id']; ?>&action=approve" class="btn btn-sm btn-success" title="Approve Partner"><i class="bi bi-check-lg"></i></a>
                                    <a href="actions/verify_user.php?id=<?php echo $user['id']; ?>&action=reject" class="btn btn-sm btn-danger" title="Reject Partner"><i class="bi bi-x-lg"></i></a>
                                <?php endif; ?>

                                <?php if (str_contains($user['role'], '_partner')): ?>
                                    <a href="review-documents.php?partner_id=<?php echo $user['id']; ?>" class="btn btn-sm btn-secondary" title="Review Documents"><i class="bi bi-file-earmark-text-fill"></i></a>
                                <?php endif; ?>

                                <a href="edit-user.php?id=<?php echo $user['id']; ?>" class="btn btn-sm btn-warning" title="Edit User"><i class="bi bi-pencil-fill"></i></a>
                            </div>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="6" class="text-center p-4">No users found matching your criteria.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php if($total_pages > 1): ?>
<nav><ul class="pagination justify-content-center mt-4">
    <?php $query_params = $_GET; for ($i = 1; $i <= $total_pages; $i++): $query_params['page'] = $i; ?>
        <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>"><a class="page-link" href="?<?php echo http_build_query($query_params); ?>"><?php echo $i; ?></a></li>
    <?php endfor; ?>
</ul></nav>
<?php endif; ?>

<?php
$stmt_fetch->close();
include 'admin-footer.php';
?>
