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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validasi input email
    if (!isset($_POST['email']) || empty($_POST['email'])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Email tidak boleh kosong']);
        exit;
    }

    $emailToDelete = $_POST['email'];
    $dataFile = 'data.json';

    // Baca data dari file JSON
    if (!file_exists($dataFile)) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'File data tidak ditemukan']);
        exit;
    }

    $data = json_decode(file_get_contents($dataFile), true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error membaca data JSON']);
        exit;
    }

    // Cari dan hapus email
    $initialCount = count($data);
    $data = array_filter($data, function($item) use ($emailToDelete) {
        return $item['email'] !== $emailToDelete;
    });

    // Jika jumlah data tidak berubah, berarti email tidak ditemukan
    if (count($data) === $initialCount) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Email tidak ditemukan']);
        exit;
    }

    // Simpan data yang sudah dihapus
    if (file_put_contents($dataFile, json_encode(array_values($data))) === false) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Gagal menyimpan data']);
        exit;
    }

    // Response sukses
    echo json_encode(['success' => true, 'message' => 'Email berhasil dihapus']);
} else {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method tidak diizinkan']);
}
?>