<?php
// Set agar cookie session tidak mati
ini_set('session.cookie_lifetime', 2592000);
ini_set('session.gc_maxlifetime', 2592000);
session_start();

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

$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'], '/'); 
        if ($row['setting_key'] == 'mpwa_api_key') $api_key = $row['setting_value'];
    }
}

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;
}

$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'; 
// ==============================================================

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    $target_number  = $conn->real_escape_string($_POST['target_number']);
    $fwd_text       = isset($_POST['fwd_text']) ? $_POST['fwd_text'] : '';
    $fwd_file       = isset($_POST['fwd_file']) ? $_POST['fwd_file'] : '';
    $fwd_type       = isset($_POST['fwd_type']) ? $_POST['fwd_type'] : 'text';
    $active_phone   = isset($_POST['active_phone']) ? $_POST['active_phone'] : '';
    
    // TANGKAP CATATAN TAMBAHAN DARI CS
    $additional_msg = isset($_POST['additional_msg']) ? trim($_POST['additional_msg']) : '';

    // Ambil Nomor Bot Utama untuk broadcast/forward
    $sender_device = '';
    $res_setting = $conn->query("SELECT setting_value FROM settings WHERE setting_key = 'default_bot_number'");
    if ($res_setting && $res_setting->num_rows > 0) {
        $sender_device = $res_setting->fetch_assoc()['setting_value'];
    }
    if (empty($sender_device)) {
        $last_bot = $conn->query("SELECT device_number FROM messages WHERE device_number IS NOT NULL LIMIT 1");
        $sender_device = ($last_bot->num_rows > 0) ? $last_bot->fetch_assoc()['device_number'] : '628XXXXXXXXX';
    }

    if (!empty($target_number)) {
        
        $full_public_url = '';

        // BENTUK TEKS PENGANTAR (HEADER)
        $header_fwd = "➡️ *[Diteruskan Dari A&S WA CS]*\n";
        if (!empty($additional_msg)) {
            $header_fwd .= "📝 *Catatan:* " . $additional_msg . "\n";
        }
        $header_fwd .= "\n"; // Spasi sebelum pesan asli

        // Jika ada lampiran (File diteruskan)
        if (!empty($fwd_file)) {
            $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
            $base_url = $protocol . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
            $full_public_url = $base_url . '/' . $fwd_file;
            
            $data_api = [
                'api_key'    => $api_key,
                'sender'     => $sender_device,
                'number'     => $target_number,
                'url'        => $full_public_url,
                'media_type' => $fwd_type
            ];
            
            $caption = $header_fwd;
            if (!empty($fwd_text) && $fwd_type !== 'audio') {
                $caption .= "--- *Pesan Asli* ---\n" . $fwd_text;
            }
            $data_api['caption'] = $caption;
            
            $target_api_url = $api_url_media; 

        } else {
            // Jika HANYA Teks
            $pesan_teks = $header_fwd . "--- *Pesan Asli* ---\n" . $fwd_text;
            $data_api = [
                'api_key' => $api_key,
                'sender'  => $sender_device,
                'number'  => $target_number,
                'message' => $pesan_teks
            ];
            $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('Pesan berhasil diteruskan!');
                    window.location.href = 'dashboard.php?phone=" . urlencode($active_phone) . "';
                  </script>";
            exit;
        } else {
            echo "<h3>Gagal Meneruskan Pesan</h3>";
            echo "<b>HTTP Code:</b> $http_code <br>";
            echo "<b>Respon Server:</b> $response <br><br>";
            echo "<a href='dashboard.php?phone=$active_phone'>Kembali ke Chat</a>";
            exit;
        }
    }
}

header("Location: dashboard.php");
exit;
?>