get_replied($sender); // CASE 1: Pesan dari CS / manusia if (isset($json_data['results']['fromMe']) && $json_data['results']['fromMe'] === true) { $senderreply = $json_data['results']['chatId'] ?? 'Tidak diketahui'; $senderreply = str_replace("@s.whatsapp.net", "", $senderreply); // Skip AI trigger jika pesan mengandung tag AI if (strpos($body, '# CS ~ Asisten') === false) { // Update chat_replied langsung $ResAI->simpan_replied($senderreply, 'Person'); } http_response_code(200); exit; } // CASE 2: Pesan dari user / client if (isset($json_data['results']['fromMe']) && $json_data['results']['fromMe'] === false) { // Cek apakah AI boleh membalas $aiCanReply = true; if ($cekReplied) { // Kalau yang terakhir membalas Asisten AI dan belum timeout → AI skip if ($cekReplied['replied'] === 'Person' && $cekReplied['update_time'] > date('Y-m-d H:i:s')) { $aiCanReply = false; } } if ($aiCanReply) { try { $Respon = $ResAI->respon_chat($body, $sender, $apiKey); if (!empty($Respon['id']) && !empty($Respon['nomor'])) { if (!class_exists('PesanWA')) { file_put_contents(__DIR__ . "/error.log", date('Y-m-d H:i:s') . " Class PesanWA tidak ditemukan!\n", FILE_APPEND); http_response_code(500); exit("Server error: PesanWA class missing"); } $API_WA = new PesanWA(); $send_result = $API_WA->Send_Pesan($Respon['id'], 'sendMessage', array($Respon['nomor']), $Respon['respon'] . "\n\n_# CS ~ Asisten🙏_"); // Update chat_replied → terakhir dibalas AI $ResAI->simpan_replied($sender, 'Asisten AI'); } } catch (Exception $e) { file_put_contents(__DIR__ . "/error.log", date('Y-m-d H:i:s') . " Exception ResponAI / Send_Pesan: " . $e->getMessage() . "\n", FILE_APPEND); http_response_code(500); exit("Server error: gagal proses AI"); } } http_response_code(200); exit; } } else { http_response_code(400); echo "Data tidak valid atau bukan pesan yang diinginkan."; exit; } } catch (Throwable $t) { file_put_contents(__DIR__ . "/error.log", date('Y-m-d H:i:s') . " Fatal error index: " . $t->getMessage() . "\n", FILE_APPEND); http_response_code(500); echo "Server error: " . $t->getMessage(); exit; }