<?php
require_once("/home/fundbridge/crons.ballng.com/db.php");

function sendSMS($numbers,$message){
    $res = false;
    try {
        $phonenumbers = array_map(function ($numb) {return preg_replace('/^0/', "234", $numb); }, $numbers);
        $curl = curl_init();
        $data = array("to" => implode(",",$phonenumbers),"sender" => "Ball NG","message"=>$message,"type" => "0","routing" => "3","token" => "JvND51A75gvpMXEuOiaFntAlphJir8mLUInEhamNA0I8Kao083");
        curl_setopt_array($curl, array(CURLOPT_URL => "https://app.smartsmssolutions.com/io/api/client/v1/sms/",CURLOPT_RETURNTRANSFER => true,CURLOPT_ENCODING => "",CURLOPT_MAXREDIRS => 10,CURLOPT_TIMEOUT => 0,CURLOPT_FOLLOWLOCATION => true,CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,CURLOPT_CUSTOMREQUEST => "POST",CURLOPT_POSTFIELDS => $data));
        $response = curl_exec($curl);
        curl_close($curl);
        $resp = json_decode($response, true);
        if(in_array("code", array_keys($resp)) && intval($resp["code"]) == 1000){
            $res = floatval($resp["units_used"]);
        }else if(in_array("code", array_keys($resp)) && intval($resp["code"]) == 1002 && $resp["error"] == true){
            $res = $resp["comment"];
        }
    } catch (NumberParseException $e) {
        
    }
    return $res;
}

$sms = mysqli_query($conn, "select * from sms where status = 1");

$rcp_types = ["","Users","Others","","","","","",""];
$rcp_tables = ["","users","","","","","","",""];
$rcp_userID = ["","uid","","","","","","",""];
$rcp_status = ["1","1","","","","","","",""];
while($sm = mysqli_fetch_assoc($sms)){
    $rcp = intval($sm['recipients']);
    $numbers = array();
    
    
    $table = $rcp_tables[$rcp];
    $uid = $rcp_userID[$rcp];
    $status = $rcp_status[$rcp];
    
    $rcps = $rcp == 0 ? [] : json_decode($sm["numbers"], true);
    if($table != ""){
        if(empty($rcps)){
            //all recipients
            $numbers = $conn->query("select phone from $table where phone != '' and status = '$status'")->fetch_all(MYSQLI_ASSOC);
            if($numbers){ $numbers = array_map(function($number){ return $number['phone']; }, $numbers); }
        }else{
            foreach($rcps as $rc){
                if($rc != ""){
                    $check_rc = mysqli_query($conn, "select phone from $table where phone != '' and $uid = '$rc' and status = '$status'");
                    if(mysqli_num_rows($check_rc)){
                        $numbers[] = mysqli_fetch_assoc($check_rc)["phone"] ;
                    }
                }
            }
        }
    }else{
        if($rcp == 0){
            // send to all
            $numbers = $conn->query("select phone from users where phone != '' and status = '1'")->fetch_all(MYSQLI_ASSOC);
            if($numbers){ $numbers = array_map(function($number){ return $number['phone']; }, $numbers); }
        }else if($rcp == 3){
            // send to users without loans
            $numbers = $conn->query("select phone from users where phone != '' and status = '1' and coalesce((select count(id) from loans where uid = users.uid limit 1),0) = 0")->fetch_all(MYSQLI_ASSOC);
            if($numbers){ $numbers = array_map(function($number){ return $number['phone']; }, $numbers); }
        }else if($rcp == 4){
            // send to users with loans
            $numbers = $conn->query("select phone from users where phone != '' and status = '1' and coalesce((select count(id) from loans where uid = users.uid limit 1),0) > 0")->fetch_all(MYSQLI_ASSOC);
            if($numbers){ $numbers = array_map(function($number){ return $number['phone']; }, $numbers); }
        }else if($rcp == 5){
            // send to verified users
            $numbers = $conn->query("select phone from users where phone != '' and status = '1' and ( coalesce((select count(id) from verifications where uid = users.uid and bvn_status = 1 and status = 1 limit 1),0) = 1 )")->fetch_all(MYSQLI_ASSOC);
            if($numbers){ $numbers = array_map(function($number){ return $number['phone']; }, $numbers); }
        }else if($rcp == 6){
            // send to failed verified users
            $numbers = $conn->query("select phone from users where phone != '' and status = '1' and ( coalesce((select count(id) from verifications where uid = users.uid and (bvn_status = 2 or status = 2) limit 1),0) = 1 )")->fetch_all(MYSQLI_ASSOC);
            if($numbers){ $numbers = array_map(function($number){ return $number['phone']; }, $numbers); }
        }else if($rcp == 7){
            // send to pending verified users
            $numbers = $conn->query("select phone from users where phone != '' and status = '1' and ( coalesce((select count(id) from verifications where uid = users.uid limit 1),0) = 0 )")->fetch_all(MYSQLI_ASSOC);
            if($numbers){ $numbers = array_map(function($number){ return $number['phone']; }, $numbers); }
        }else if($rcp == 8){
            // send to web users only
            $numbers = $conn->query("select phone from users where phone != '' and status = '1' and ( coalesce((select count(id) from devices where uid = users.uid and type = 2 limit 1),0) != 0 ) and ( coalesce((select count(id) from devices where uid = users.uid and type != 2 limit 1),0) = 0 )")->fetch_all(MYSQLI_ASSOC);
            if($numbers){ $numbers = array_map(function($number){ return $number['phone']; }, $numbers); }
        }else{
            //others
            $numbers = $rcps;
        }
    }
    $cost = 0;
    $reason = "";
    $ret = sendSMS($numbers,$sm['message']);
    if(gettype($ret) != "string" && $ret){
        $status = 2;
        $cost = $ret;
    }else{
        $status = 4;
        $reason = $ret;
    }
    
    mysqli_query($conn, "update sms set status = $status, cost = $cost,comment='$reason' where id = '".$sm['id']."' limit 1");
}
$conn->close();
?>