<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
/* require_once "labClass.php";
$con = new labClass();
 
$dr=0;
$drn=0;
$totaldbts=0;
$status="NOT PAID";
if ($_POST['msg']) { 
    $message = $_POST['msg'];
//////
 //Step 1: Authorize and get the token
$url = 'https://apis.onfonmedia.co.ke/v1/authorization';

$data = [
    'apiUsername' => 'rombostar',
    'apiPassword' => 'czu3YnOb5j4tfR08LsEmUIhvkP1BZS9qdoXlCgN6rwax7G2e'
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$response = curl_exec($ch);
curl_close($ch);

// Step 2: Decode the JSON response
$responseData = json_decode($response, true);

if (isset($responseData['token'])) 
{
    $token = $responseData['token'];
    $validDuration = $responseData['validDurationSeconds'];
////////
                                $chkp= $con->getCus(); 
                                if ($chkp->rowCount()>0)
                                {
                                  $phones=$chkp->fetchAll();
      
                                    
                                    foreach ($phones as $phon):
                                   echo $pn=$phon['phone'];
                                    $gt= $con->getThisOnlyCusdbt($pn,$status);
                                    print_r($gt->ErrorInfo());
                                    if ($gt->rowCount()>0)
                                    {
                                    $dbts=$gt->fetchAll();
                                    foreach ($dbts as $db):
                                    $totaldbts=$totaldbts+$db['balance'];
                                    endforeach;
                                    }
                                    $phone ="255".substr($phon['phone'], 1);
                                    if ($totaldbts>0){ 
                                          sendSmsViaVodacom($dr,$drn,$token,$phone, $message); 
                                      }
                                        ?><p/><?php 
                                     $totaldbts=0;
                                     endforeach;
                                     
                                     
                                     
                                }
                                   
                                   //echo $dr."customer(s) received message";
 
                                  // echo $drn." customer(s) not reachable.";
   
}

    echo $dr."customer(s) received message";
    echo $drn." customer(s) not reachable.";
} else {
    echo "Failed to get token. Response: $response\n";
}



function sendSmsViaVodacom($dr,$drn,$token,$phone, $message) {
        
             $url = 'https://apis.onfonmedia.co.ke/v2_send'; 
             $payload = [
            'to' =>$phone,              // E.g., 254712345678
            'from' => 'ROMBO STAR',               // E.g., ONFON
            'content' =>$message ,
            'dlr' => 'yes',
             'dlr-url' => 'https://buda.co.tz/rombotz//sms_rdir.php',
            'dlr-level' => 1
               ];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $token",
    "Accept: application/json",
    "Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
$response = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
} else {
    //echo 'Response: ' . $response;
    $dat = json_decode($response, true);

// Check if 'message_id' exists
if (isset($dat['message_id'])) {
    $dr++;
    //echo $dr."customer(s) received message";
} else {
    $drn++;
   // echo $drn." customer(s) not reachable.";
}
}
curl_close($ch);
///////////////////

}*/
?>





















































<?php
 require_once "labClass.php";
$con = new labClass();
 $countUser=0;
$dr=0;
$drn=0;
$totaldbts=0;
$status="NOT PAID";
// send_sms.php

                    // Replace with your Sender ID

// === Build SMS data ===
$params = [];
////////////////

       $chkp= $con->getCus();//getUsersRecord();//; 
        if ($chkp->rowCount()>0)
                {
                $phones=$chkp->fetchAll();
                foreach ($phones as $phon):
                $pn=$phon['phone'];
                $gt= $con->getThisOnlyCusdbt($pn,$status); 
                 if ($gt->rowCount() >0)
                        {
                        $countUser++;
                        $dbts=$gt->fetchAll();
                        foreach ($dbts as $db):
                        $totaldbts=$totaldbts+$db['balance'];
                        endforeach;
                         }
                        $phone ="255".substr($phon['phone'], 1);
            if (in_array($phon['cname'], ['MAMUYA', 'AZIZI TAJIRI'])) 
                              {
                                  continue;
                             }
                        if ($totaldbts>0){
                            //{$phon['cname']}
                            $amountFormatted = number_format($totaldbts, 2);
                            $message = "Boss,habari. Tunakukumbusha kulipa deni lako TZS {$amountFormatted}. Tafadhali lipa ili tuweze kuendelea kukuhudumia.Lipa (M-pesa Lipa no: 54926722-ROMBO STAR) au bank(NMB: 43510048697-LADISLAUS ERNEY KIMARIO). Kwa maelezo zaidi piga 0744195006.";
                                    $params[] = [
                                         "Number" => $phone,
                                          "Text" => $message
                                                 ];
                                      }
                                        ?><p/><?php 
                                        if($countUser==20){
                                            smsAPI($params);
                                            $params = [];
                                            $countUser=0;
                                             echo "First 20 msg sent"; 
                                        }
                                        
                                     $totaldbts=0;
                                     endforeach;
                        if (!empty($params)) 
                             {
                              smsAPI($params);
                             }
                                     
               }


////////////////////////

/////////////OLD DEBIT////////////
$params = [];
////////////////

       $chkp= $con->getCus();//getUsersRecord();//; 
        if ($chkp->rowCount()>0)
                {
                $phones=$chkp->fetchAll();
                foreach ($phones as $phon):
                $cn=$phon['cname'];
                $gt= $con->getThisOnlyOlddbt($cn,$status); 
                 if ($gt->rowCount() >0)
                        {
                        $countUser++;
                        $dbts=$gt->fetchAll();
                        foreach ($dbts as $db):
                        $totaldbts=$totaldbts+$db['balance'];
                        endforeach;
                         }
                        $phone ="255".substr($phon['phone'], 1);
            if (in_array($phon['cname'], ['MAMUYA', 'AZIZI TAJIRI'])) 
                              {
                                  continue;
                             }
                        if ($totaldbts>0){ 
                            $amountFormatted = number_format($totaldbts, 2);
                            $message = "Boss,habari.Tunakukumbusha kulipa deni lako TZS {$amountFormatted}. Tafadhali lipa ili tuweze kuendelea kukuhudumia.Lipa (M-pesa Lipa no: 54926722-ROMBO STAR) au bank(NMB: 43510048697-LADISLAUS ERNEY KIMARIO). Kwa maelezo zaidi piga 0744195006.";
                                    $params[] = [
                                         "Number" => $phone,
                                          "Text" => $message
                                                 ];
                                      }
                                        ?><p/><?php 
                                        if($countUser==20){
                                            smsAPI($params);
                                            $params = [];
                                            $countUser=0;
                                             echo "First 20 msg sent"; 
                                        }
                                        
                                     $totaldbts=0;
                                     endforeach;
                        if (!empty($params)) 
                             {
                              smsAPI($params);
                             }
                                     
               }




 function smsAPI($params){
// === Configuration ===

date_default_timezone_set('Africa/Dar_es_Salaam');

// Database config 

// Onfon Media API config
$api_url     = "https://api.onfonmedia.co.ke/v1/sms/SendBulkSMS";
$api_key     = "czu3YnOb5j4tfR08LsEmUIhvkP1BZS9qdoXlCgN6rwax7G2e";  // Replace with your real API Key
$client_id   = "rombostar";  // Replace with your real Client ID
//$access_key  = "xxxxxxxx-xxxx-xxxx-xxxx";  // Replace with your real Access Key
$sender_id   = "ROMBO STAR";
// === Send SMS via Onfon API ===
if (!empty($params)) {
    $payload = json_encode([
        "SenderId" => $sender_id,
        "MessageParameters" => $params,
        "ApiKey" => $api_key,
        "ClientId" => $client_id
    ]);

    $ch = curl_init($api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
   // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // Log success or failure
    file_put_contents("sms_response_log.txt", "[" . date("Y-m-d H:i:s") . "] HTTP $httpCode - $response\n", FILE_APPEND);
} else {
    file_put_contents("sms_response_log.txt", "[" . date("Y-m-d H:i:s") . "] No unpaid customers found.\n", FILE_APPEND);
}
}





?>
             
  