<?php
// === PASANG CCTV WEBHOOK ===
$raw_input = file_get_contents('php://input');
if (!empty($raw_input)) {
    file_put_contents('log_mpwa.txt', date('Y-m-d H:i:s') . " - " . $raw_input . "\n\n", FILE_APPEND);
}
// ===========================

// Set zona waktu agar pembacaan jam akurat (WIB)
date_default_timezone_set('Asia/Jakarta');

// ==============================================================
// 1. KONFIGURASI ONESIGNAL (Wajib Diisi!)
// ==============================================================
define('ONESIGNAL_APP_ID', 'ff9c1ab6-72f6-4358-8d61-ea010813d722');
define('ONESIGNAL_REST_KEY', 'os_v2_app_76obvnts6zbvrdlb5iaqqe6xeltu6mdrmieuwkurmyta7pljafa4ms666nxf4l5xanetj4jybnn2wxuyrdvt4hkryzhwejk2q3brjaq');

// ==============================================================
// 2. KONFIGURASI DATABASE
// ==============================================================
$host = 'localhost';
$user = 'majapahi_omnich';
$pass = 'A1b2c3d4.,@';
$db   = 'majapahi_omnich';

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) die("Koneksi gagal");

// ==============================================================
// 3. MENERIMA DATA DARI BOT NODE.JS
// ==============================================================
$jsonData = file_get_contents('php://input');
$data = json_decode($jsonData, true);

if ($data && isset($data['from']) && isset($data['device'])) {
    
    $device  = $conn->real_escape_string($data['device']);
    $sender  = $conn->real_escape_string($data['from']);
    $name    = isset($data['name']) ? $conn->real_escape_string($data['name']) : 'Pelanggan';
    
    // ==============================================================
    // 🛡️ FILTER KEAMANAN (HANYA GRUP)
    // ==============================================================
    // Blokir jika dari Grup WA
    if (strpos($sender, '-') !== false || strpos($sender, '@g.us') !== false || (isset($data['isGroup']) && $data['isGroup'] == true) || (isset($data['is_group']) && $data['is_group'] == true)) {
        http_response_code(200); 
        echo "Pesan dari Grup WA Diabaikan.";
        exit; 
    }

    // Normalisasi nomor (bersihkan karakter non-angka dan paksakan awalan 62 HANYA jika dimulai dari 0)
    $sender = preg_replace('/[^0-9]/', '', $sender);
    if (substr($sender, 0, 1) === '0') $sender = '62' . substr($sender, 1);
    
    // Blokir jika nomor terlalu pendek
    if (strlen($sender) < 10) {
        http_response_code(200); 
        echo "Nomor terlalu pendek/invalid diabaikan.";
        exit;
    }
    // ==============================================================

    // Menangkap teks pesan atau caption
    $message = isset($data['message']) ? $data['message'] : '';
    if (empty($message) && isset($data['media']['caption']) && !empty($data['media']['caption'])) {
        $message = $data['media']['caption'];
    }
    
    $pesan_untuk_notif = $message; 
    $message = $conn->real_escape_string($message);
    
    $file_url = '';
    $msg_type = 'text';
    $ext_file = ''; 

    // --- DETEKSI FILE MEDIA ---
    if (isset($data['media']['stream']['data']) && is_array($data['media']['stream']['data'])) {
        $buffer_array = $data['media']['stream']['data'];
        $file_content = pack('C*', ...$buffer_array);

        if (!empty($file_content)) {
            $mimetype = isset($data['media']['mimetype']) ? $data['media']['mimetype'] : 'image/jpeg';
            $ext = 'jpg';
            
            if (strpos($mimetype, 'audio') !== false || strpos($mimetype, 'ogg') !== false) {
                $ext = 'ogg'; $msg_type = 'document'; 
            } elseif (strpos($mimetype, 'video') !== false) { 
                $ext = 'mp4'; $msg_type = 'video'; 
            } elseif (strpos($mimetype, 'pdf') !== false) { 
                $ext = 'pdf'; $msg_type = 'document'; 
            } elseif (strpos($mimetype, 'png') !== false) { 
                $ext = 'png'; $msg_type = 'image'; 
            } elseif (strpos($mimetype, 'webp') !== false) { 
                $ext = 'webp'; $msg_type = 'image'; 
            } else { 
                $msg_type = 'image'; 
            }

            $ext_file = $ext; 
            $filename = time() . '_' . rand(100, 999) . '.' . $ext;
            $filepath = 'uploads/' . $filename;
            
            if(file_put_contents($filepath, $file_content)) {
                $file_url = $filepath;
            }
        }
    }

    // ==============================================================
    // 💾 SIMPAN DATA KE DATABASE
    // ==============================================================
    $sql_contact = "INSERT INTO contacts (phone_number, name, status) 
                    VALUES ('$sender', '$name', 'open') 
                    ON DUPLICATE KEY UPDATE status='open'";
    $conn->query($sql_contact);

    $sql_message = "INSERT INTO messages (device_number, phone_number, message_text, file_url, message_type, type, is_read) 
                    VALUES ('$device', '$sender', '$message', '$file_url', '$msg_type', 'in', 0)";
    $conn->query($sql_message);
    
    // ==============================================================
    // 4. KIRIM PUSH NOTIFICATION KE APK CS (ONESIGNAL)
    // ==============================================================
    if ($ext_file == 'ogg' || $ext_file == 'mp3') {
        $isi_notif = "🎤 Mengirim Pesan Suara";
    } elseif ($msg_type == 'image') {
        $isi_notif = "📷 Mengirim Gambar";
    } elseif ($msg_type == 'video') {
        $isi_notif = "🎥 Mengirim Video";
    } elseif ($msg_type == 'document') {
        $isi_notif = "📄 Mengirim Dokumen";
    } else {
        $isi_notif = $pesan_untuk_notif;
    }
    
    $fields = array(
        'app_id' => ONESIGNAL_APP_ID,
        'included_segments' => array('All'),
        'headings' => array("en" => "Pesan Baru Masuk!"),
        'contents' => array("en" => $isi_notif),
        'priority' => 10,
        'android_sound' => 'notification' 
    );

    $fields_json = json_encode($fields);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8',
        'Authorization: Basic ' . ONESIGNAL_REST_KEY
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_json);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    
    $response = curl_exec($ch);
    curl_close($ch);

    http_response_code(200);
    echo "Pesan masuk & Notifikasi berhasil diproses.";
} else {
    http_response_code(400);
    echo "Data diabaikan";
}
?>