<?php
//require "wa_api";
function optIn($number)
{
    global $conn;
    if (!empty($number)) {
        $data = '{"numbers":["' . $number . '"]}';
        $url = "https://www.mobily.ws/wa/v1/provision/optin/";
        $header = array('content-type: application/json', 'Authorization: Bearer rdxG7GoQxQ.eMIgSDrG4J.JR2WP97FGE');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        return curl_exec($ch);
    }
}
function optOut($number)
{
    global $conn;
    if (!empty($number)) {
        $data = '{"numbers":["' . $number . '"]}';
        $url = "https://www.mobily.ws/wa/v1/provision/optout/";
        $header = array('content-type: application/json', 'Authorization: Bearer rdxG7GoQxQ.eMIgSDrG4J.JR2WP97FGE');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        return curl_exec($ch);
    }
}
function uploadFile($type, $ext)
{
    global $conn;
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES[$type]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    if ($_FILES[$type]["size"] > 10000000)
        $uploadOk = 0;
    if (!empty($ext))
        if (!in_array($imageFileType, $ext))
            $uploadOk = 0;
    if ($uploadOk != 0) {
        $newfilename = round(microtime(true)) . '.' . $imageFileType;
        if (move_uploaded_file($_FILES[$type]["tmp_name"], $target_dir . $newfilename)) {
            return $target_dir . $newfilename;
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}
function base_url($atRoot = FALSE, $atCore = FALSE, $parse = FALSE)
{
    global $conn;
    if (isset($_SERVER['HTTP_HOST'])) {
        $http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
        $hostname = $_SERVER['HTTP_HOST'];
        $dir =  str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);

        $core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);
        $core = $core[0];

        $tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s");
        $end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);
        $base_url = sprintf($tmplt, $http, $hostname, $end);
    } else $base_url = 'http://localhost/';

    if ($parse) {
        $base_url = parse_url($base_url);
        if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';
    }

    return $base_url;
}
function send($to, $msg, $type = "text", $lat = '', $lng = '')
{
    global $conn;
    $bearerToken = "";
    $res = (new whatsApp($bearerToken))->text($to, $msg);


    /*
    if (!empty($to) && !empty($msg)) {
        if ($type == "text")
            $data = '{  "to": ["' . $to . '"],"message": {"type": "text","text": "' . $msg . '"}}'; //send msg
        if (in_array($type, array("image", "video", "audio", "document")))
            $data = '{  "to": ["' . $to . '"],"message": {"type": "' . $type . '",  "url": "' . $msg . '","caption": ""}}'; //send msg
        if (in_array($type, array("image", "video", "audio", "document")))
            $data = '{  "to": ["' . $to . '"],"message": {"type": "' . $type . '",  "url": "' . $msg . '","caption": ""}}'; //send msg
    } elseif (!empty($to) && !empty($lat) && !empty($lng)) {
        $data = '{  "to": ["' . $to . '"],"message": {"type": "location","lat": ' . $lat . ',"lng": ' . $lng . ',"name": "","address": ""}}'; //send msg
    } else {
        return false;
    }

    */
    $data = stripslashes($data);
    $url = "https://www.mobily.ws/wa/v1/messages/";
    $header = array('content-type: application/json', 'Authorization: Bearer rdxG7GoQxQ.eMIgSDrG4J.JR2WP97FGE');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);

    $body = explode("\n", $response);
    if (!empty($body[8]))
        $data = $body[8];
    elseif (!empty($body[6]))
        $data = $body[6];
    $json = json_decode($data, true);
    if (!empty($json["statuses"])) {
        foreach ($json["statuses"] as $jsonData) {
            if ($jsonData["status"] == "success") {
                $msg_id = $jsonData["message_id"];
                $to = str_replace("+", "", $jsonData["recipient"]);
                mysqli_query($conn, "INSERT INTO `msg_archive` ( `to`,`from`, `body`, `message_id`, `msg_type`, `type`,`date`) VALUES ('" . mysqli_real_escape_string($conn, $to) . "','966580662676','" . mysqli_real_escape_string($conn, $msg) . "','" . mysqli_real_escape_string($conn, $msg_id) . "','" . $type . "','2','" . time() . "');");
            }
        }
    }
    return  $data;
}
