<?php

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
 */

/**
 * Description of Class
 *
 * @author arix
 */
class AsteriskCustom {

    public $astHost;
    public $astUser;
    public $astPassword;
    public $astPort;
    private $astSocket;
    public $svaLog;

    public function __construct($astHost, $astUser, $astPassword, $astPort, $svaLog) {
        $this->astHost = $astHost;
        $this->astUser = $astUser;
        $this->astPassword = $astPassword;
        $this->astPort = $astPort;
        $this->svaLog = $svaLog;
    }

    private function connect() {
        $status = false;

        $this->astSocket = @fsockopen($this->astHost, "$this->astPort", $errno, $errstr, 10);
        if (!$this->astSocket) {
            echo "$errstr ($errno)\n";
        } else {

            $status = true;
        }

        return $status;
    }

    private function disconnect() {

        if ($this->astSocket) {

            fclose($this->astSocket);
        }
    }

    public function exec($cmd) {
        $result = "";
        $status = false;
        $status = $this->connect();

        if ($status) {
            fputs($this->astSocket, "Action: Login\r\n");
            fputs($this->astSocket, "UserName: $this->astUser\r\n");
            fputs($this->astSocket, "Secret: $this->astPassword\r\n\r\n");
            fputs($this->astSocket, "Action: Command\r\n");
            fputs($this->astSocket, "Command: $cmd \r\n\r\n");
            fputs($this->astSocket, "Action: Logoff\r\n\r\n");
            $i = 0;
            while (!feof($this->astSocket)) {

                $result[$i] = fgets($this->astSocket);
                $i++;
            }


            fclose($this->astSocket);
        }

        return $this->formatResult($result);
    }

    public function exec3($cmd) {


        $socket = fsockopen("127.0.0.1", "5038", $errno, $errstr, 10);
        if (!$socket) {
            echo "$errstr ($errno)\n";
        } else {
            fputs($socket, "Action: Login\r\n");
            fputs($socket, "UserName: svam\r\n");
            fputs($socket, "Secret: svam\r\n\r\n");
            fputs($socket, "Action: Command\r\n");
            fputs($socket, "Command: $cmd\r\n");

            fputs($socket, "Action: Logoff\r\n\r\n");

            while (!feof($socket)) {

                $result = fgets($socket);

                echo $result . "<br>";

                if (stristr($result, 'Output:') == TRUE) {

                    exit();
                }
            }
        }
        fclose($socket);

        return $res;
    }
    
     public function setAgentQueueMemberStatus($agentNumber, $status) {
        $cmd = "queue $status member SIP/$agentNumber";
        $peer = $this->exec($cmd);
        //echo "SIP/$agentNumber (Not in use)";
        //echo $peer['data'];
        return 0;
    }

    public function getAgentStatusByQueue($agentNumber, $queueName) {
        $status = "Désactivé";
        
        if(strlen($agentNumber)> 0 ){
            
             $cmd = "queue show $queueName ";

        // echo $cmd;
        $peer = $this->exec($cmd);
        //echo "SIP/$agentNumber (Not in use)";
        //echo $peer['data'];
        // print_r($peer);
       // echo count($peer['output']);
       
        $j = 0;
        $total = count($peer['output']);
       // $peer = $peer['output'];
         
        do {
           //  echo "ID => ".$j. " CURDATA :-> ".$peer['output'][$j];
            if (substr_count($peer['output'][$j], "SIP/$agentNumber") > 0) {
                //     echo " Line found checking";
                if (substr_count($peer['output'][$j], "pause") > 0) {
                    $status = "Pause";
                    $j = 100;
                }elseif(substr_count($peer['output'][$j], "Busy") > 0) {  
                    $status = "Busy";
                    $j = 100;
                } elseif(substr_count($peer['output'][$j], "Not in use")) {
                    $status = "Actif";
                    
                    $j = 100;
                }

                //  echo $status;
            }
           
            $j++;
        } while ( $j < $total);
            
        }
       

        return $status;
    }

    private function formatResult($result) {
        $formatted = "";

        $resultLength = count($result);
        $work = "";
        $rescnt = 0;
        $msgcnt = 0;
        $outcnt = 0;

        for ($i = 10; $i < $resultLength; $i++) {
            //  echo substr(trim($result[$i]), 0, 8) ;

            if (substr(trim($result[$i]), 0, 8) == "Response") {
                $work = substr(trim($result[$i]), 0, 8) . ":";
                $formatted['response'][$rescnt] = str_replace($work, "", trim($result[$i]));
                $rescnt++;
            } elseif (substr(trim($result[$i]), 0, 7) == "Message") {
                $work = substr(trim($result[$i]), 0, 7) . ":";
                $formatted['message'][$msgcnt] = str_replace($work, "", trim($result[$i]));
                $msgcnt++;
            } elseif (substr(trim($result[$i]), 0, 6) == "Output") {
                $work = substr(trim($result[$i]), 0, 6) . ":";
                $formatted['output'][$outcnt] = str_replace($work, "", trim($result[$i]));
                $outcnt++;
            }
        }



        return $formatted;
    }

    public function getSipUserRegistrations() {
        // $output = "";
        $cmd = "sip show registry";
        $res = $this->exec($cmd);
        $output = $res['output'];
        /* if($res['response'][0] == "Success") {


          } */

        return $output;
    }

    public function getSipUserRegistrationStatus($username, $output) {
        //   echo ($output[0]);
        $status = false;
        $total = count($output);
        $name = trim(substr($username, 0, 12));
        $work = "";
        // echo "AM HERE = ".$total;
        if (strlen($name) > 0) {

            for ($i = 0; $i < $total; $i++) {

                if (substr_count(strtolower($output[$i]), strtolower($name)) > 0) {

                    if (substr_count($output[$i], "Registered") > 0) {
                        // echo "JE SUIS ICI A NOUVO";
                        $status = true;
                        continue;
                    }
                }
            }
        }




        return $status;
    }

    public function getSipPeers() {
        // $output = "";
        $cmd = "sip show peers";
        $res = $this->exec($cmd);
        $output = $res['output'];
        /* if($res['response'][0] == "Success") {


          } */

        return $output;
    }

    public function getSipPeerStatus($username, $output) {
        //  echo ($output[0]);

        $status = false;
        $total = count($output);
        $name = $username;
        $work = "";
        // echo "AM HERE = ".$total;

        if (strlen($name) > 0) {

            for ($i = 0; $i < $total; $i++) {
                // echo $i." -  CUR :> ".$output[$i]." -  NAME:>".$name;
                if (substr_count(strtolower($output[$i]), strtolower($name)) > 0) {

                    if (substr_count($output[$i], "OK") > 0) {
                        // echo "JE SUIS ICI A NOUVO";
                        $status = true;
                        continue;
                    }
                }
            }
        }




        return $status;
    }

    /*** NEW ***/

    // Méthode pour récupérer les informations des files d'attente
    public function getQueueInfo() {
        $cmd = "queue show";
 
        $res = $this->exec($cmd);
       // print_r($res);
        return $this->extractQueueInfo($res['output']);
    }

    // Méthode pour parcourir le retour et détecter les stats Asterisk
    public function extractQueueInfo($output) {
        $callsInProgress = 0;
        $callsInQueue = 0;
        $queueCount = 0;
        $totalWaitTime = 0;
    
       // echo "Début de l'analyse des files d'attente...\n";
        //print_r($output);
    
        foreach ($output as $line) {
            $line = trim($line);
           // echo "Analyse de la ligne : $line\n";
            
            // Détecter les lignes de files d'attente
            if (preg_match('/^(.*) has (\d+) calls/', $line, $matches)) {
              //  echo "Ligne de file d'attente détectée : $line\n";
                $queueCount++;
            }
            
            // Détecter les personnes en communication
            if (preg_match('/(.*)(in call)/', $line)) {
              //  echo "Personne en communication détectée : $line\n";
                $callsInProgress++;
            }
            
            // Extraire le temps d'attente moyen
            if (preg_match('/wait: (\d+):(\d+)/', $line, $matches)) {
                $minutes = (int)$matches[1];
                $seconds = (int)$matches[2];
                $totalWaitTime += ($minutes * 60) + $seconds;
                $callsInQueue++;
             //   echo "Tempssssssssssssssss d'attente détecté : $minutes minutes et $seconds secondes\n";
            }
        }
    
        $averageWaitTime = $callsInQueue > 0 ? $totalWaitTime / $callsInQueue : 0;
    
        $retour ['callsInProgress']=$callsInProgress;
        $retour ['callsInQueue']=$callsInQueue;
        $retour ['queueCount']=$queueCount;
        $retour ['averageWaitTime']=$averageWaitTime;

        return $retour;
    }


public function getSipPeersInfo() {
    $cmd = "sip show peers";
    $res = $this->exec($cmd);

    // Extraire les informations des pairs SIP
    return $this->extractSipPeersInfo($res['output']);
}

public function extractSipPeersInfo($output) {
    $onlineuser = 0;

    foreach ($output as $line) {
        $line = trim($line);

        // Arrêter la boucle si la ligne commence par "Orange-out"
        if (strpos($line, 'Orange-out') === 0) {
            break;
        }

        // Vérifier si la ligne contient "OK" suivi de "(x ms)"
        if (preg_match('/OK \(\d+ ms\)/', $line)) {
            $onlineuser++;
        }
    }

    $retour['onlineuser'] = $onlineuser;
    return $retour;
}

}
