<?php

// System customized by BUANAdotnet
// Powerby CB
// Whatsapp: 628558828262
// Site: www.buana.net

//if (!defined('WHMCS')) {
//	exit('Access Restricted - Powered by www.buana.net');
//}

use WHMCS\Session;
use Carbon\Carbon;
use WHMCS\Database\Capsule;

require "../../../init.php";
require "suiten_koreksinomor.php";

global $ipvisitor;
$global_module_name = 'SUITEN Whatsapp API';
		
if (!empty( $_SERVER['HTTP_CLIENT_IP'] )) {        
    $ipvisitor = $_SERVER['HTTP_CLIENT_IP'];
}
else {
    if (!empty( $_SERVER['HTTP_X_FORWARDED_FOR'] )) {            
        $ipvisitor = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else {
        if (!empty( $_SERVER['REMOTE_ADDR'] )) {
            $ipvisitor = $_SERVER['REMOTE_ADDR'];
        }
        else {
            $ipvisitor = $_SERVER['HTTP_CF_CONNECTING_IP'];
        }
    }
}

foreach (WHMCS\Database\Capsule::table('s10wa_config')->WHERE('suiten_Nama_Modul', $global_module_name)->get() as $modulwa_config) {
    $apikey = $modulwa_config->suiten_apikey;
	$countrycode = $modulwa_config->suiten_countrycode;
}

if ($apikey == '') {
	logactivity("Invalid S10WAM API call from ".$ipvisitor." (Key not defined)");
    exit("Invalid S10WAM API call (Key not defined)");
} elseif ($_POST['key'] <> $apikey) {
	logactivity("Invalid S10WAM API call from ".$ipvisitor);
    exit("Invalid S10WAM API call");
}

Capsule::connection()->transaction(
	function ($connectionManager)
		{
		global $ipvisitor;
		$KoreksiNomor = suiten_koreksinomor($countrycode,$_POST['to']);	
		$isipesan = $_POST['message'];

		if (($KoreksiNomor <> '') && ($isipesan <> '')) {
			$connectionManager->table('s10wa_sendmsg')->insert(

				[
					's10wa_date' => timeStampWhatsapp(),
					's10wa_wanumber' => $KoreksiNomor,
					's10wa_interval' => (int)4,
					's10wa_message' => $isipesan,
					's10wa_msgtype' => (int)1,
					's10wa_clientid' => (int)0,
					's10wa_clientinfo' => 'API Call from '.$ipvisitor,
					's10wa_status' => (int)0
				]
			);
			logactivity( 'SUITEN_WAMLog: Send Message via API to ' . $KoreksiNomor);
			echo 'queued';

		} else {
			echo 'failed #'.$KoreksiNomor." - ".$isipesan;
			logactivity( 'SUITEN_WAMLog: Invalid Send Message attempt via API from ' . $ipvisitor);
		}

	}
);

?>