<?php
// Disable caching
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
header('Content-Type: application/json');

session_start(['read_and_close' => true]);

// ===== CEK LOGIN =====
if (!isset($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Unauthorized: Session tidak valid']);
    exit;
}

// ===== HELPERS =====
function read_json_file_lock(string $path): array {
    if (!file_exists($path)) return [];
    $fp = @fopen($path, 'r');
    if (!$fp) return [];
    $contents = '';
    if (flock($fp, LOCK_SH)) {
        $contents = stream_get_contents($fp);
        flock($fp, LOCK_UN);
    }
    fclose($fp);
    $data = json_decode($contents, true);
    return is_array($data) ? $data : [];
}

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_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    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;
}

// ===== AMBIL PARAMETER =====
$comment = isset($_GET['comment']) ? trim($_GET['comment']) : '';
if (empty($comment)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Comment parameter required']);
    exit;
}

// ===== SETUP FILE PATHS =====
$cacheDir = __DIR__ . '/cache';
if (!is_dir($cacheDir)) {
    @mkdir($cacheDir, 0755, true);
}

$mikrotikIpRaw = $_SESSION['ip'] ?? '';
$mikrotikIp = preg_replace('/[^0-9\.]/', '', $mikrotikIpRaw);
$dedicatedFile = $cacheDir . '/dedicated_comments_' . ($mikrotikIp ?: 'unknown') . '.json';

try {
    // Cek apakah file exists
    if (!file_exists($dedicatedFile)) {
        echo json_encode(['success' => true, 'message' => 'File tidak ada, dianggap sudah dihapus']);
        exit;
    }

    $data = read_json_file_lock($dedicatedFile);
    
    // Cek apakah comment exists
    if (!isset($data['comments'][$comment])) {
        echo json_encode(['success' => true, 'message' => 'Comment sudah dihapus sebelumnya']);
        exit;
    }

    // Hapus comment
    unset($data['comments'][$comment]);
    
    // Simpan kembali
    if (!atomic_write_json($dedicatedFile, $data)) {
        throw new Exception('Gagal menyimpan file (permission issue)');
    }

    echo json_encode(['success' => true, 'message' => 'Comment berhasil dihapus dari riwayat']);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Exception: ' . $e->getMessage()]);
}
?>