<?php
declare(strict_types=1);

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

$input = sync_json_input();
$table = sync_clean_text($input['table'] ?? '');
$rows = $input['data'] ?? null;

if ($table === '') {
    sync_fail('Parameter table wajib diisi.', 400);
}

if (!is_array($rows)) {
    sync_fail('Parameter data wajib berupa array.', 400);
}

$summary = [
    'success' => true,
    'table' => $table,
    'inserted' => 0,
    'updated' => 0,
    'skipped' => 0,
    'results' => [],
];

mysqli_begin_transaction($conn);

try {
    foreach ($rows as $row) {
        if (!is_array($row)) {
            throw new RuntimeException('Ada row batch yang bukan object.');
        }

        $result = sync_upsert_row($conn, $table, $input, $row);
        $summary['results'][] = $result;

        if (($result['status'] ?? '') === 'inserted') {
            $summary['inserted']++;
        } elseif (($result['status'] ?? '') === 'updated') {
            $summary['updated']++;
        } else {
            $summary['skipped']++;
        }
    }

    mysqli_commit($conn);
    sync_response($summary);
} catch (Throwable $exception) {
    mysqli_rollback($conn);
    sync_fail(
        'Sync batch gagal diproses.',
        500,
        [
            'detail' => $exception->getMessage(),
            'table' => $table,
        ]
    );
}