<?php 
include "/www/wwwroot/bilspro/config/connect.php";

// Ambil data dari tabel setting_mikrotik
$stmt = $pdo->prepare("SELECT id, pppa, id_data_server FROM setting_mikrotik WHERE pppa != '' AND id IN (12,73)");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Menyimpan bagian CASE dan nilai parameter binding
$caseParts = [];
$whereTuples = [];
$bindValues = [];

foreach ($rows as $rowIndex => $row) {
    $id_setting = $row['id'];
    $id_data_server = $row['id_data_server'];
    $pppa = rtrim($row['pppa'], '|');
    $entries = explode('|', $pppa);

    foreach ($entries as $entryIndex => $entry) {
        $parts = explode('_', $entry);
        if (count($parts) !== 2) continue;

        list($akun, $ip_address) = $parts;

        // Buat key unik agar tidak tabrakan
        $key = $rowIndex . '_' . $entryIndex;

        // Tambahkan ke bagian CASE
        $caseParts[] = "WHEN akun = :akun_$key AND id_data_server = :server_$key THEN :setting_$key";

        // Tambahkan ke bagian WHERE IN
        $whereTuples[] = "(:akun_$key, :server_$key)";

        // Bind parameter
        $bindValues[":akun_$key"] = $akun;
        $bindValues[":server_$key"] = $id_data_server;
        $bindValues[":setting_$key"] = $id_setting;
    }
}

echo "<pre>";
echo $sql . "\n";
print_r($bindValues);
echo "</pre>";


if (!empty($caseParts)) {
    $sql = "
        UPDATE pelanggan 
        SET id_setting_mikrotik = CASE 
            " . implode("\n", $caseParts) . "
        END
        WHERE (akun, id_data_server) IN (" . implode(", ", $whereTuples) . ")
    ";

    $stmtUpdate = $pdo->prepare($sql);
    $stmtUpdate->execute($bindValues);

    echo "Update berhasil.";
} else {
    echo "Tidak ada data yang perlu diupdate.";
}
