<?php
declare(strict_types=1);

require_once __DIR__ . '/sync_support/bootstrap.php';

$input = sync_json_input();
$companyId = sync_request_company_id($input);
sync_assert_company_access($companyId);

$tablesInput = $input['tables'] ?? array_keys(sync_table_registry());
if (!is_array($tablesInput)) {
    sync_fail('Parameter tables harus berupa array.', 400);
}

$limitPerTable = (int)($input['limit_per_table'] ?? 200);
$limitPerTable = $limitPerTable > 0 ? min($limitPerTable, 1000) : 200;

$payload = [];
$total = 0;

foreach ($tablesInput as $tableRaw) {
    $table = sync_clean_text($tableRaw);
    if ($table === '') {
        continue;
    }

    sync_allowed_table($table);
    $rows = sync_force_resend_rows($conn, $table, $companyId, $limitPerTable);
    $payload[$table] = $rows;
    $total += count($rows);
}

sync_response([
    'success' => true,
    'company_id' => $companyId,
    'total' => $total,
    'data' => $payload,
]);
