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

$dataFile = 'data.json';

// Cek metode request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); // Method Not Allowed
    echo json_encode([
        'success' => false,
        'message' => 'Hanya metode POST yang diizinkan'
    ]);
    exit;
}

// Validasi input
if (empty($_POST['email'])) {
    http_response_code(400); // Bad Request
    echo json_encode([
        'success' => false,
        'message' => 'Email tidak boleh kosong'
    ]);
    exit;
}

$email = $_POST['email'];
$jumlahResult = isset($_POST['jumlahResult']) ? (int)$_POST['jumlahResult'] : 1;

// Validasi format email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Format email tidak valid'
    ]);
    exit;
}

// Validasi jumlah result
if ($jumlahResult < 1) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Jumlah result minimal 1'
    ]);
    exit;
}

try {
    // Baca file data.json
    if (!file_exists($dataFile)) {
        file_put_contents($dataFile, '[]');
    }
    
    $data = json_decode(file_get_contents($dataFile), true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Error membaca data JSON');
    }

    // Cek apakah email sudah ada
    foreach ($data as $item) {
        if ($item['email'] === $email) {
            http_response_code(409); // Conflict
            echo json_encode([
                'success' => false,
                'message' => 'Email sudah terdaftar'
            ]);
            exit;
        }
    }

    // Tambahkan data baru
    $data[] = [
        'email' => $email,
        'jumlahResult' => $jumlahResult
    ];

    // Simpan ke file
    $result = file_put_contents($dataFile, json_encode($data));
    
    if ($result === false) {
        throw new Exception('Gagal menyimpan data');
    }

    // Response sukses
    http_response_code(201); // Created
    echo json_encode([
        'success' => true,
        'message' => 'Email berhasil ditambahkan'
    ]);

} catch (Exception $e) {
    http_response_code(500); // Internal Server Error
    echo json_encode([
        'success' => false,
        'message' => 'Terjadi kesalahan: ' . $e->getMessage()
    ]);
}
?>