<?php
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");

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

if (empty($mpwa_api_url_base) || empty($api_key)) {
    die("<h3>Gagal: Konfigurasi Belum Lengkap!</h3>Harap isi URL Endpoint MPWA dan API Key di menu Admin Panel.");
}

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

// ==============================================================
// 2. PROSES PENGIRIMAN
// ==============================================================
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $phone = $conn->real_escape_string($_POST['phone_number']);
    
    // FORMATTING NOMOR TELEPON YANG AMAN UNTUK MPWA
    $phone = preg_replace('/[^0-9]/', '', $phone); 
    if (substr($phone, 0, 1) === '0') $phone = '62' . substr($phone, 1);

    if (isset($_POST['message'])) {
        $raw_message = trim($_POST['message']); 
        // Normalisasi format baris baru (newline) agar tidak merusak JSON/cURL
        $clean_message = preg_replace("/\r\n|\r|\n/", "\n", $raw_message);
        $message_db    = $conn->real_escape_string($clean_message);
    } else {
        $clean_message = '';
        $message_db    = '';
    }
    
    $sender_device = $conn->real_escape_string($_POST['sender_device']);
    $user_id       = $_SESSION['user_id'];

    if (empty($sender_device)) {
        $last_bot = $conn->query("SELECT device_number FROM messages WHERE phone_number = '$phone' AND device_number IS NOT NULL AND device_number != '' ORDER BY created_at DESC LIMIT 1");
        if($last_bot->num_rows > 0){
            $sender_device = $last_bot->fetch_assoc()['device_number'];
        } else {
            $any_bot = $conn->query("SELECT device_number FROM messages WHERE device_number IS NOT NULL AND device_number != '' LIMIT 1");
            $sender_device = ($any_bot->num_rows > 0) ? $any_bot->fetch_assoc()['device_number'] : ''; 
        }
    }

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

        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, ['webm', 'mp3', 'ogg', 'wav', 'm4a'])) $msg_type = 'audio';
            elseif (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() . '_' . rand(100, 999) . '.' . $file_ext;
            $upload_path   = 'uploads/' . $new_file_name;

            if (move_uploaded_file($tmp_name, $upload_path)) {
                $file_url_db     = $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;
            }
        }

        $conn->query("INSERT INTO messages (device_number, phone_number, message_text, file_url, message_type, type, user_id) 
                      VALUES ('$sender_device', '$phone', '$message_db', '$file_url_db', '$msg_type', 'out', '$user_id')");

        $conn->query("UPDATE contacts SET status = 'open' WHERE phone_number = '$phone'");

        // ==============================================================
        // 3. LOGIKA REQUEST API (CURL)
        // ==============================================================
        if ($msg_type !== 'text' && !empty($full_public_url)) {
            $data_api = [
                'api_key'    => $api_key,
                'sender'     => $sender_device,
                'number'     => $phone,
                'url'        => $full_public_url,
                'media_type' => $msg_type
            ];
            if (!empty($clean_message) && $msg_type !== 'audio') {
                $data_api['caption'] = $clean_message;
            }
            $target_api_url = $api_url_media; 
        } else {
            $data_api = [
                'api_key' => $api_key,
                'sender'  => $sender_device,
                'number'  => $phone,
                'message' => $clean_message 
            ];
            $target_api_url = $api_url_text; 
        }

        // KITA GUNAKAN HTTP_BUILD_QUERY SEBAGAI FORMAT UTAMA (X-WWW-FORM-URLENCODED)
        // MPWA versi tertentu lebih stabil menerima data format formulir daripada JSON.
        $payload = http_build_query($data_api);

        $ch = curl_init($target_api_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded'
        ]);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Mencegah gagal karena isu sertifikat SSL
        
        $response  = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_err  = curl_error($ch);
        curl_close($ch);

        if ($http_code == 200 || $http_code == 201) {
            header("Location: dashboard.php?phone=" . urlencode($phone) . "&tab=open");
            exit;
        } else {
            // DEBUGGING INFORMASI (Agar kita tahu persis di mana masalahnya)
            echo "<div style='font-family: Arial, sans-serif; padding: 20px; background: #ffebee; border-left: 5px solid #ef5350;'>";
            echo "<h3 style='color: #d32f2f; margin-top: 0;'>Gagal Mengirim Pesan</h3>";
            echo "<b>Target Nomor:</b> $phone <br>";
            echo "<b>Sender Device (Nomor Bot):</b> $sender_device <br>";
            echo "<b>Endpoint:</b> $target_api_url <br>";
            echo "<b>HTTP Code:</b> $http_code <br>";
            echo "<b>Data yang dikirim:</b> " . htmlspecialchars($payload) . " <br><br>";
            echo "<b>Respon Server (MPWA):</b> " . htmlspecialchars($response) . " <br>";
            if($curl_err) echo "<b>CURL Error:</b> $curl_err <br>";
            echo "<br><a href='dashboard.php?phone=$phone' style='display:inline-block; padding:10px 20px; background:#ef5350; color:white; text-decoration:none; border-radius:5px;'>Kembali ke Dashboard</a>";
            echo "</div>";
            exit;
        }
    }
}

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