<?php
session_start();

// PENGUNCI HALAMAN
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

// 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 Database Gagal");

// ==============================================================
// AMBIL KONFIGURASI API MPWA DARI DATABASE
// ==============================================================
$mpwa_api_url_base = '';
$api_key           = '';

$res_api = $conn->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('mpwa_api_url', 'mpwa_api_key')");
if ($res_api) {
    while ($row = $res_api->fetch_assoc()) {
        if ($row['setting_key'] == 'mpwa_api_url') $mpwa_api_url_base = rtrim($row['setting_value'], '/'); // Hilangkan '/' di akhir jika ada
        if ($row['setting_key'] == 'mpwa_api_key') $api_key = $row['setting_value'];
    }
}

// Keamanan: Jika belum disetting di Admin Panel
if (empty($mpwa_api_url_base) || empty($api_key)) {
    echo "<script>alert('Gagal: Konfigurasi API MPWA belum lengkap di Admin Panel!'); window.history.back();</script>";
    exit;
}

// Karena user bisa saja menginput URL full (mengandung /send-message) atau URL dasar, kita pisahkan URL dasarnya.
$base_domain = str_replace(['/send-message', '/send-media'], '', $mpwa_api_url_base);

$api_url_text  = $base_domain . '/send-message'; 
$api_url_media = $base_domain . '/send-media'; 
// ==============================================================

// AMBIL NOMOR BOT DARI PENGATURAN ADMIN
$res_setting = $conn->query("SELECT setting_value FROM settings WHERE setting_key = 'default_bot_number'");
$sender_device = ($res_setting && $res_setting->num_rows > 0) ? $res_setting->fetch_assoc()['setting_value'] : '';

if (empty($sender_device)) {
    echo "<script>alert('Gagal: Nomor Bot Utama belum diisi di Pengaturan Admin Panel!'); window.history.back();</script>";
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $group_id = $conn->real_escape_string($_POST['group_id']);
    
    // =========================================================================
    // FILTER TEKS PESAN AGAR ENTER TERBACA BENAR OLEH API WHATSAPP
    // =========================================================================
    if (isset($_POST['message'])) {
        $raw_message = trim($_POST['message']); 
        // Mengubah semua jenis format enter menjadi baris baru murni (\n)
        $clean_message = str_replace(["\r\n", "\r", "\\n", "\\r"], "\n", $raw_message);
        // Escape string hanya jika ingin disimpan ke database (saat ini broadcast tidak masuk ke tabel messages)
        $message_db = $conn->real_escape_string($clean_message);
    } else {
        $clean_message = '';
    }
    // =========================================================================

    if (!empty($group_id)) {
        
        $msg_type = 'text';
        $full_public_url = '';

        // LOGIKA PENANGKAPAN FILE LAMPIRAN BROADCAST
        if (isset($_FILES['media_file']) && $_FILES['media_file']['error'] == UPLOAD_ERR_OK) {
            $tmp_name = $_FILES['media_file']['tmp_name'];
            $file_name = $_FILES['media_file']['name'];
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

            if (in_array($file_ext, ['jpg', 'jpeg', 'png', 'webp'])) {
                $msg_type = 'image';
            } elseif (in_array($file_ext, ['mp4', 'avi', 'mov', '3gp'])) {
                $msg_type = 'video';
            } else {
                $msg_type = 'document';
            }

            $new_file_name = time() . '_grp_' . rand(100, 999) . '.' . $file_ext;
            $upload_path = 'uploads/' . $new_file_name;

            if (move_uploaded_file($tmp_name, $upload_path)) {
                $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
                $base_url = $protocol . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
                $full_public_url = $base_url . '/' . $upload_path;
            }
        }

        // Persiapan Kirim API (Gunakan $clean_message yang belum di-escape SQL)
        if ($msg_type !== 'text' && !empty($full_public_url)) {
            $data_api = [
                'api_key'    => $api_key,
                'sender'     => $sender_device,
                'number'     => $group_id,
                'url'        => $full_public_url,
                'media_type' => $msg_type
            ];
            
            if (!empty($clean_message)) {
                $data_api['caption'] = $clean_message;
            }
            $target_api_url = $api_url_media; 
        } else {
            $data_api = [
                'api_key' => $api_key,
                'sender'  => $sender_device,
                'number'  => $group_id,
                'message' => $clean_message 
            ];
            $target_api_url = $api_url_text; 
        }

        $ch = curl_init($target_api_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data_api));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($http_code == 200 || $http_code == 201) {
            echo "<script>alert('Broadcast Berhasil Dikirim!'); window.history.back();</script>";
            exit;
        } else {
            echo "<h3>Gagal Mengirim Broadcast</h3>";
            echo "<b>Endpoint:</b> $target_api_url <br>";
            echo "<b>HTTP Code:</b> $http_code <br>";
            echo "<b>Respon Server:</b> $response <br><br>";
            echo "<a href='javascript:history.back()'>Kembali</a>";
            exit;
        }
    }
}

// Jika gagal/bukan POST, kembalikan ke halaman sebelumnya
if (isset($_SERVER['HTTP_REFERER'])) {
    header("Location: " . $_SERVER['HTTP_REFERER']);
} else {
    header("Location: dashboard.php");
}
exit;
?>