<?php

class svaTool {

    public function checkLocalPhone($phoneNumber) {
        $isValid = false;
        $phoneNumber = (string) $phoneNumber;
        $prefix = $phoneNumber[0] . $phoneNumber[1];

        if (strlen($phoneNumber) == 8 && ($prefix == "61" || $prefix == "60"))
            $isValid = true;

        return $isValid;
    }

    public function checkRechargeCode($rechargeCode) {
        $isValid = false;
        $rechargeCode = (string) $rechargeCode;
        if (strlen($rechargeCode) == 14)
            $isValid = true;

        return $isValid;
    }

    function convertSecToMin($value) {
        $tobedisplayed = "";
        $result[0] = $value % 60;
        $result[1] = $value / 60;

        $tobedisplayed = "";

        if ($result[1] >= 1) {
            $minutes = (int) $result[1];
            $tobedisplayed .= $minutes . "Min";
        }


        if ($result[0] > 0) {
            $secondes = $result[0];
            $tobedisplayed .= $secondes . "s";
        }

        return $tobedisplayed;
    }

    //CONVERTIR S EN MOIS JOUR HEUR MIN S
    public function convertSecondsToMJDHMS($value) {
        $months = floor($value / (30 * 24 * 3600)); 
        $restantAPresMonths = $value % (30 * 24 * 3600);
        
        $days = floor($restantAPresMonths / (24 * 3600));
        $RestantApresDays = $restantAPresMonths % (24 * 3600);
        
        $hours = floor($RestantApresDays / 3600);
        $RestantApresHours = $RestantApresDays % 3600;
        
        $minutes = floor($RestantApresHours / 60);
        $seconds = $RestantApresHours % 60;
        
        $result = '';
        if ($months > 0) {
            $result .= $months . 'Mois ';
        }
        if ($days > 0) {
            $result .= $days . 'J ';
        }
        if ($hours > 0) {
            $result .= $hours . 'H ';
        }
        if ($minutes > 0) {
            $result .= $minutes . 'Min ';
        }
        if ($seconds > 0 || ($months == 0 && $days == 0 && $hours == 0 && $minutes == 0)) {
            $result .= $seconds . 'S';
        }
        
        return trim($result);
    }
    

    public function getWalletName($walletId) {

        $walletLongList = array('1' => 'Solde', '2' => 'Vin', '3' => 'Bonus', '4' => 'Sin', '5' => 'Shr', '6' => 'Data', '7' => 'MMS', '8' => 'MUL');

        return $walletLongList[$walletId];
    }

    public function getWalletType($walletId) {
        $walletType = "D";
        if ($walletId == 1) {
            $walletType = "B";
        } elseif ($walletId > 1 && $walletId < 9) {
            $walletType = "S";
        } else {
            $walletType = "D";
        }


        return $walletType;
    }

    public function resetArray($length, $defaultVal) {

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

            $arrayTab[$i] = $defaultVal;
        }

        return $arrayTab;
    }

    public function getUserRightDef($right) {

        $rightDef = NULL;

        switch ($right) {

            case 1 : $rightDef = "ADMINISTRATEUR";
                break;
            case 2 : $rightDef = "MASTER";
                break;
            case 3 : $rightDef = "INTERMEDIAIRE";
                break;
            case 4 : $rightDef = "POS";
                break;
        }


        return $rightDef;
    }

    public function getDateTemplateFr($timestamp) {
        $timestamp = (string) $timestamp;
        $year = $timestamp[0] . $timestamp[1] . $timestamp[2] . $timestamp[3];
        $month = $timestamp[4] . $timestamp[5];
        $day = $timestamp[6] . $timestamp[7];
        $hours = $timestamp[8] . $timestamp[9];
        $minute = $timestamp[10] . $timestamp[11];
        $seconde = $timestamp[12] . $timestamp[13];

        //$dateFormat = $year."-".$month."-".$day." ".$hours.":".$minute.":".$seconde;
        $dateFormat = $day . "/" . $month . "/" . $year . " " . $hours . ":" . $minute . ":" . $seconde;

        return $dateFormat;
    }

    public function getDateTemplateExtFr($timestamp) {
        $timestamp = (string) $timestamp;
        $year = $timestamp[0] . $timestamp[1] . $timestamp[2] . $timestamp[3];
        $month = $timestamp[4] . $timestamp[5];
        $day = $timestamp[6] . $timestamp[7];
        $hours = $timestamp[8] . $timestamp[9];
        $minute = $timestamp[10] . $timestamp[11];
        $seconde = $timestamp[12] . $timestamp[13];

        //$dateFormat = $year."-".$month."-".$day." ".$hours.":".$minute.":".$seconde;
        $dateFormat = $day . "/" . $month . "/" . $year . " " . $hours . ":" . $minute . ":" . $seconde;

        return $dateFormat;
    }

    public function getTransactionSumHtml($from, $to, $amount, $batchId) {


        $htmlContent = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>Document sans nom</title>
</head>

<body>

<style type="text/css">
<!--
.Style2 {
	color: #FFFFFF;
	font-weight: bold;
}
.Style3 {color: #FF0000}
-->
</style>
<table width="67%" border="0">
  <tr>
    <td width="20%" bgcolor="#009900"><span class="Style2">Date</span></td>
    <td width="22%" bgcolor="#009900"><span class="Style2"> Source </span></td>
    <td width="23%" bgcolor="#009900"><span class="Style2">Destination</span></td>
    <td width="35%" bgcolor="#009900"><span class="Style2">Montant</span></td>
    <td width="35%" bgcolor="#009900"><span class="Style2">Numero Transaction</span></td>
  </tr>
  <tr>
    <td><div align="center"><span class="Style3">' . date("d/m/Y H:i:s") . '</span></div></td>
    <td><div align="center"><span class="Style3">' . $from . '</span></div></td>
    <td><div align="center"><span class="Style3">' . $to . '</span></div></td>
    <td><div align="center"><span class="Style3">' . $amount . '</span></div></td>
    <td><div align="center"><span class="Style3">' . $batchId . '</span></div></td>
  </tr>
</table>

</body>
</html>
';

        return $htmlContent;
    }

    public function getTransacType($errorCode) {

        switch ($errorCode) {

            case 100: $message = "EXECUTEE";
                break;
            case 101: $message = "ANNULEE";
                break;
            case 102: $message = "CREE";
                break;
            case 103: $message = "VALIDEE";
                break;
            case 104: $message = "APPROUVEE";
                break;
        }

        return $message;
    }

    function processListArray($listType, $currentList, $xwadDbAcess) {

        $outListArray = array();
        $saveTplMarkerArr = array("[", "]");
        $j = 0;

        $listData = explode(";", $currentList);

        //print_r($listData);

        $countData = count($listData);

        for ($cmp = 0; $cmp < $countData; $cmp++) {

            if (strlen($listData[$cmp]) != 0) {

                if (substr($listData[$cmp], 0, 1) == "[") {


                    //echo "Liste Sauvegarder ".$listData[$cmp].'<br>';
                    $currentTpl = trim(str_replace($saveTplMarkerArr, "", $listData[$cmp]));
                    $listCurs = $xwadDbAcess->getPhoneListDtlsByName($currentTpl, $listType);

                    if (mysql_num_rows($listCurs) > 0) {

                        while ($dbNewData = mysql_fetch_array($listCurs)) {
                            if (strlen($dbNewData['phone_number_n']) >= 8) {
                                $outListArray[$j] = $dbNewData['phone_number_n'];
                                $j++;
                            } else
                                return 4;
                        }
                    }
                } else {

                    $gapData = explode("-", $listData[$cmp]);
                    $gapDataCount = count($gapData);
                    if ($gapDataCount == 2) {

                        if (is_numeric($gapData[0]) && is_numeric($gapData[1])) {

                            if (strlen($gapData[0]) == 8 && strlen($gapData[1]) == 8) {


                                $gap = $gapData[1] - $gapData[0] + 1;

                                for ($p = 1; $p <= $gap; $p++) {

                                    $outListArray[$j] = $gapData[0];
                                    $gapData[0] = $gapData[0] + 1;
                                    $j++;
                                }
                            } else
                                return 4;
                        } elseif (is_numeric($listData[$cmp])) {

                            if (strlen($listData[$cmp]) == 8) {
                                $outListArray[$j] = $listData[$cmp];
                                $j++;
                            } else
                                return 4;
                        }


                        //echo "Direct".$listData[$cmp].'<br>';
                    } else {

                        if (strlen($listData[$cmp]) == 8) {
                            $outListArray[$j] = $listData[$cmp];
                            $j++;
                        } else
                            return 4;
                    }
                }
            }




            //echo $countData;
        }

        return $outListArray;
    }

    /*     * *********************** */

    public function getDateFormatEn($timestamp) {
        //25/10/2011
        $timestamp = (string) $timestamp;
        //list($day,$month,$year) = split("/",$timestamp);
        $day = $timestamp[0] . $timestamp[1];
        $month = $timestamp[3] . $timestamp[4];
        $year = $timestamp[6] . $timestamp[7] . $timestamp[8] . $timestamp[9];
        $dateFormat = $year . "-" . $month . "-" . $day;
        //  $dateFormat = $day."/".$month."/".$year." ".$hours.":".$minute.":".$seconde;

        return $dateFormat;
    }

    public function getDateTemplateFrSimple($date) {

        $dateTimePart = explode(" ", $date);
        $datePart = explode("-", $dateTimePart[0]);
        $timePart = explode(":", $dateTimePart[1]);

        $dateFormat = $datePart[2] . "/" . $datePart[1] . "/" . $datePart[0] . " " . $timePart[0] . ":" . $timePart[1] . ":" . $timePart[2];

        return $dateFormat;
    }

    function xml2HtmlWriter($xml) {
        $outputHeader = '<table width="100%" border="0" >';
        $outputFooter = '</table><br>';
        $working = count($xml->object);
        $xhtml = "";

        for ($i = 0; $i < $working; $i++) {
            $type = $xml->object[$i]['type'];
            $fileName = $xml->object[$i]->toneFile;

            switch ($type) {


                case "intro": $xhtml .= $this->writeIntro($xml->object[$i]);
                    break;
                case "playFile": $xhtml .= $this->writePlayFile($xml->object[$i]);
                    break;
                case "menu": $xhtml .= $this->writeMenu($xml->object[$i]);
                    break;
                case "goodbye" : $xhtml .= $this->writeHtmlGoodBye($xml->object[$i]);
                    break;
            }
        }



        return $outputHeader . $xhtml . $outputFooter;
    }

    function writePlayFile($object) {
        $html = NULL;

        $fileName = $object->toneFile;
        $fileName = str_replace("#", "", $fileName);
        $label = $object['label'];

        $html = '
                        <tr>
                            <td>' . $label . '</td>
                            <td align="left"><input type="file" name="' . $fileName . '" id="' . $fileName . '"  /></td>
                            <td>&nbsp;</td>
                        </tr>
                        ';

        return $html;
    }

    function writeHtmlGoodBye($object) {
        $html = NULL;

        $fileName = $object->toneFile;
        $fileName = str_replace("#", "", $fileName);
        $label = $object['label'];

        $html = '
                        <tr>
                            <td>' . $label . '</td>
                            <td align="left"> Oui : <input type="radio" name="goodbye" id="goodbye" value="yes" checked="checked" /></td>
                            <td align="left">Non : <input type="radio" name="goodbye" id="goodbye" value="no" /></td>
                        </tr>
                        ';

        return $html;
    }

    function writeIntro($object) {
        $html = NULL;

        $fileName = $object->toneFile;
        $fileName = str_replace("#", "", $fileName);
        $label = $object['label'];

        $html = '
                        <tr>
                            <td>' . $label . '</td>
                            <td align="left"> Oui : <input type="radio" name="intro" id="intro" value="yes" checked="checked" /></td>
                            <td align="left">Non : <input type="radio" name="intro" id="intro" value="no" /></td>
                        </tr>
                        ';

        return $html;
    }

    function writeMenu($object) {
        $html = NULL;
        $outputHeader = "";
        $outputFooter = "";
        // $outputHeader = '<table width="50%" border="0">';
        // $outputFooter ='</table><br>';
        $outputBody = "";
        $fileName = $object->toneFile;
        $fileName = str_replace("#", "", $fileName);
        $label = $object['label'];
        $layout = $object['layout'];
        $autoField = $object['autofield'];

        $menuOptionList = '<tr>
                             <td align="left">Selectionnez les options du menu : </td>
                             <td align="left"> <select name="autoMenuToneId" id="autoMenuToneId" size="4" onchange="showAutoMenuDesc();">
                                <option value="1">Option de réécoute uniquement</option>
                                <option value="2">Option de partage uniquement</option>
                                <option value="3">Option de souscription uniquement</option>
                                <option value="4">Option de réécoute et partage</option>
                                <option value="5">Option de réécoute et souscription</option>
                                <option value="6">Option de partage et souscription</option>
                                <option value="7" selected >Option de réécoute, partage et souscription</option>
                            </select></td>
                            <td>&nbsp;</td>
                             
                            </tr>
                              ';

        $selectFileZone = '<tr>
                            <td align="left">' . $label . '</td>
                            <td align="left"><input type="file" name="' . $fileName . '" id="' . $fileName . '" /></td>
                            <td>&nbsp;</td>
                        </tr>
               ';

        $selectOfferZone = '<tr>
                            <td align="left"><input type="checkbox" name="' . $fileName . '" id="' . $fileName . '" /> : ' . $label . '</td>
                            <td align="left"><input type="file" name="' . $fileName . '" id="' . $fileName . '" /></td>
                            <td>&nbsp;</td>
                        </tr>
               ';

        if ($layout == 'auto') {


            $outputBody .= $menuOptionList;
        } elseif ($layout == 'manual') {
            $totalOptions = count($object->optionList->option);
            $outputBody .= $selectFileZone;
            // echo $totalOptions; 
            for ($p = 0; $p < $totalOptions; $p++) {
                $checked = "";
                $offerId = str_replace("#", "", $object->optionList->option[$p]->action['id']);
                $label = $object->optionList->option[$p]->action['label'];
                $offerControlId = $offerId . "Control";
                $itemId = trim($object->optionList->option[$p]->itemId);
                if ($object->optionList->option[$p]->itemId == 1)
                    $checked = "";
                else
                    $checked = "";


                $selectOfferZone = '<tr>
                            <td align="left"><input type="checkbox" name="' . $offerControlId . '" id="' . $offerControlId . '" ' . $checked . ' /> &nbsp; ' . $label . '</td>
                            <td align="left"><input type="text" name="' . $offerId . '" id="' . $offerId . '" size="3"  />  <input type="text" name="' . $offerId . $itemId . '" id="' . $offerId . $itemId . '" size="30"  /></td>
                            <td><a href="#" onclick="popOfferList(\'' . $offerId . '\',\'' . $itemId . '\')">Choisir</a> | <a href="#" onclick="cleanBox(\'' . $itemId . '\')">Effacer</a> </td>
                        </tr>
               ';

                $outputBody .= $selectOfferZone;
            }
        }


        $html = $outputHeader . $outputBody . $outputFooter;

        return $html;
    }

    function writeShareFrind($object) {
        $html = NULL;

        return $html;
    }

    public function xml2phpAgiGenerate($xml, $cfg) {
        $doGroupCount = 0;

        $doGroupOpenner = "
          
                      do {
          
                         ";

        $doGroupCloser = "} while (#COND);";

        $output = "";
        $doGroupList = array();

        $working = count($xml->object);

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

            if ($xml->object[$i]['doGroup'] != 'no')
                $doGroupList[$i] = $xml->object[$i]['doGroup'];
        }

        /*         * *****Rangement et suppresion des doublons****** */
        // print_r($doGroupList);
        if (count($doGroupList) != 0) {

            $doGroupList = array_unique($doGroupList);
        }




        $doGroupCount = count($doGroupList);
        //echo $doGroupCount;
        $bId = 0;
        $ivrBody = NULL;
        $xhtml = NULL;
        $doGroupReached = NULL;

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


            $type = $xml->object[$i]['type'];
            $fileName = $xml->object[$i]->toneFile;
            $doGroupId = $xml->object[$i]['doGroup'];
            $doGroupId = trim($doGroupId);
            //$doGroupBodyIdArray = NULL;


            if ($xml->object[$i]['doGroup'] == 'no') {
                // Process No Do group.



                switch ($type) {

                    case "playFile" : $xhtml = $this->writeIvrPlayFile($xml->object[$i]);
                        break;
                    case "menu": $xhtml = $this->writeIvrMenu($xml->object[$i]);
                        break;
                    case "intro": $xhtml = $this->writeIvrIntro($xml->object[$i]);
                        break;
                    case "goodbye" : $xhtml = $this->writeIvrGoodbye($xml->object[$i]);
                        break;
                    case "shareFriend" : $xhtml = $this->writeIvrShareFriend($xml->object[$i]);
                        break;
                }

                $ivrBody[$bId]['data'] = $xhtml[0];
                $bId++;
            } else {
                // Process Do group
                // $usedDoGroupArray[$usedDoGroupCount] = $xml->object[$i]['doGroup'];
                // $usedDoGroupCount++;

                switch ($type) {

                    case "playFile" : $xhtml = $this->writeIvrPlayFile($xml->object[$i]);
                        break;
                    case "menu": $xhtml = $this->writeIvrMenu($xml->object[$i]);
                        break;
                    case "intro": $xhtml = $this->writeIvrIntro($xml->object[$i]);
                        break;
                    case "goodbye" : $xhtml = $this->writeIvrGoodbye($xml->object[$i]);
                        break;
                    case "shareFriend" : $xhtml = $this->writeIvrShareFriend($xml->object[$i]);
                        break;
                }

                // echo "My Do Group ID ".$doGroupId." <br>";

                if (!isset($doGroupReached[$doGroupId])) {

                    $ivrBody[$bId]['doGroup'][$doGroupId]['data'] = "";
                    $ivrBody[$bId]['doGroup'][$doGroupId]['ivrExit'] = "";
                    $doGroupReached[$doGroupId] = $bId;

                    $ivrBody[$bId]['doGroup'][$doGroupId]['data'] .= $xhtml[0];
                    $ivrBody[$bId]['doGroup'][$doGroupId]['ivrExit'] .= $xhtml[1];

                    if ($xml->object[$i]['isProtected'] == 'yes') {

                        $ivrBody[$bId]['doGroup'][$doGroupId]['ivrProtected'] = $xml->object[$i]['id'];
                    } else {

                        $ivrBody[$bId]['doGroup'][$doGroupId]['ivrProtected'] = 'none';
                    }


                    $bId++;
                    //$doGroupBodyIdArray[]
                } else {


                    $ivrBody[$doGroupReached[$doGroupId]]['doGroup'][$doGroupId]['data'] .= $xhtml[0];
                    $ivrBody[$doGroupReached[$doGroupId]]['doGroup'][$doGroupId]['ivrExit'] .= $xhtml[1];
                }
            }
        }

        // Rewrite Do Group 
        $gid = null;
        // echo $doGroupCount;
        for ($i = 1; $i <= $doGroupCount; $i++) {
            $ifOpenner = "";
            $ifCloser = "";
            $doGroupCloser = "}
                            while (#COND);";
            $gid = $doGroupReached[$i];

            if ($ivrBody[$gid]['doGroup'][$i]['ivrProtected'] == 'none') {

                $doGroupCloser = str_replace('#COND', $ivrBody[$gid]['doGroup'][$i]['ivrExit'], $doGroupCloser);
                $ivrBody[$gid]['data'] = $doGroupOpenner . $ivrBody[$gid]['doGroup'][$i]['data'] . $doGroupCloser;
            } else {

                $ifOpenner = '
                  if($nextItem=="' . $ivrBody[$gid]['doGroup'][$i]['ivrProtected'] . '"){
                      

                  ';

                $ifCloser = "
                  
                    }
                    ";

                if ($ivrBody[$gid]['doGroup'][$i]['ivrProtected'] == "subscriptionMenu") {

                    $ifCloser = '
                         
                            // Play Option 
                       
                        $agi->exec("read","nchoice,".$menu."/".$defaultLanguage."/7019,1");
                        $nchoice = $ivrAction->extractDmtfVariable("nchoice");
                        
                        if($nchoice == 2 ) {
                            
                             replay_sendto_friend($agi, $menu, $defaultLanguage,$msisdn,$campaignId, $ivrAction, $svaDbAcess , $replayCount );
                            
                        }
                            
                            
                  
                    }
                              

                        ';
                }


                $doGroupCloser = str_replace('#COND', $ivrBody[$gid]['doGroup'][$i]['ivrExit'], $doGroupCloser);
                $ivrBody[$gid]['data'] = $ifOpenner . $doGroupOpenner . $ivrBody[$gid]['doGroup'][$i]['data'] . $doGroupCloser . $ifCloser;
            }
        }


        // print_r($ivrBody);
        $output = "";
        for ($p = 0; $p < count($ivrBody); $p++) {

            $output .= $ivrBody[$p]['data'];
        }

        // echo  $output;

        return $output;
    }

    function writeIvrPlayFile($object) {
        $phpAgiContent = array();
        $fileName = $object->toneFile;
        $phpAgiContent[0] = '
             $agi->exec("Playback","' . $fileName . '");
                 ';
        $phpAgiContent[1] = '';

        return $phpAgiContent;
    }

    function writeIvrIntro($object) {
        $phpAgiContent = array();
        //$fileName = $object->toneFile; 

        if ($object['enabled'] == 'yes') {

            $phpAgiContent[0] = '
                $agi->exec("Playback",$menu."/".$defaultLanguage."/intro");
                ';
            $phpAgiContent[1] = '';
        } else {

            $phpAgiContent[0] = '';
            $phpAgiContent[1] = '';
        }



        return $phpAgiContent;
    }

    function writeIvrGoodbye($object) {
        $phpAgiContent = array();
        //$fileName = $object->toneFile; 

        if ($object['enabled'] == 'yes') {

            $phpAgiContent[0] = '
                $agi->exec("Playback",$menu."/".$defaultLanguage."/goodbye");
                ';
            $phpAgiContent[1] = '';
        } else {

            $phpAgiContent[0] = '';
            $phpAgiContent[1] = '';
        }



        return $phpAgiContent;
    }

    function writeIvrMenu($object) {

        $output = NULL;

        $phpAgiContent = "\n";
        $fileName = $object->toneFile;
        $layout = $object['layout'];
        $autoField = $object['autofield'];
        $playerPart = "";
        $working = "";
        $optCount = 0;

        if ($layout == "auto") {
            // Automatic Mode Detected

            $playerPart = $this->writeAutoMenuPlayFile($autoField);

            $autoMenuOption = $this->showCaseTone($autoField);

            $ivrData = str_replace('#', '$', $autoMenuOption[0]);

            $output[0] = $phpAgiContent . $playerPart . $ivrData;

            // print_r($output[0]);

            $output[1] = str_replace('#', '$', $autoMenuOption[1]);

            //print_r($output[1]);
            //$output['phpCode'] = $phpAgiContent;
        } elseif ($layout == "manual") {

            $optCount = count($object->optionList->option);

            for ($j = 0; $j < $optCount; $j++) {

                if ($object->optionList->option[$j]->action['enabled'] == "yes") {
                    // Offer is enabled


                    $working .= '
                              case ' . $object->optionList->option[$j]->itemId . ' : $res = $serviceAction->subscribeOffer( $campaignId, "' . $object->optionList->option[$j]->action['offerCode'] . '",$msisdn );  $replayCount= 10; $agi->exec("Playback",$menu."/".$defaultLanguage."/7020");  break;
                           
                               ';
                }
            }




            // manual Mode detected 
            // $phpAgiContent .= '$agi->exec("Playback",'.$fileName.');'; 
            $output[0] = '  
                    $res = NULL;
                    $agi->exec("read","choice,' . $fileName . ',1");
                    $choice = $ivrAction->extractDmtfVariable("choice");
                    switch($choice){  
                    
                     ' . $working . '



                      default : $replayCount++;
                                    $agi->exec("Playback",$menu."/".$defaultLanguage."/7008");  
                          
                          
                      }
                    
                    ';
            $output[1] = '$replayCount <= MAX_REPLAY ';
        }




        return $output;
    }

    public function showCaseTone($toneId) {
        $caseData = NULL;
        $caseEnd = NULL;
        $dumpVar = NULL;

        switch ($toneId) {

            case 1 :

                $caseData = "
                                switch(#input){

                                    case 1 : #replayEnabled= true;  #replayCount++;     break;

                                    default :  #replayCount++; 

                                }

                                    ";
                $caseEnd = '#replayCount < MAX_REPLAY && #replayEnabled ';
                break;    // Only Replay Option 
            case 2 :

                $caseData = "
                                switch(#input){

                                  case 3 :  #nextItem ='shareFriend'; #exitOption = true; break;

                                    default :  #replayCount++; 

                                }

                                    ";

                $caseEnd = '#replayCount < MAX_REPLAY && !#exitOption ';

                break;    // Only Share Option
            case 3 :
                $caseData = "
                                switch(#input){
                                
                                    case 2 :  #nextItem ='subscriptionMenu'; #exitOption = true;  break;
                                    default :  #replayCount++; 

                                }

                                    ";

                $caseEnd = '#replayCount < MAX_REPLAY  && !#exitOption ';

                break;    // Only Subscription Option
            case 4 :

                $caseData = "
                                switch(#input){
                                    
                                    case 1 :  #replayEnabled= true;   #replayCount++;      break;
                                    case 3 :  #nextItem ='shareFriend'; #exitOption = true; break;  
                                    default :  #replayCount++; 

                                }

                                    ";

                $caseEnd = '#replayCount < MAX_REPLAY && #replayEnabled && !#exitOption ';

                break;    // Only Replay and Share option
            case 5 :

                $caseData = "
                                switch(#input){
                                    
                                    case 1 :  #replayEnabled= true;  #replayCount++;      break;
                                    case 2 :  #nextItem ='subscriptionMenu'; #exitOption = true;  break;
                                    default :  #replayCount++; 

                                }

                                    ";

                $caseEnd = '#replayCount < MAX_REPLAY && #replayEnabled && !#exitOption ';

                break;    // Only Replay and Subscription

            case 6 :


                $caseData = "
                                switch(#input){
                                    
                                    case 3 :  #nextItem ='shareFriend'; #exitOption = true; break;      
                                    case 2 :  #nextItem ='subscriptionMenu'; #exitOption = true;  break;
                                    default : #replayCount++; 

                                }

                                    ";

                $caseEnd = '#replayCount < MAX_REPLAY && #replayEnabled && !#exitOption ';

                break;    // Only Share and Subscription
            case 7 :

                $caseData = "
                                switch(#input){
                                    
                                    case 1 :  #replayEnabled= true; #replayCount++;     break;
                                    case 3 :  #nextItem ='shareFriend'; #exitOption = true; break;      
                                    case 2 :  #nextItem ='subscriptionMenu'; #exitOption = true;  break;
                                    default :  #replayCount++; 

                                }

                                    ";

                $caseEnd = '#replayCount < MAX_REPLAY && #replayEnabled && !#exitOption ';

                break;    //  Replay, Share, Subscription
        }




        $dumpVar[0] = $caseData;
        $dumpVar[1] = $caseEnd;

        return $dumpVar;
    }

    public function writeAutoMenuPlayFile($toneId) {
        $phpAgiPlayer = "
                ";

        $phpAgiPlayer .= ' $agi->exec("read","input,".$menu."/".$defaultLanguage."/auto/' . $toneId . ',1");';

        $phpAgiPlayer .= '
                $input = $ivrAction->extractDmtfVariable("input");';

        return $phpAgiPlayer;
    }

    public function writeIvrShareFriend($object) {

        $phpAgiContent = array();
        // $fileName = $object->toneFile; 

        $phpAgiContent[0] = '
             
                    $res = NULL;
                    $agi->exec("read","input1,".$menu."/".$defaultLanguage."/7010,9");
                    $input1 = $ivrAction->extractDmtfVariable("input1");
                    
                    if(strlen($input1) == 8 ){
                       $ndc = substr($input1,0,2);
                       
                       $res =  $svaDbAcess->iadCheckNdc($ndc);
                       // Check NDC
                       
                       if(mysql_num_rows($res) > 0 ){
                           // This NDC Exist, We can send the campaigned
                           // Send campaign to this Friend
                           
                         
                          $agi->exec("Playback",$menu."/".$defaultLanguage."/7013"); 
                         
                          $replayCount = 10;
                          $field = NULL;
                          $entity="";
   
                         // $svaDbAcess->upldBroadcastQueues( $campaignId, $input1, $entity, $field, 2  );
                          $svaDbAcess->upldQueuesProcessor($campaignId, $input1, $entity, 2  );
                         
                         /** Insert Statistic **/ 
                         $svaDbAcess->upldSharingStatistic($msisdn, $input1, $campaignId  );
                         
                         

                           
                       }
                       else {
                           // play Error
                           
                           $agi->exec("Playback",$menu."/".$defaultLanguage."/7012");
                           $replayCount ++;
                          // $agi->hangup();
                           
                       }
                        
                        
                        
                    }
                    else{
                        
                           $agi->exec("Playback",$menu."/".$defaultLanguage."/7011");
                           $replayCount ++; 
                          // $agi->hangup();
                    }
                    ';

        $phpAgiContent[1] = '$replayCount <= MAX_REPLAY ';

        return $phpAgiContent;
    }

    public function formatQueueQuery($count, $campaignId, $phoneNumber, $entity, $field, $status) {

        $sql = '';
        $header = 'INSERT INTO broadcast_queues_tab VALUES ';
        $separator = ',';
        $terminator = ';';
        $body = '';

        if ($count < 100) {
            // Not Nuùber reaches

            $body .= "(NULL,now(),'" . $campaignId . "','" . $phoneNumber . "','" . $entity . "','" . $field[0] . "','" . $field[1] . "','" . $field[2] . "','" . $field[3] . "','" . $field[4] . "','" . $status . "') " . $separator;
        } elseif ($count == 100) {

            $body .= "(NULL,now(),'" . $campaignId . "','" . $phoneNumber . "','" . $entity . "','" . $field[0] . "','" . $field[1] . "','" . $field[2] . "','" . $field[3] . "','" . $field[4] . "','" . $status . "') " . $terminator;

            $sql .= $header . $body;
        }
    }

    public function getFileExtension($filename) {

        $extData = explode(".", $filename);
        $partCount = count($extData);
        $ext = strtolower($extData[$partCount - 1]);

        return $ext;
    }

    public function regularStringCheck($string) {
        $isValid = false;
        $res = 0;
        // $bannedCharList = "[!\"#$%&/()=?*°'+*.,_;:-]";

        preg_match('/[\'\/~`\!#\$%\^&\*\(\)\+=\{\}\[\]\|;:"\<\>,\ \.\?\\\]/', $string, $res);

        if (count($res) > 0) {

            $isValid = false;
        } elseif (count($res) == 0) {

            $isValid = true;
        }


        return $isValid;
    }

    public function regularEmailCheck($string) {
        $isValid = false;
        $res = 0;
        // $bannedCharList = "[!\"#$%&/()=?*°'+*.,_;:-]";

        $regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';

        if (preg_match($regex, $string)) {

            $isValid = true;
        } else {
            $isValid = false;
        }



        return $isValid;
    }

    function extractParathensisData($data) {
        $extracted = null;
        $separator = array("(", ")");
        $data = str_replace($separator, ";", $data);

        $extracted = explode(";", $data);

        return $extracted[1];
    }

    public function checkUrl($url) {

        $file_headers = get_headers($url);
        if ($file_headers[0] == 'HTTP/1.1 404 Not Found') {
            $exists = false;
        } else {
            $exists = true;
        }

        return $exists;
    }

    public function oracleEscapeString($string) {

        $string = str_replace("'", "''", $string);
        $string = str_replace("\"", "\"\"", $string);

        return $string;
    }

    public function getSIPAgentConfig($agentNumber, $type, $host, $secret, $callLimit) {
        //$filePath = "/opt/svam/lib/scc/additional/scc_sip_additional.conf";
        $content = "\r\n[$agentNumber]\ntype=$type\ncontext=callcenter\nhost=$host\nusername=$agentNumber\nsecret=$secret\ndisallow=all\nallow=gsm\nallow=alaw\nallow=ulaw\nallow=g729\ncanreinvite=yes\nqualify=yes\ninsecure=invite,port\ncall-limit=$callLimit\ntransport=tcp";

        /*
          $fp= fopen($filePath,'a') or  print_r(error_get_last());
          fputs($fp,$content);
          fclose($fp);
         */

        return $content;
    }

    public function getSIPAgentConfigTrunk($agentNumber, $type, $host, $secret, $callLimit) {
        //$filePath = "/opt/svam/lib/scc/additional/scc_sip_additional.conf";
        $content = "\r\n[$agentNumber]\ntype=$type\ncontext=callcenter\nhost=$host\nusername=$agentNumber\nsecret=$secret\ndisallow=all\nallow=gsm\nallow=alaw\nallow=ulaw\nallow=g729\ncanreinvite=yes\nqualify=yes\ninsecure=invite,port\ntrunk=yes\ncall-limit=$callLimit\n";

        /*
          $fp= fopen($filePath,'a') or  print_r(error_get_last());
          fputs($fp,$content);
          fclose($fp);
         */

        return $content;
    }

    public function getSIPRegistrationConfig($username, $authUserName, $host, $port, $secret, $callerId) {
        //$filePath = "/opt/svam/lib/scc/additional/scc_sip_additional.conf";
        //$content = "\r\nregister => \ntype=$type\ncontext=callcenter\nhost=$host\nusername=$agentNumber\nsecret=$secret\ndisallow=all\nallow=gsm\nallow=alaw\nallow=ulaw\nallow=g729\ncanreinvite=yes\nqualify=yes\ninsecure=invite,port\n";		

        $content = "\r\n";
        $content .= 'register => ' . $username . ':"' . $secret . '":' . $authUserName . '@' . $host . ':' . $port . '/' . $callerId;
        $content .= "\n";

        return $content;
    }

    public function getQueueConfig($queueName, $wrapuptime, $member) {
        //$filePath = "/opt/svam/lib/scc/additional/scc_sip_additional.conf";
        $content = "\r\n[$queueName]\nmusicclass = default\nstrategy = ringall\ncontext = qoutscc\nwrapuptime = $wrapuptime\nmonitor-format = wav\nmonitor-type = MixMonitor\n$member";

        /*
          $fp= fopen($filePath,'a') or  print_r(error_get_last());
          fputs($fp,$content);
          fclose($fp);
         */

        return $content;
    }

    public function getQueueConfigExtend($queueName, $wrapuptime, $strategy, $member) {
        //$filePath = "/opt/svam/lib/scc/additional/scc_sip_additional.conf";
        $content = "\r\n[$queueName]\nmusicclass = default\nstrategy = $strategy\ncontext = qoutscc\nwrapuptime = $wrapuptime\nmonitor-format = wav\nmonitor-type = MixMonitor\nperiodic-announce-frequency=5\nperiodic-announce = busy-pls-hold\n$member";
        //echo $content;			
        /*
          $fp= fopen($filePath,'a') or  print_r(error_get_last());
          fputs($fp,$content);
          fclose($fp);
         */

        return $content;
    }

    public function getQueueMemberConfig($agentId) {
        //$filePath = "/opt/svam/lib/scc/additional/scc_sip_additional.conf";
        $content = "member => SIP/$agentId\n";
        //echo $content;			
        /*
          $fp= fopen($filePath,'a') or  print_r(error_get_last());
          fputs($fp,$content);
          fclose($fp);
         */

        return $content;
    }

    function escapeJsonString($value) { # list from www.json.org: (\b backspace, \f formfeed)
        $escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
        $replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
        $result = str_replace($escapers, $replacements, $value);
        return $result;
    }

    function SCCRefreshQueue($dba, $manager) {


        /* Get all interface -> getinterface Details by Id -> Build physical config -> reload config */
        $stdSipAccntData = "";
        $registrySipAccntData = "";
        $errorCode = 0;

        $queuelist = "";
        $res = $dba->SCCGetVoiceQueueAll();
        $total = count($res);

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



            $ures = $dba->SCCGetVoiceQueueMembersById($res[$i]['queue_id_n']);

            $memberlist = "";
            for ($p = 0; $p < count($ures); $p++) {

                if (strlen($ures[$p]['caller_id_v']) > 0) {

                    $memberlist .= $this->getQueueMemberConfig($ures[$p]['caller_id_v']);
                }
            }
            //  print_r($res[$i]);
            $queuelist .= $this->getQueueConfigExtend($res[$i]['name'], $res[$i]['wrapuptime'], $res[$i]['strategy'], $memberlist);
        }

        /*         * ************** Writing related file ********* */
        $fp = fopen($_SESSION['cfg']['scc']['queues.additional.file'], 'w') or die('Impossible d\'accéder au fichier.');

        if ($fp) {

            fputs($fp, $queuelist);
            fclose($fp);
        } else {

            $errorCode = 1;
        }



        $manager->reloadConfig();
    }

    public function exec($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 prepareMailBody($ticketId, $fromTeam, $toTeam, $priority, $description, $moduleName, $submoduleName, $qualification, $elapseTime){
        $mailBody = ' 
<table style="background:#f5f6fa;font-size:14px;line-height:22px;font-weight:400;color:#8094ae;width:100%">
    <tbody><tr>
            <td>
                <table style="width:100%;max-width:620px;margin:0 auto">
                    <tbody>
                        <tr>
                            <td style="text-align:center!important">
                                
                                <p style="font-size:13px;color:#6576ff;padding-top:12px"></p>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <table style="width:96%;max-width:620px;margin:0 auto;background:#ffffff">
                    <tbody>
                        <tr>
                            <td style="padding:2.75rem!important">



                                <p>Bonjour '.$toTeam.' ,</p>  
                                <p>Vous avez un ticket dans votre corbeille. Ci-dessous les informations :</p> 
                                <p>De               :<b>'.$fromTeam.'</b></p>
                                <p>Ticket N°        :<b>'.$ticketId.'</b></p>
                                <p>Motif            :<b>'.$qualification.'</b></p>
                                <p>Description      :<b>'.$description.'</b></p>
                                <p>Priorité         :<b>'.$priority.'</b></p>
                                <p>Categorie        :<b>'.$moduleName.'</b></p>
                                <p>Sous-Categorie   :<b>'.$submoduleName.'</b></p>  


                            </td>
                        </tr>
                    </tbody>
                </table>
                <table style="width:100%;max-width:620px;margin:0 auto">
                    <tbody>
                        <tr>
                            <td style="text-align:center!important">
                                <p>
                                    <em>Vous avez '.$elapseTime.' jour(s) pour traiter cette demande.</em>
                                </p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
    </tbody></table>';
        
        
        
        
        return $mailBody;
    }
    

    
    public function prepareMailEventBody($ticketId, $fromTeam, $toOwner, $priority, $description, $moduleName, $submoduleName, $qualification, $status){
        $mailBody = ' 
<table style="background:#f5f6fa;font-size:14px;line-height:22px;font-weight:400;color:#8094ae;width:100%">
    <tbody><tr>
            <td>
                <table style="width:100%;max-width:620px;margin:0 auto">
                    <tbody>
                        <tr>
                            <td style="text-align:center!important">
                                
                                <p style="font-size:13px;color:#6576ff;padding-top:12px"></p>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <table style="width:96%;max-width:620px;margin:0 auto;background:#ffffff">
                    <tbody>
                        <tr>
                            <td style="padding:2.75rem!important">



                                <p>Bonjour '.$fromTeam.' ,</p>  
                                <p>Le ticket ci-dessous a été : <b>'.$status.'</b></p> 
                                <p>De               :<b>'.$toOwner.'</b></p>
                                <p>Ticket N°        :<b>'.$ticketId.'</b></p>
                                <p>Motif            :<b>'.$qualification.'</b></p>
                                <p>Description      :<b>'.$description.'</b></p>
                                <p>Priorité         :<b>'.$priority.'</b></p>
                                <p>Categorie        :<b>'.$moduleName.'</b></p>
                                <p>Sous-Categorie   :<b>'.$submoduleName.'</b></p>  


                            </td>
                        </tr>
                    </tbody>
                </table>
                <table style="width:100%;max-width:620px;margin:0 auto">
                    <tbody>
                        <tr>
                            <td style="text-align:center!important">
                                <p>
                                   
                                </p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
    </tbody></table>';
        
        
        
        
        return $mailBody;
    }
    
    
    
    public function prepareMailBodyTicketCreation($ticketId, $mutualisteName,$agentName, $description, $moduleName, $submoduleName, $elapseTime){
        $mailBody = ' 
<table style="background:#f5f6fa;font-size:14px;line-height:22px;font-weight:400;color:#8094ae;width:100%;font-family:Century Gothic, sans-serif;">
    <tbody><tr>
            <td>
                <table style="width:100%;max-width:620px;margin:0 auto">
                    <tbody>
                        <tr>
                            <td style="text-align:center!important">
                                
                                <p style="font-size:13px;color:#6576ff;padding-top:12px"></p>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <table style="width:96%;max-width:620px;margin:0 auto;background:#ffffff">
                    <tbody>
                        <tr>
                            <td style="padding:2.75rem!important; font-family:Century Gothic, sans-serif; font-size:11px;"">


                                <p>Cher Mutualiste,</p>  
                                <p>Votre réclamation a été bien reçue et est enregistrée sous le numéro '.$ticketId.'.</p> 
                                <p>Elle sera traitée dans '.$elapseTime.' . Merci pour votre confiance et restons à votre <br>entière disposition. </p>

                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
    </tbody></table>';
              
        
        return $mailBody;
    }

    public function prepareMailBodyTicketCreationPrestataire($ticketId, $mutualisteName,$agentName, $description, $moduleName, $submoduleName, $elapseTime){
        $mailBody = ' 
<table style="background:#f5f6fa;font-size:14px;line-height:22px;font-weight:400;color:#8094ae;width:100%;font-family:Century Gothic, sans-serif;">
    <tbody><tr>
            <td>
                <table style="width:100%;max-width:620px;margin:0 auto">
                    <tbody>
                        <tr>
                            <td style="text-align:center!important">
                                
                                <p style="font-size:13px;color:#6576ff;padding-top:12px"></p>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <table style="width:96%;max-width:620px;margin:0 auto;background:#ffffff">
                    <tbody>
                        <tr>
                            <td style="padding:2.75rem!important; font-family:Century Gothic, sans-serif; font-size:11px;"">


                                <p>Cher Prestataire,</p>  
                                <p>Votre réclamation a été bien reçue et est enregistrée sous le numéro '.$ticketId.'.</p> 
                                <p>Elle sera traitée dans 45 jours. Merci pour votre confiance et restons à votre <br>entière disposition. </p>

                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
    </tbody></table>';
              
        
        return $mailBody;
    }
    
      
       
    public function prepareMailBodyTicketClosure($ticketId, $mutualisteName,$agentName, $description, $moduleName, $submoduleName, $elapseTime){
        $mailBody = ' 
<table style="background:#f5f6fa;font-size:14px;line-height:22px;font-weight:400;color:#8094ae;width:100%;font-family:Century Gothic, sans-serif;">
    <tbody><tr>
            <td>
                <table style="width:100%;max-width:620px;margin:0 auto">
                    <tbody>
                        <tr>
                            <td style="text-align:center!important">
                                
                                <p style="font-size:13px;color:#6576ff;padding-top:12px"></p>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <table style="width:96%;max-width:620px;margin:0 auto;background:#ffffff">
                    <tbody>
                        <tr>
                            <td style="padding:2.75rem!important; font-family:Century Gothic, sans-serif; font-size:11px;">



                                 <p>Cher Mutualiste,</p>  
                                <p>Votre réclamation référencée '.$ticketId.' a été traitée avec succès.</p> 
                                <p>Nous vous remercions pour votre confiance.</p>  


                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
    </tbody></table>';
        
        
        
        
        return $mailBody;
    }
/*
    public function prepareMailBodyClosureSatisfactionMessage($ticketId, $mutualisteName,$matricule,$agentName, $description, $moduleName, $submoduleName, $elapseTime){
        // Construire l'URL dynamique
    $baseUrl = "http://avisreclamations.mugef-ci.com:9010/";
    $queryParams = http_build_query([
        'ticket' => $ticketId,
        'firstname' => explode(' ', $mutualisteName)[0], 
        'lastname' => explode(' ', $mutualisteName)[1], 
        'matricule' => $matricule,
    ]);
    $dynamicUrl = $baseUrl . '?' . $queryParams;
        $mailBody = ' 
<table style="background:#f5f6fa;font-size:14px;line-height:22px;font-weight:400;color:#8094ae;width:100%;font-family:Century Gothic, sans-serif;">
    <tbody><tr>
            <td>
                <table style="width:100%;max-width:620px;margin:0 auto">
                    <tbody>
                        <tr>
                            <td style="text-align:center!important">
                                
                                <p style="font-size:13px;color:#6576ff;padding-top:12px"></p>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <table style="width:96%;max-width:620px;margin:0 auto;background:#ffffff">
                    <tbody>
                        <tr>
                            <td style="padding:2.75rem!important; font-family:Century Gothic, sans-serif; font-size:11px;">



                                 <p>Cher Mutualiste,</p>  
                                <p>Nous aimerions recueillir votre avis à la suite du traitement de votre réclamation pour améliorer nos services.</p>
                                <p>Pour répondre à notre enquête de satisfaction, veuillez cliquer sur le lien ci-dessous :</p>
                                <p><a href="' . $dynamicUrl . '" style="color:#6576ff; text-decoration:underline;" target="_blank">Donner mon avis</a></p>
                                <p>Merci pour votre collaboration.</p>


                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
    </tbody></table>';
        
        
        
        
        return $mailBody;
    }
*/
    
public function prepareMailBodyTicketCreationToService($ticketId, $mutualisteName,$agentName, $description, $moduleName, $submoduleName, $elapseTime){
    $mailBody = ' 
<table style="background:#f5f6fa;font-size:14px;line-height:22px;font-weight:400;color:#8094ae;width:100%;font-family:Century Gothic, sans-serif;">
<tbody><tr>
        <td>
            <table style="width:100%;max-width:620px;margin:0 auto">
                <tbody>
                    <tr>
                        <td style="text-align:center!important">
                            
                            <p style="font-size:13px;color:#6576ff;padding-top:12px"></p>
                        </td>
                    </tr>
                </tbody>
            </table>
            <table style="width:96%;max-width:620px;margin:0 auto;background:#ffffff">
                <tbody>
                    <tr>
                        <td style="padding:2.75rem!important; font-family:Century Gothic, sans-serif; font-size:11px;"">


                            <p>Bonjour/bonsoir '.$moduleName.' ,</p>  
                            <p>Vous avez une nouvelle réclamation en attente. Elle est enregistrée sous le numéro '.$ticketId.'.</p> 
                            <p>Elle devra être traitée dans '.$elapseTime.'. </p>

                        </td>
                    </tr>
                </tbody>
            </table>
        </td>
    </tr>
</tbody></table>';
          
    
    return $mailBody;
}

public function prepareMailBodyTicketClosureToService($ticketId, $mutualisteName,$agentName, $description, $moduleName, $submoduleName, $elapseTime){
    $mailBody = ' 
<table style="background:#f5f6fa;font-size:14px;line-height:22px;font-weight:400;color:#8094ae;width:100%;font-family:Century Gothic, sans-serif;">
<tbody><tr>
        <td>
            <table style="width:100%;max-width:620px;margin:0 auto">
                <tbody>
                    <tr>
                        <td style="text-align:center!important">
                            
                            <p style="font-size:13px;color:#6576ff;padding-top:12px"></p>
                        </td>
                    </tr>
                </tbody>
            </table>
            <table style="width:96%;max-width:620px;margin:0 auto;background:#ffffff">
                <tbody>
                    <tr>
                        <td style="padding:2.75rem!important; font-family:Century Gothic, sans-serif; font-size:11px;">



                             <p>Bonjour/bonsoir '.$moduleName.' ,</p>  
                            <p>La réclamation référencée '.$ticketId.' a été traitée avec succès.</p>   
                        </td>
                    </tr>
                </tbody>
            </table>
        </td>
    </tr>
</tbody></table>';
    
    
    
    
    return $mailBody;
}

public function prepareMailBodyClosureSatisfactionMessage($ticketId, $mutualisteName, $matricule, $agentName, $description, $moduleName, $submoduleName, $elapseTime) {
    // Construire l'URL dynamique
    $baseUrl = "http://avisreclamations.mugef-ci.com:9010/";

    // Gérer le cas où le nom contient un seul mot
    $nameParts = explode(' ', trim($mutualisteName));
    $firstname = isset($nameParts[0]) ? $nameParts[0] : '';
    $lastname = isset($nameParts[1]) ? $nameParts[1] : '';

    $dynamicUrl = $baseUrl . '?ticket=' . urlencode($ticketId) . 
                  '&firstname=' . urlencode($firstname) . 
                  '&lastname=' . urlencode($lastname) . 
                  '&matricule=' . urlencode($matricule);

    // Modèle de l'email
    $mailBody = '
<table style="background:#f5f6fa;font-size:14px;line-height:22px;font-weight:400;color:#8094ae;width:100%;font-family:Century Gothic, sans-serif;">
    <tbody>
        <tr>
            <td style="height:30px;"></td>
        </tr>
        <tr>
            <td>
                <table style="width:100%;max-width:620px;margin:0 auto;border-radius:8px;overflow:hidden;box-shadow:0 4px 6px rgba(0,0,0,0.1);background:#ffffff;">
                    <tbody>
                        <tr>
                            <td style="text-align:center;padding:20px 0;">
                                <img src="logo-small.png" alt="MUGEF-CI" style="max-width:100px;">
                            </td>
                        </tr>
                        <tr>
                            <td style="padding:2.5rem 2.5rem;font-family:Century Gothic, sans-serif;font-size:14px;color:#526484;line-height:1.8;">
                                <h2 style="font-size:18px;font-weight:600;color:#333333;margin-bottom:20px;text-align:center;">Enquête de Satisfaction</h2>
                                <p style="margin-bottom:15px;">Cher adhérent,</p>
                                <p style="margin-bottom:15px;">votre réclamation ' . $ticketId . ' a été traitée.</p>
                                <p style="margin-bottom:25px;">Votre avis nous intéresse sur ce traitement pour améliorer nos services. Répondre via ce lien </p>
                                <p style="text-align:center;margin-bottom:30px;">
                                    <a href="' . $dynamicUrl . '" style="background:#6576ff;color:#ffffff;padding:10px 20px;border-radius:5px;text-decoration:none;font-size:14px;font-weight:bold;">Donner mon avis</a>
                                </p>
                                <p style="margin-bottom:0;color:#999999;font-size:12px;text-align:center;">Merci pour votre collaboration.<br>MUGEF-CI</p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
        <tr>
            <td style="text-align:center;padding:20px 0;font-size:12px;color:#8094ae;">
                © ' . date("Y") . ' MUGEF-CI. Tous droits réservés.
            </td>
        </tr>
    </tbody>
</table>';

    return $mailBody;
}

    
}

?>