<?php
namespace App\Controllers\Concerns;

trait BulkDeleteRequest
{
    /**
     * Parse ids payload from POST body and validate base shape.
     * Accepts either JSON string or array.
     */
    protected function parseBulkDeleteIds($idsRaw): array
    {
        if (is_string($idsRaw)) {
            $decoded = json_decode($idsRaw, true);
            $ids = is_array($decoded) ? $decoded : [];
        } elseif (is_array($idsRaw)) {
            $ids = $idsRaw;
        } else {
            $ids = [];
        }

        return array_values(array_unique(array_filter(array_map('intval', $ids), static function ($id) {
            return $id > 0;
        })));
    }

    /**
     * Validate ids against table existence (Laravel-like: ids.* exists:table,id).
     */
    protected function validateBulkDeleteIdsExist(\PDO $pdo, string $table, array $ids): array
    {
        if (count($ids) < 1) {
            return [];
        }
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $sql = "SELECT id FROM {$table} WHERE id IN ({$placeholders})";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($ids);
        $rows = $stmt->fetchAll(\PDO::FETCH_COLUMN) ?: [];
        return array_values(array_unique(array_map('intval', $rows)));
    }
}

