0; })); $total_uploaded = count($user_ids); if ($total_uploaded === 0) { throw new Exception('No valid numeric IDs found'); } $pdo = getClientDBConnection(); // shop DB $panelPdo = getPanelDBConnection(); // panel DB // Verify project belongs to this client $stmt = $pdo->prepare("SELECT id, project_id FROM projects WHERE id = ? AND client_id = ?"); $stmt->execute([$project_id, $_SESSION['client_id']]); if (!$stmt->fetch()) { throw new Exception('Unauthorized'); } // Step 1: Check which IDs exist in panel DB and are active + email_verified // Process in batches of 1000 to avoid query limits $valid_user_ids = []; $batches = array_chunk($user_ids, 1000); foreach ($batches as $batch) { $placeholders = str_repeat('?,', count($batch) - 1) . '?'; $stmt = $panelPdo->prepare(" SELECT id FROM users WHERE id IN ($placeholders) AND status = 'active' AND email_verified = 1 "); $stmt->execute($batch); $valid_user_ids = array_merge($valid_user_ids, $stmt->fetchAll(PDO::FETCH_COLUMN)); } $valid_active = count($valid_user_ids); $not_found = $total_uploaded - $valid_active; // Step 2: Check which valid IDs are already in selections for this project $already_in_selections = 0; $already_ids = []; if (!empty($valid_user_ids)) { // Get all selection IDs for this project $stmt = $pdo->prepare("SELECT id FROM project_selections WHERE project_id = ?"); $stmt->execute([$project_id]); $project_selection_ids = $stmt->fetchAll(PDO::FETCH_COLUMN); if (!empty($project_selection_ids)) { // Find which valid_user_ids are already members of these selections $selPlaceholders = str_repeat('?,', count($project_selection_ids) - 1) . '?'; // Process in batches $valid_batches = array_chunk($valid_user_ids, 1000); foreach ($valid_batches as $batch) { $userPlaceholders = str_repeat('?,', count($batch) - 1) . '?'; $stmt = $pdo->prepare(" SELECT DISTINCT user_id FROM selection_members WHERE selection_id IN ($selPlaceholders) AND user_id IN ($userPlaceholders) "); $params = array_merge($project_selection_ids, $batch); $stmt->execute($params); $already_ids = array_merge($already_ids, $stmt->fetchAll(PDO::FETCH_COLUMN)); } $already_ids = array_unique($already_ids); $already_in_selections = count($already_ids); } } // Step 3: Compute available to add (valid minus already assigned) $available_ids = array_diff($valid_user_ids, $already_ids); $available_to_add = count($available_ids); echo json_encode([ 'total_uploaded' => $total_uploaded, 'valid_active' => $valid_active, 'not_found' => $not_found, 'already_in_selections' => $already_in_selections, 'available_to_add' => $available_to_add, 'valid_user_ids' => array_values($available_ids) // only the ones actually available ]); } catch (Exception $e) { http_response_code(400); echo json_encode(['error' => $e->getMessage()]); }