<?php
if(isset($_POST["pOpt"]) &&isset($_POST["bal"]) && isset($_POST["orno"]) && isset($_POST["user"]) && isset($_POST["cbal"]) &&    isset($_POST["sdate"]))
{ 
////
    $cash= $_POST['bal'];
    $orderID= $_POST['orno'];  
    $cbal= $_POST['cbal'];
    $pOpt= $_POST['pOpt'];
    $user= $_POST['user'];
    $sdate= $_POST['sdate'];
    $tPrice=$cash;
    if($cbal==$cash)
    {
      $pst="PAID";
    }
    else{
       $pst="NOT PAID"; 
    } 
  //CHECKING ENDS HER
    require_once"labClass.php";
    $con=new labClass(); 
  $pOpt="CASH";
  $k= $con->getMuamalaCash($pOpt,$sdate);
 if($k->rowCount()>0)
      {
   $cs=$k->fetch() ;
   if($cs['statusB']=="Saved"){
       
    $Qc= $con->getThisOrder($orderID);
      //print_r($Qc->ErrorInfo());
    if($Qc->rowCount()>0)
     {
      $p= $con->getThisOrder($orderID)->fetch();
      $ptd=$p["paidtodate"]+$cash;
      $obal=$p["balance"];
      $cus=$p["cname"];
      $nbal=$obal-$cash;       
      if(($ptd>0) && ($nbal>=0)) 
       { 
       $rQc= $con->updateOrder($orderID,$nbal,$ptd,$pst);
       if($rQc->rowCount()>0)
        {
           $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!. Tunakushukuru kwa malipo ya TZS {$amountFormatted} yaliyofanyika. Asante kwa uaminifu wako. Karibu tena";
              $params[] = [
                          "Number" => $phone,
                          "Text" => $message
                          ];
                     }
           
           smsAPI($params);
           
           ///////////////////
            $pOpt= $_POST['pOpt'];
           if($popt=="DISCOUNT"){
               $cash= -1*$_POST['bal'];
           } 
            
            
        $rc= $con->debitPRec($orderID,$cus,$cash,$sdate,$user,$pOpt);
        
        if($rc->rowCount()>0)
        {
            
              //////////////////////////////
        if($pOpt!="DISCOUNT"){
        $pOpt="CASH";
        $e= $con->getMuamalaCash($pOpt,$sdate);
          if($e->rowCount()>0)
           {
             $nn=$e->fetch();
             $tPrice= $nn['amount']+$tPrice;
             $r= $con->updateToDayCash($tPrice,$pOpt,$sdate);
              if($r->rowCount()>0)
               {
                ///$rQc= $con->miamala($pOpt,$user,$tPrice,$sdate);
                  ?>
                   <h6 class="text-success">Save!..</h6>
                  <?php
               }
               else{
                  ?>
                  <h6 class="text-danger">Transaction update failed!..</h6>
                 <?php
                   }
              }
           else{
              $rc= $con->miamala($pOpt,$user,$tPrice,$sdate);
                  if($rc->rowCount()>0)
                   {
                    ?>
                      <h6 class="text-success">Save!..</h6>
                    <?php
                    }
                 else{
                    ?>
                    <h6 class="text-danger">Failed to register transaction!..</h6>
                   <?php
                    }
              }
        }else{
    //////////////  
            
           
        ?>
          <h6 class="text-success">Save!..</h6>
         <?php  
        }
         }
        else{
          ?>
          <h6 class="text-danger">Technical error!..</h6>
          <?php
           }
        }
  else{
       ?>
       <h6 class="text-danger">Upadate failed!..</h6>
       <?php
       }
       }
  else{
       ?>
       <h6 class="text-danger">Invalid balance submit!..</h6>
       <?php
       }
      }
  else{
       ?>
       <h6 class="text-danger">Invalid order number!..</h6>
       <?php
       }
       
       ////////////
   }
else{
   echo "Transaction closed up can't delete!";

}
}
else{
    echo "Transaction not found!";
}
///////
     }
  else{
       ?>
       <h6 class="text-danger">All field required!..</h6>
       <?php
       }
       
function smsAPI($params){

date_default_timezone_set('Africa/Dar_es_Salaam'); 
$api_url     = "https://api.onfonmedia.co.ke/v1/sms/SendBulkSMS";
$api_key     = "czu3YnOb5j4tfR08LsEmUIhvkP1BZS9qdoXlCgN6rwax7G2e"; 
$client_id   = "rombostar";  
$sender_id   = "ROMBO STAR"; 

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); 
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch); 
    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);
}


}


?>