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

header('Content-Type: text/html; charset=utf-8'); // pastikan output bisa dibaca oleh Swal

$idServer = intval($_GET['id']);
$stmt = $pdo->prepare("SELECT id, pppa, id_data_server, nama FROM setting_mikrotik WHERE pppa != '' AND id_data_server = :idserver");
$stmt->execute([':idserver' => $idServer]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$caseParts = [];
$whereTuples = [];
$bindValues = [];
$mikrotikCount = [];
$mikrotikNama = [];

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

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

        list($akun, $ip_address) = $parts;
        $key = $rowIndex . '_' . $entryIndex;

        $caseParts[] = "WHEN akun = :akun_$key AND id_data_server = :server_$key THEN :setting_$key";
        $whereTuples[] = "(:akun_$key, :server_$key)";
        $bindValues[":akun_$key"] = $akun;
        $bindValues[":server_$key"] = $id_data_server;
        $bindValues[":setting_$key"] = $id_setting;

        if (!isset($mikrotikCount[$id_setting])) {
            $mikrotikCount[$id_setting] = 0;
        }
        $mikrotikCount[$id_setting]++;
    }
}

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 "<b>✅ Sinkronisasi Berhasil</b><br>";
    foreach ($mikrotikCount as $id_mikrotik => $jumlah) {
        $nama = $mikrotikNama[$id_mikrotik] ?? 'Tidak diketahui';
        echo "<b>$nama</b>: $jumlah akun diperbarui</br>";
    }
} else {
    echo "<b>⚠️ Tidak ada data yang perlu disinkronkan.</b>";
}
