<?php
// Hentikan blocking session: kita hanya membaca kredensial dari session
session_start(['read_and_close' => true]);

require('routeros_api.class.php');

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, must-revalidate');

// ===== validasi sesi =====
if (!isset($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'not_authenticated']);
    exit;
}

// ===== sanitasi parameter comment =====
$commentRaw = (string) filter_input(INPUT_GET, 'comment', FILTER_UNSAFE_RAW);
$comment = trim($commentRaw);
if ($comment === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'comment_missing']);
    exit;
}

// ===== direktori cache & helper atomic write =====
$cacheDir = __DIR__ . '/cache';
if (!is_dir($cacheDir)) {
    @mkdir($cacheDir, 0755, true);
}

function atomic_write_json(string $path, $data): bool {
    $dir = dirname($path);
    if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
        return false;
    }
    $tmp = $path . '.tmp';
    $json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    if ($json === false) return false;
    $fp = @fopen($tmp, 'c');
    if (!$fp) return false;
    $ok = false;
    if (flock($fp, LOCK_EX)) {
        ftruncate($fp, 0);
        rewind($fp);
        $written = fwrite($fp, $json);
        fflush($fp);
        flock($fp, LOCK_UN);
        fclose($fp);
        if ($written !== false && @rename($tmp, $path)) {
            @chmod($path, 0644);
            $ok = true;
        } else {
            @unlink($tmp);
            $ok = false;
        }
    } else {
        fclose($fp);
        @unlink($tmp);
        $ok = false;
    }
    return $ok;
}

// nama file progress (tulis dua file: normal dan _all untuk comment_all.php)
$mikrotikIp = preg_replace('/[^0-9\.]/', '', $_SESSION['ip']);
$progressFile1 = $cacheDir . '/progress_' . ($mikrotikIp ?: 'unknown') . '.json';
$progressFileAll = $cacheDir . '/progress_' . ($mikrotikIp ?: 'unknown') . '_all.json';

// reset progress awal (0%)
@atomic_write_json($progressFile1, ['percent' => 0]);
@atomic_write_json($progressFileAll, ['percent' => 0]);

// ===== koneksi ke Mikrotik =====
$API = new RouterosAPI();
$API->debug = false;
$API->connect_timeout = 4;
$API->read_timeout = 7;

$connected = false;
try {
    if (!$API->connect($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'connect_failed']);
        exit;
    }
    $connected = true;

    // ambil user berdasarkan comment (filter)
    // gunakan write/parseResponse untuk konsistensi
    $API->write('/ip/hotspot/user/print', false);
    // pastikan tidak ada newline di filter
    $safeComment = str_replace(["\r", "\n"], '', $comment);
    $API->write('?comment=' . $safeComment);
    $users = $API->parseResponse($API->read(false));
    if (!is_array($users)) $users = [];

    $total = count($users);
    if ($total === 0) {
        // tidak ada user ditemukan
        // pastikan progress diset 100 untuk UI agar tidak menggantung
        @atomic_write_json($progressFile1, ['percent' => 100]);
        @atomic_write_json($progressFileAll, ['percent' => 100]);

        echo json_encode(['success' => false, 'error' => 'no_user_found', 'deleted' => 0, 'total' => 0]);
        exit;
    }

    // proses hapus satu per satu, update progress secara atomic
    $deleted = 0;
    foreach ($users as $u) {
        if (!isset($u['.id'])) continue;
        $id = $u['.id'];

        try {
            $API->comm('/ip/hotspot/user/remove', ['.id' => $id]);
        } catch (Exception $e) {
            // skip jika error pada satu user
            continue;
        }

        $deleted++;
        $percent = (int) floor(($deleted / $total) * 100);

        // tulis progress ke kedua file (agar comment.php dan comment_all.php dapat membaca)
        @atomic_write_json($progressFile1, ['percent' => $percent]);
        @atomic_write_json($progressFileAll, ['percent' => $percent]);

        // jeda kecil supaya filesystem/Router tidak terbebani; kurangi kalau ingin lebih cepat
        usleep(50000); // 0.05s
    }

    // pastikan progress 100% di akhir
    @atomic_write_json($progressFile1, ['percent' => 100]);
    @atomic_write_json($progressFileAll, ['percent' => 100]);

    // disconnect dari Mikrotik
    $API->disconnect();
    $connected = false;

    // hapus cache terkait agar UI menampilkan data terbaru
    $cacheFiles = [
        $cacheDir . '/cache_comment_' . ($mikrotikIp ?: 'unknown') . '.json',
        $cacheDir . '/cache_comment_' . ($mikrotikIp ?: 'unknown') . '_all.json',
        $cacheDir . '/cache_users_' . ($mikrotikIp ?: 'unknown') . '.json'
    ];
    foreach ($cacheFiles as $f) {
        if (file_exists($f)) @unlink($f);
    }

    echo json_encode([
        'success' => true,
        'deleted' => $deleted,
        'total' => $total
    ]);
    exit;

} catch (Exception $e) {
    // error tak terduga
    if ($connected && $API->connected) $API->disconnect();
    http_response_code(500);
    // set progress to 100 agar UI tidak menunggu terlalu lama
    @atomic_write_json($progressFile1, ['percent' => 100]);
    @atomic_write_json($progressFileAll, ['percent' => 100]);
    echo json_encode(['success' => false, 'error' => 'exception', 'message' => $e->getMessage()]);
    exit;
}
?>