<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if($_POST["itemID"] && $_POST["iname"] && $_POST["user"] && $_POST["recID"] &&   $_POST["qty"]&& $_POST["tim"]  && $_POST["ds"] && $_POST["orderID"])
{ 
    
   // user:user,itemID:itemID,recID:recID,pOpt:pOpt,ds:ds,tim:tim,iname:iname
     $qty= $_POST['qty']; 
     $recID= $_POST['recID'];
     $user= $_POST['user'];
     $iname= $_POST['iname'];
     $ds= $_POST['ds'];
     $itemID= $_POST['itemID'];
     $tim= $_POST['tim'];
     $orderID=$_POST["orderID"];
     $us=$tim."(Edt:".$user.")";
     require_once"labClass.php";
     $con=new labClass();
     $p= $con->getThisOrder($orderID)->fetch();
     $ptd=$p["paidtodate"];
     $obal=$p["balance"];
     $cus=$p["cname"]; 
    // 603AIRFRESH1514:13:10 PM: By AIKOH, HASSAN
  //CHECKING ENDS HER
  
  $Q= $con->getThisSelVinV($tim,$itemID,$iname);
  if($Q->rowCount()>0)
    {
     
        $Qr= $con->delSellVinVD($ds,$tim,$iname,$itemID);
        if($Qr->rowCount()>0)
      {
          //======
          
       $Q= $con->getThisItemBID($itemID,$iname);
       if($Q->rowCount()){
           $it=$Q->fetch();
           $tQty=$qty+$it['iqty'];
           $r= $con->updateItemQ($iname,$tQty,$itemID);
          ////////////////
          //echo "p1";
             
              $Qq= $con->getThisItmInvLstBID($tim,$itemID,$iname);
              if($Qq->rowCount()>0)
               { 
                    //echo "p2";
                $gr=$Qq->fetch();
                $orderID=$gr['orderID'];
                $rate=$gr['tprice'];
                $qq= $con->getThisOrder($orderID)->fetch();
                $bal=$qq['balance'];
                $pbal=$qq['payableA'];
                $cname=$qq['cname'];
                //$cr= $con->updateInvItmListD($ds,$us,$iname,$itemID,$orderID);
                $oi= $con->delorderitD($ds,$orderID,$tim,$iname,$itemID,$recID);
                if($pbal>$rate)
                  {
                     // echo "p3";
                     $pbal=$pbal-$rate;
                     $bal=$bal-$rate;
                     $crc= $con->updateOrderD($bal,$pbal,$orderID); 
                       ?>
                 <h6 class="text-success">Item deleted!..</h6>
               <?php
                  }
                  else if($pbal==$rate)
                    {
                        
                        //echo "p4";
                     $pbal=$pbal-$rate;
                     $bal=$bal-$rate;
                     $crc= $con->cancelOrderD($cname,$bal,$pbal,$orderID);
                     
                     

                     
                     
                      $params = [];
           //////////////////////////
          // if ($cash>0){ 
               $parts = explode('(', $p['cname']); 
               if (preg_match('/Tel:(\d{10,})/', $p['cname'], $matches)) 
                      {
                        $phon = $matches[1];
                      }  
              $phone ="255".substr($phon, 1);
              //$amountFormatted = number_format($cash, 2);
              $message = "Boss {$parts[0]},habari za kazi!. Deni lako limefutwa.Tunaomba radhi kwa usumbufu uliojitokeza. Asante na karibu tena";
              $params[] = [
                          "Number" => $phone,
                          "Text" => $message
                          ];
                     //}
           
           smsAPI($params);
           
                       ?>
                 <h6 class="text-success">Cancelled!..</h6>
               <?php
                  }
                  
               
               
                 }
         else{
             ?>
              <h6 class="text-danger">Invoice not found!..</h6>
            <?php
             }
                 ///// 
             }
            else{
       ?>
        <h6 class="text-danger">Item not found!..</h6>
       <?php
       }
        //------
          }else{
           ?>
            <h6 class="text-danger">Sells not deleted!..</h6>
           <?php
             }
          /////////////////
       }
  else{
       ?>
        <h6 class="text-danger">Sells not found!..</h6>
       <?php
       }
          //==========
        }
  
  else{
       ?>
       <h6 class="text-danger">All field required!..</h6>
       <?php
       }
       
       
 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);
}
}

  
?>