<?php
// include '../../manage/function.php';
$message=$_POST['message'];
if($_POST['delivery_type']=='individual')
{
    individual_message();//Call Function
}
else
{
    // Send in Buk
    echo bulk_message();
}


function bulk_message()
{
    include '../../manage/function.php';
    include '../../manage/connection.php';
    // echo http_build_query(array('name'=>'Abdallah nas'));
    $phone='';
    $getTeachers=$connect->query("SELECT * FROM teacher");
    $cnt=1;
    if($_POST['send_option']=='selected')
    {
        while($teacher=$getTeachers->fetch_assoc())
        {
            if(isset($_POST['tch_'.$teacher['phone']]))
            {
                if($cnt!=1)
                {
                    $phone.=','.$teacher['phone'];
                }
                else
                {
                    $phone.=$teacher['phone'];
                }
        
                $cnt++;
            }
            
        }
    }
    else
    {
        while($teacher=$getTeachers->fetch_assoc())
        {
            if($cnt!=1)
            {
                $phone.=','.$teacher['phone'];
            }
            else
            {
                $phone.=$teacher['phone'];
            }
    
            $cnt++;
            
        }
    }
    $post_vals==array('username'=>$kudi_username, 
    'password'=>$kudi_password, 
    'message'=>str_replace('@teacher', $teacher['fullname'], $message),
    'sender'=>$kudi_sender, 
    'mobiles'=>$phone);
    // echo $phone;

    // $url = "http://localhost/aziza/admin/test_post.php?".http_build_query($post_vals);
    $url = "https://account.kudisms.net/api/?username=$kudi_username&password=$kudi_password&message=".$_POST['message']."&sender=$kudi_sender&mobiles=".$phone;
                    
    
    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data
     

    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POST,1);//1 for post
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_vals);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_VERBOSE,true); 
    //So that curl_exec returns the contents of the cURL; rather than echoing it
    // curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
    // curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    //     "Authorization: Bearer \$key_ar",
    //     "Cache-Control: no-cache",
    //     'Content-Type: application/json',
    //     ));
    //execute post
    $result = curl_exec($ch);
    $decodedRes = json_decode($result, true);
    if(strtolower($decodedRes['status'])=='ok')
    {
        return $decodedRes['count'].' Message(s) Sent';
    }
    else
    {
        return 'Could Not Send Message';
    }
}

function individual_message()
{
    include '../../manage/function.php';
    include '../../manage/connection.php';
    // Get Parents
    // global $kudi_username,$kudi_password,$message,$kudi_sender;
    $request_contents=array();
    $urls = array();

    // echo json_encode($_POST);
    
    $getTeachers=$connect->query("SELECT * FROM teacher");
    if($_POST['send_option']=='selected')
    {
        while($teacher=$getTeachers->fetch_assoc())
        {
            if(isset($_POST['tch_'.$teacher['phone']]))
            {
                $post_vals=array('username'=>$kudi_username, 
                'password'=>$kudi_password, 
                'message'=>str_replace('@parent', $teacher['fullname'], $message),
                'sender'=>$kudi_sender, 
                'mobiles'=>$teacher['phone']);
                array_push($request_contents, $post_vals);
                // Define url and infor for each fetched parent
                        // echo $urls[]='https://account.kudisms.net/api/?'.http_build_query('$post_vals');
                        $urls[]="https://account.kudisms.net/api/?username=$kudi_username&password=$kudi_password&message=".str_replace('@parent', $teacher['parent_name'], $_POST['message'])."&sender=$kudi_sender&mobiles=".$teacher['phone'];
                        // $urls[]='http://localhost/aziza/admin/test_post.php?'.http_build_query($post_vals);
                        // echo '<a href="'.$urls[0].'">Hello</a>';
            }
    
        }
    }
    else
    {
        while($teacher=$getTeachers->fetch_assoc())
        {
            $post_vals=array('username'=>$kudi_username, 
            'password'=>$kudi_password, 
            'message'=>str_replace('@parent', $teacher['parent_name'], $message),
            'sender'=>$kudi_sender, 
            'mobiles'=>$teacher['phone']);
            array_push($request_contents, $post_vals);
            // Define url and infor for each fetched parent
                    // echo $urls[]='https://account.kudisms.net/api/?'.http_build_query('$post_vals');
                    $urls[]="https://account.kudisms.net/api/?username=$kudi_username&password=$kudi_password&message=".str_replace('@parent', $teacher['parent_name'], $_POST['message'])."&sender=$kudi_sender&mobiles=".$teacher['phone'];
                    // $urls[]='http://localhost/aziza/admin/test_post.php?'.http_build_query($post_vals);
                    // echo '<a href="'.$urls[0].'">Hello</a>';
        }
    }
    

    //array of cURL handles
    $chs = array();
    //create the array of cURL handles and add to a multi_curl
    $mh = curl_multi_init();
    foreach ($urls as $key => $url) {
        // echo json_encode($request_contents);
        $chs[$key] = curl_init($url);
        curl_setopt($chs[$key], CURLOPT_RETURNTRANSFER, true);
        curl_setopt($chs[$key], CURLOPT_URL, $url);
        // curl_setopt($chs[$key], CURLOPT_POST, false);
        // curl_setopt($chs[$key], CURLOPT_POSTFIELDS, $request_contents[$key]);

        curl_multi_add_handle($mh, $chs[$key]);
    }

    //running the requests
    $running = null;
    do {
    curl_multi_exec($mh, $running);
    } while ($running);

    $sent_count=0;
    //getting the responses
    foreach(array_keys($chs) as $key){
        $error = curl_error($chs[$key]);
        $last_effective_URL = curl_getinfo($chs[$key], CURLINFO_EFFECTIVE_URL);
        $time = curl_getinfo($chs[$key], CURLINFO_TOTAL_TIME);
        $response = curl_multi_getcontent($chs[$key]);  // get results
        if (!empty($error)) {
        echo "The request $key return a error: $error" . "\n";
        }
        else {
            // echo $response;
            $decodedRes=json_decode($response, true);
            if(strtolower($decodedRes['status'])=='ok')
            {
                $sent_count+=1;
            }
        // echo "The request to '$last_effective_URL' returned '$response' in $time seconds." . "\n";
        }
        curl_multi_remove_handle($mh, $chs[$key]);
    }

    echo $sent_count.' Messages Sent';
    // close current handler
    curl_multi_close($mh);
}
?>