<?php
// include '/include/functions.php';
 date_default_timezone_set('America/Montreal');
// Récupération des données
$gateways = getLinkedGateways($logLines);

// Fichiers de log et stockage
$logGW = 'log/GWLog.log';
$connectedFile = 'log/connected_gateways.json';

    $ik = 0; // ********************************** Compte Init GW *********************************
    $DatapageLimiteGW = 10;

// Debut Couleur GW ----------  #< ? = $ BgColGW1; ? > ;  ---------
 require '/var/www/html/include/Themes.php';
// Fin Couleur GW  -------------------------------------------

// Fonction pour écrire dans le log texte
function logGatewayEvent($callsign, $event, $timestamp = null) {
    global $logGW;
    $StartDateTime = $timestamp ?? date('Y-m-d -- H:i:s');
    $logEntry = "[$StartDateTime] GW: $callsign - $event\n";
    file_put_contents($logGW, $logEntry, FILE_APPEND);
    chmod($logGW, 0664);
}

// Charger connexions précédentes
if (file_exists($connectedFile)) {
    $connected = json_decode(file_get_contents($connectedFile), true);
    if (!is_array($connected)) {
        $connected = [];
    }
} else {
    $connected = [];
}

// Extraire appels actuels
$currentCalls = [];
foreach ($gateways as $g) {
    $currentCalls[] = $g['callsign'];
}

// Nouveaux connectés
foreach ($currentCalls as $callsign) {
    // Trouver timestamp de cet appel actuel
    $timestamp = null;
    foreach ($gateways as $g) {
        if ($g['callsign'] === $callsign) {
            $timestamp = $g['timestamp'];
            break;
        }
    }
    if (!isset($connected[$callsign])) {
        $connected[$callsign] = $timestamp ?? date('Y-m-d -- H:i:s');
        logGatewayEvent($callsign, 'Start-Connect', $connected[$callsign]);
    }
}

// Déconnectés
foreach ($connected as $callsign => $startTimestamp) {
    if (!in_array($callsign, $currentCalls)) {
        logGatewayEvent($callsign, 'End-Connect');
        unset($connected[$callsign]);
    }
}

// Sauvegarder liste mise à jour
file_put_contents($connectedFile, json_encode($connected));

// Fonction formatage de la date en français
function formatDateFrenchGW($date) {
    // Ajustement du fuseau horaire -4h
    $dt = new DateTime($date, new DateTimeZone('UTC'));
    //  ***  $dt->modify('-4 hours'); //  ******************************************* UTC **************************

    $mois = [
        'January' => 'Janvier', 'February' => 'Février', 'March' => 'Mars', 
        'April' => 'Avril', 'May' => 'Mai', 'June' => 'Juin', 
        'July' => 'Juillet', 'August' => 'Août', 'September' => 'Septembre', 
        'October' => 'Octobre', 'November' => 'Novembre', 'December' => 'Décembre'
    ];
    $jours = [
        'Monday' => 'Lundi', 'Tuesday' => 'Mardi', 'Wednesday' => 'Mercredi', 
        'Thursday' => 'Jeudi', 'Friday' => 'Vendredi', 'Saturday' => 'Samedi', 
        'Sunday' => 'Dimanche'
    ];
//    $dateFormatted = $dt->format('H:i - l d F Y');
    $dateFormatted = $dt->format('H:i l d F Y');
    $dateFormatted = strtr($dateFormatted, $jours);
    $dateFormatted = strtr($dateFormatted, $mois);

    return $dateFormatted;
}
?>

<?php
function formatDateFrenchFR($dateString) {
    setlocale(LC_TIME, 'fr_CA.UTF-8');
    $timestamp = strtotime($dateString);
    return strftime('%A %d %B %Y, %H:%M', $timestamp);
}

?>
<!-- **                               ********  Affichage  ********                       ** -->
<div class="card" style="background-color: #<?= $BgColGW1; ?>; padding: 5px; box-shadow: 0px 0px 10px 3px #000; border-radius: 15px;">
   <div style="display: flex; justify-content: space-between; background-color: #<?= $BgColGW2; ?>; font-size: 1.25em; border-radius: 15px;">
  <div style="text-align: left; background-color: #<?= $BgColGW3; ?>; color: #<?= $TxtColGW1; ?>; font-size: 1.5em; text-shadow: 1px 1px 3px #000; padding: 20px; border-radius: 15px;">Passerelles YSF connectées</div>
  <div style="text-align: right; background-color: #<?= $BgColGW4; ?>; font-size: 1.2em; font-weight: bold; color: #<?= $TxtColGW2; ?>; padding: 20px; border-radius: 15px;"><?php echo formatDateFrenchGW3(date('H:i Y-m-d')); ?> -- (<?php echo TIMEZONE;?>)</div>
</div>
      <div class="table-responsive">
         <table id="gateways" class="table table-condensed" data-page-length="<?= $DatapageLimiteGW ?>" style="background-color: #<?= $BgColGW5; ?>;"><!--  **********  5 a 100 par page **********  -->
         <thead>
           <tr style="background-color: #<?= $BgColGW6; ?>;">
            <th style="color: #<?= $TxtColGW3; ?>; font-size: 1.35em;">Connectées Depuis  </th>
            <th style="color: #<?= $TxtColGW4; ?>; font-size: 1.25em;">Passerelle ( GW )</th>
            <th style="color: #<?= $TxtColGW5; ?>; font-size: 1.25em;">IP </th>
            <th style="color: #<?= $TxtColGW6; ?>; font-size: 1.25em;">Port </th>
            <th style="color: #<?= $TxtColGW7; ?>; font-size: 1.25em;">Durée </th>
           </tr>
         </thead>
            <tbody style="background-color: #<?= $BgColGW7; ?>;">
<?php foreach ($gateways as $gateway): ?>
<?php

    $ik = 1 +$ik; // ********************************* Compte GW ********************************

$line = $gateway['ipport'];
$parts = explode(': ', $line);
if (count($parts) === 3) {
    $callsignRaw = trim($parts[0]);
    $callsign = str_replace('0', '&Oslash;', $callsignRaw);
    $ipportInfo = trim($parts[1]); 
    $ipportParts = explode(' ', $ipportInfo);
    $ipPort = $ipportParts[0]; 
    list($ip, $port) = explode(':', $ipPort);
    $octets = explode('.', $ip);
    if (count($octets) === 4) {
        $ip_masked = $octets[0] . '.' . $octets[1] . '.' . $octets[2] . '.xxx';
    } else {
        $ip_masked = '! xxx.xxx.xxx.xxx !';
    }
    $startConnectDateRaw = trim($parts[2]);
    $startConnectDate = formatDateFrenchGW($startConnectDateRaw);

    // Calcul durée
    $now = time();// ****************************************  *****  *****  *****  *****  Probleme avec  $now = time()  *****  *****  *****  *****
    $dateTimeLocal = new DateTime('@' . $now);
    $timeZoneLocal = new DateTimeZone('UTC'); // ************ America/Montreal ***** UTC *************************  Probleme resolue ***********
    $dateTimeLocal->setTimezone($timeZoneLocal);

    $offsetSecondsLocal = $timeZoneLocal->getOffset($dateTimeLocal);
    $timestampStartUTC = strtotime($startConnectDateRaw);

    if ($offsetSecondsLocal < 0) {
        $timestampStart = $timestampStartUTC + $offsetSecondsLocal;
      } else {
        $timestampStart = $timestampStartUTC - $offsetSecondsLocal;
        }

  }  else {
        $callsignRaw = $callsign = '! No CallSign !';
        $ip_masked = '???';
        $port = '???';
        $startConnectDateRaw = date('Y-m-d H:i:s');
        $startConnectDate = 'Date inconnue';
        $timestampStart = '-?h -?m -?s';
      }

?>
<tr style='background-color: #<?= $BgColGW8; ?>; color: #<?= $TxtColGW8; ?>;'>
    <td data-order="<?php echo htmlspecialchars($startConnectDateRaw); ?>" style='color: #<?= $TxtColGW9; ?>; font-size: 1.3em;'><?php echo $ik; ?> ** <?php echo htmlspecialchars($startConnectDate); ?></td>
    <td><a target="_new" style="color: #<?= $TxtColGW10; ?>; font-size: 1.3em; font-weight: bold; text-shadow: 0px 0px 1px #000;" href="https://qrz.com/db/<?php echo htmlspecialchars($callsignRaw); ?>"><?php echo $callsign; ?></a></td>
    <td><a target="_new" style="color: #<?= $TxtColGW11; ?>; font-size: 1.2em;" href="https://mail.ip-address-lookup-v4.com/ip/<?php echo htmlspecialchars($ip); ?>"><?php echo $ip_masked; ?></a></td>
    <td style='color: #<?= $TxtColGW12; ?>; font-size: 1.2em;'><?php echo htmlspecialchars($port); ?></td>
    <td style='color: #<?= $TxtColGW13; ?>; font-size: 1.3em; font-weight: bold;'><span class="live-duration" data-start="<?php echo $timestampStart; ?>">--</span></td>
</tr>
<?php endforeach; ?>
            </tbody>
         </table>
<script>
function updateDurations() {
    const spans = document.querySelectorAll('.live-duration');
    spans.forEach(span => {
        const start = parseInt(span.getAttribute('data-start')) * 1000; // en ms
        const now = Date.now(); // ms
        let diff = Math.floor((now - start) / 1000); // secondes  ----**--**   font-weight: bold; **--**----

        const days = Math.floor(diff / 86400);
        diff = diff % 86400;
        const hours = Math.floor(diff / 3600);
        diff = diff % 3600;
        const minutes = Math.floor(diff / 60);
        const seconds = diff % 60;

        const formatted = 
            (days > 0 ? days + "j " : "") +
            (hours > 0 || days > 0 ? String(hours).padStart(2, '0') + "h " : "") +
            String(minutes).padStart(2, '0') + "m " +
            String(seconds).padStart(2, '0') + "s";

        span.textContent = formatted;
    });
}
setInterval(updateDurations, 1000);
updateDurations();

</script>

      </div>
      <script> <!-- asc desc  -->
         $(document).ready(function(){ 
            $('#gateways').dataTable( {
            "aaSorting": [[0,'desc']]
            } );
         });
      </script>
</div>
