<?php

function sendmessage($no_faktur_penjualan)
{
    // require_once ('vendor/autoload.php'); // if you use Composer
    require_once('whatsapp-php-sdk-main/ultramsg.class.php'); // if you download ultramsg.class.php

    // awal koneksi
    // untuk koneksi berikut silahkan diubah sesuai kebutuhan
 

    // Check connection
    if (mysqli_connect_errno()) {
        echo "Koneksi database gagal : " . mysqli_connect_error();
    }

    // mengambil nama file pdf
    $data = $this->db->query("SELECT * FROM outbox WHERE nobukti=$no_faktur_penjualan");
    $d = $data->row_array();
    // akhir koneksi

    $ultramsg_token = "hyzcgga1ymdyp8d3"; // ubah sesuai token milik anda
    $instance_id = "instance4654"; // ubah sesuai instance id milik anda
    $client = new UltraMsg\WhatsAppApi($ultramsg_token, $instance_id);

    $to = "082313191685"; // nomor WA tujuan

    // pesan (text) bisa disesuaikan
    $body = "*TERIMA KASIH*
〰〰〰〰〰〰〰〰〰〰〰
Struk Pembelian";
    $api = $client->sendChatMessage($to, $body);

    $namafile = $d['wa_file']; // nama file pdf
    $path = "/storage/emulated/0/Download/" . $namafile; // sesuaikan tempat download anda
    $data = file_get_contents($path);
    // you can convert File to Base64  using ultramsg UI
    // https://user.ultramsg.com/app/base64/base64.php 

    //Encodes data base64
    $img_base64 =  base64_encode($data);
    //urlencode — URL-encodes string  
    $img_base64 = urlencode($img_base64);

    // awal proses pengiriman
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.ultramsg.com/$instance_id/messages/document",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "token=$ultramsg_token&to=$to&document=$img_base64&filename=$namafile",
        CURLOPT_HTTPHEADER => array(
            "content-type: application/x-www-form-urlencoded"
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
        echo $response;
    }
    // akhir proses pengiriman
}
