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

$action = sync_clean_text($input['action'] ?? 'clear_resend');
$requests = $input['tables'] ?? null;

if (!in_array($action, ['mark_for_resend', 'clear_resend'], true)) {
    sync_fail('Action manual sync tidak valid.', 400);
}

if (!is_array($requests)) {
    sync_fail('Parameter tables wajib berupa object table => [uuid].', 400);
}

$clear = $action === 'clear_resend';
$total = 0;
$detail = [];

mysqli_begin_transaction($conn);

try {
    foreach ($requests as $tableRaw => $uuids) {
        $table = sync_clean_text((string)$tableRaw);
        sync_allowed_table($table);

        if (!is_array($uuids)) {
            throw new RuntimeException("Payload uuid untuk table `$table` harus berupa array.");
        }

        $affected = sync_mark_force_resend($conn, $table, $companyId, $uuids, $clear);
        $detail[$table] = $affected;
        $total += $affected;
    }

    mysqli_commit($conn);
    sync_response([
        'success' => true,
        'action' => $action,
        'company_id' => $companyId,
        'total' => $total,
        'detail' => $detail,
    ]);
} catch (Throwable $exception) {
    mysqli_rollback($conn);
    sync_fail(
        'Manual sync ack gagal diproses.',
        500,
        ['detail' => $exception->getMessage()]
    );
}
