<?php
// Set header balasan sebagai JSON
header('Content-Type: application/json');

// Siapkan array balasan
$response = [
    'status' => 'error',
    'message' => 'Terjadi kesalahan. Silakan coba lagi.'
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 1. AMBIL DATA DARI FORM
    $nama = trim($_POST['nama'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $pesan = trim($_POST['pesan'] ?? '');

    // 2. VALIDASI DASAR
    if (empty($nama) || empty($email) || empty($pesan)) {
        $response['message'] = 'Harap lengkapi semua field yang wajib diisi.';
        echo json_encode($response);
        exit;
    }

    // 3. ATUR KREDENSIAL BOT ANDA (Ganti dengan data Anda)
    $botToken = "8271113469:AAEPF6haxSgtqfnwPXzzYHrniXiBOBXLovQ";
    $chatId = "7819636371";

    // 4. FORMAT PESAN
    $pesan_telegram = "<b>🔔 Pesan Website Baru!</b>\n\n";
    $pesan_telegram .= "<b>Nama:</b> " . htmlspecialchars($nama) . "\n";
    $pesan_telegram .= "<b>Email:</b> " . htmlspecialchars($email) . "\n";
    $pesan_telegram .= "<b>Pesan:</b>\n" . htmlspecialchars($pesan);

    // 5. SIAPKAN API URL DAN DATA
    $apiUrl = "https://api.telegram.org/bot" . $botToken . "/sendMessage";
    $data = [
        'chat_id' => $chatId,
        'text' => $pesan_telegram,
        'parse_mode' => 'HTML'
    ];

    // 6. KIRIM MENGGUNAKAN cURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $api_response_str = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $api_response = json_decode($api_response_str, true);

    // 7. ATUR BALASAN JSON
    if ($http_code == 200 && $api_response['ok'] == true) {
        $response['status'] = 'success';
        $response['message'] = 'Pesan berhasil dikirim! Kami akan segera menghubungi Anda.';
    } else {
        $response['message'] = 'Gagal mengirim pesan ke server. Coba lagi nanti.';
    }

    // 8. KIRIM BALASAN
    echo json_encode($response);
    exit;

} else {
    // Jika diakses langsung
    $response['message'] = 'Metode tidak diizinkan.';
    echo json_encode($response);
    exit;
}
?>
