<?php
include_once __DIR__ . '/../config/connexion.php';
$subscription_days_remaining = null; $subscription_expired=false; $subscription_label='';
if(!empty($_SESSION['compagnie_ref'])){
  // Connexion base centrale pour date d'expiration
  $central = __DIR__.'/../gestion_compagnies/config/connexion.php';
  if(is_file($central)){
    require_once $central; // $gc_pdo
    if(isset($gc_pdo) && $gc_pdo instanceof PDO){
      try {
        $ref = $_SESSION['compagnie_ref'];
        $colCheck = $gc_pdo->query("SHOW COLUMNS FROM compagnies_table LIKE 'expiartion_date'")->fetch();
        $col = $colCheck? 'expiartion_date':'expiration_date';
        // Vérifier colonne validation_note
        $hasValNote = (bool)$gc_pdo->query("SHOW COLUMNS FROM compagnies_table LIKE 'validation_note'")->fetch();
        $selectCols = "$col AS exp, observation_support, compagnie_name".($hasValNote?", validation_note":"");
        $st = $gc_pdo->prepare("SELECT $selectCols FROM compagnies_table WHERE compagnie_ref=? LIMIT 1");
        $st->execute([$ref]);
        $payment_refused=false; $payment_observation=''; $payment_pending=false; $payment_validated_recent=false; $payment_agency_name=''; $validation_note_val=0;
        if($row=$st->fetch()){
          if(!empty($row['exp'])){
            $exp=$row['exp'];
            $todayYmd=date('Y-m-d');
            $subscription_days_remaining = (int)((new DateTime())->diff(new DateTime($exp)))->format('%r%a');
            if($exp < $todayYmd){ $subscription_expired=true; }
          }
          if(!empty($row['observation_support'])){ $payment_refused=true; $payment_observation=$row['observation_support']; }
          if(!empty($row['compagnie_name'])) $payment_agency_name=$row['compagnie_name'];
          if($hasValNote && isset($row['validation_note'])) $validation_note_val = (int)$row['validation_note'];
        }
        // Vérifier présence de fichiers en attente côté central (uploads)
        $pendingDir = realpath(__DIR__.'/../gestion_compagnies/files/uploads');
        if($pendingDir){
          $companyFolder = $pendingDir.DIRECTORY_SEPARATOR.$ref;
          if(is_dir($companyFolder)){
            foreach(scandir($companyFolder) as $f){ if($f==='.'||$f==='..') continue; if(is_file($companyFolder.DIRECTORY_SEPARATOR.$f)){ $payment_pending=true; break; } }
          }
        }
        // Notification validation basée sur validation_note (1=afficher) si colonne existe
        if(!$payment_refused && !$payment_pending && !$subscription_expired && $subscription_days_remaining !== null){
          if(isset($validation_note_val) && $validation_note_val === 1){
            $payment_validated_recent = true;
          }
        }
        if($subscription_days_remaining !== null){
          if($subscription_expired){ $subscription_label='Abonnement expiré'; }
          elseif($subscription_days_remaining < 30){ $subscription_label='Abonnement: '.$subscription_days_remaining.' '.'jour(s) restants'; }
        }
      } catch(Throwable $e){ /* ignore */ }
    }
  }
}
$safeConn = (isset($conn) && ($conn instanceof mysqli));
$today = date('Y-m-d');
// Nombre d'échéances à valider aujourd'hui
if ($safeConn) {
  $sqlAlert = "SELECT COUNT(*) AS total_echeance_today FROM receipts_table WHERE paiement_statut = 0 AND (UPPER(paiement_mode) = 'CHEQUE' OR UPPER(paiement_mode) = 'EFFET' OR UPPER(paiement_mode) = 'VIREMENT BANCAIRE') AND echeance_date = ?";
  $stmtAlert = $conn->prepare($sqlAlert);
  $stmtAlert->bind_param("s", $today);
  $stmtAlert->execute();
  $stmtAlert->bind_result($totalAlertCount);
  $stmtAlert->fetch();
  $total_echeance_today = $totalAlertCount !== null ? intval($totalAlertCount) : 0;
  $stmtAlert->close();
} else { $total_echeance_today = 0; }
// Nombre total d'échéances non validées (toutes dates)
if ($safeConn) {
  $sqlTotal = "SELECT COUNT(*) AS total_echeance_non_valide FROM receipts_table WHERE paiement_statut = 0 AND (UPPER(paiement_mode) = 'CHEQUE' OR UPPER(paiement_mode) = 'EFFET' OR UPPER(paiement_mode) = 'VIREMENT BANCAIRE')";
  $resTotal = $conn->query($sqlTotal);
  $rowTotal = $resTotal ? $resTotal->fetch_assoc() : null;
  $total_echeance_non_valide = $rowTotal && isset($rowTotal['total_echeance_non_valide']) ? intval($rowTotal['total_echeance_non_valide']) : 0;
} else { $total_echeance_non_valide = 0; }

// Appels Clients (phases 30,15,7,3,1) : clients à appeler si end_date dans 30 jours, pas finalisé, et prochaine date due
// Fenêtre portée à 30 jours; on n'affiche que si next_call_date est NULL (phase initiale) ou arrivée (<= aujourd'hui)
$dateLimit = date('Y-m-d', strtotime('+30 days'));
$sqlAppels = "SELECT COUNT(DISTINCT client_id) AS total_clients_a_appeler
              FROM policy_table
              WHERE client_id IS NOT NULL
                AND end_date BETWEEN CURDATE() AND ?
                AND (appel IS NULL OR appel = 0)
                AND (next_call_date IS NULL OR next_call_date <= ?);";
if ($safeConn) {
  $stmtAppels = $conn->prepare($sqlAppels);
  $stmtAppels->bind_param("ss", $dateLimit, $today);
  $stmtAppels->execute();
  $stmtAppels->bind_result($totalClientsAppeler);
  $stmtAppels->fetch();
  $total_clients_a_appeler = $totalClientsAppeler !== null ? intval($totalClientsAppeler) : 0;
  $stmtAppels->close();
} else { $total_clients_a_appeler = 0; }
// Appels Paiements Aujourd'hui (next_paiement = today & reste > 0)
if ($safeConn) {
  $total_clients_paiement_today = 0;
  // Vérifier colonne next_paiement
  $colChk = $conn->query("SHOW COLUMNS FROM policy_table LIKE 'next_paiement'");
  if ($colChk && $colChk->num_rows > 0) {
    $stmtPayCall = $conn->prepare("SELECT COUNT(DISTINCT client_id) AS nb FROM policy_table WHERE next_paiement = ? AND total_reste > 0.009");
    $stmtPayCall->bind_param('s', $today);
    $stmtPayCall->execute();
    $stmtPayCall->bind_result($nbPayCall);
    $stmtPayCall->fetch();
    $total_clients_paiement_today = $nbPayCall !== null ? (int)$nbPayCall : 0;
    $stmtPayCall->close();
  }
  if ($colChk) $colChk->close();
} else { $total_clients_paiement_today = 0; }
?>
<nav class="navbar navbar-expand navbar-light bg-navbar topbar mb-4 static-top">
  <button id="sidebarToggleTop" class="btn btn-link rounded-circle mr-3">
    <i class="fa fa-bars"></i>
  </button>
  <ul class="navbar-nav ml-auto">
    <?php if($subscription_expired): ?>
      <li class="nav-item mx-1">
        <span class="badge badge-danger" style="font-size:.75rem;">⚠ <?=$subscription_label?></span>
      </li>
    <?php elseif($subscription_days_remaining !== null && $subscription_days_remaining < 30): ?>
      <li class="nav-item mx-1">
        <a href="infos.php"><span class="badge badge-warning" style="font-size:.75rem; color:#000;">⏳ <?=$subscription_label?></span></a>
      </li>
    <?php endif; ?>
    <!-- Notifications combinées -->
    <!-- Notifications séparées -->
    <li class="nav-item dropdown no-arrow mx-1">
      <a class="nav-link dropdown-toggle" href="#" id="alertsDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        <i class="fas fa-bell fa-fw"></i>
        <?php
        // Compter les notifications : échéances, appels, rappels du jour
        $notif_count = 0;
    // Rappels du jour pour l'utilisateur connecté
        $rappels_jour_count = 0;
    // Rappels expirés pour l'utilisateur connecté
    $rappels_expire_count = 0;
        // Déterminer l'identité agent (fallback: nom complet puis email)
        $agent = null;
        if (!empty($_SESSION['user_name'])) {
            $agent = $_SESSION['user_name'];
        } elseif (!empty($_SESSION['first_name']) || !empty($_SESSION['last_name'])) {
            $agent = trim(($_SESSION['first_name'] ?? '') . ' ' . ($_SESSION['last_name'] ?? ''));
        } elseif (!empty($_SESSION['user_email'])) {
            $agent = $_SESSION['user_email'];
        }
        if ($agent && $safeConn) {
          // Rappels aujourd'hui (uniquement utilisateur connecté)
          $stmtRappels = $conn->prepare("SELECT COUNT(*) AS nb FROM rappels_table WHERE agent = ? AND date_rappel = ?");
          $stmtRappels->bind_param("ss", $agent, $today);
          $stmtRappels->execute();
          $stmtRappels->bind_result($nbRappels);
          $stmtRappels->fetch();
          $rappels_jour_count = $nbRappels !== null ? intval($nbRappels) : 0;
          $stmtRappels->close();
          // Rappels expirés (uniquement utilisateur connecté)
          $stmtRappelsExp = $conn->prepare("SELECT COUNT(*) AS nb FROM rappels_table WHERE agent = ? AND date_rappel < ?");
          $stmtRappelsExp->bind_param("ss", $agent, $today);
          $stmtRappelsExp->execute();
          $stmtRappelsExp->bind_result($nbRappelsExp);
          $stmtRappelsExp->fetch();
          $rappels_expire_count = $nbRappelsExp !== null ? intval($nbRappelsExp) : 0;
          $stmtRappelsExp->close();
        }
  if ($total_echeance_today > 0) $notif_count++;
  if ($total_clients_a_appeler > 0) $notif_count++;
  if (!empty($total_clients_paiement_today) && $total_clients_paiement_today > 0) $notif_count++;
        if ($rappels_jour_count > 0) $notif_count++;
  // Rappels expirés (déjà comptés pour utilisateur connecté)
  $expired_for_display_count = $rappels_expire_count;
  $show_expired_notif = ($expired_for_display_count > 0);
  if ($show_expired_notif) $notif_count++;
  // Paiement (justificatifs) : refus / en attente / validation récente
  if(!empty($payment_refused)) $notif_count++;
  elseif(!empty($payment_pending)) $notif_count++;
  elseif(!empty($payment_validated_recent)) $notif_count++;
        ?>
        <?php if ($notif_count > 0): ?>
          <span class="badge badge-danger badge-counter"><?php echo $notif_count; ?></span>
        <?php endif; ?>
      </a>
      <div class="dropdown-list dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="alertsDropdown">
        <h6 class="dropdown-header">Notifications</h6>
        <!-- Échéances -->
        <?php if ($total_echeance_today > 0): ?>
          <a class="dropdown-item d-flex align-items-center" href="echeances_aujourdhui.php">
            <div class="mr-3">
              <div class="icon-circle bg-warning">
                <i class="fas fa-exclamation-triangle text-white"></i>
              </div>
            </div>
            <div>
              <div class="small text-gray-500"><?php echo date('d/m/Y'); ?></div>
              <span class="font-weight-bold">Il y a <?php echo $total_echeance_non_valide; ?> échéance(s) non validée(s) à traiter</span>
            </div>
          </a>
        <?php endif; ?>
        <!-- Rappels du jour -->
        <?php if ($rappels_jour_count > 0): ?>
          <a class="dropdown-item d-flex align-items-center" href="rappels_jour.php">
            <div class="mr-3">
              <div class="icon-circle bg-primary">
                <i class="fas fa-bell text-white"></i>
              </div>
            </div>
            <div>
              <div class="small text-gray-500"><?php echo date('d/m/Y'); ?></div>
              <span class="font-weight-bold">Vous avez <?php echo $rappels_jour_count; ?> tache(s) à effectuer aujourd'hui</span>
            </div>
          </a>
        <?php endif; ?>
        <!-- Rappels expirés -->
    <?php if (!empty($show_expired_notif)): ?>
          <a class="dropdown-item d-flex align-items-center" href="rappels.php?filter=expired">
            <div class="mr-3">
              <div class="icon-circle bg-danger">
                <i class="fas fa-exclamation-circle text-white"></i>
              </div>
            </div>
            <div>
              <div class="small text-gray-500"><?php echo date('d/m/Y'); ?></div>
      <span class="font-weight-bold">Vous avez <?php echo $expired_for_display_count; ?> rappel(s) expiré(s)</span>
            </div>
          </a>
        <?php endif; ?>
        <!-- Appels Clients -->
    <?php if ($total_clients_a_appeler > 0): ?>
          <a class="dropdown-item d-flex align-items-center" href="appels.php">
            <div class="mr-3">
              <div class="icon-circle bg-info">
                <i class="fas fa-phone-alt text-white"></i>
              </div>
            </div>
            <div>
              <div class="small text-gray-500"><?php echo date('d/m/Y'); ?></div>
      <span class="font-weight-bold">Il y a <?php echo $total_clients_a_appeler; ?> appel(s) pour Renouvellement de Police</span>
            </div>
          </a>
        <?php endif; ?>
        <?php if ($notif_count === 0): ?>
          <span class="dropdown-item text-muted small">Aucune notification pour aujourd'hui.</span>
        <?php endif; ?>
        <!-- Paiement refusé -->
        <?php if(!empty($payment_refused)): ?>
          <a class="dropdown-item d-flex align-items-center" href="justificatif_paiement.php">
            <div class="mr-3"><div class="icon-circle bg-danger"><i class="fas fa-times text-white"></i></div></div>
            <div>
              <div class="small text-gray-500">Paiement</div>
              <span class="font-weight-bold">Justificatif refusé</span>
              <?php if($payment_observation): ?><div class="text-muted small" style="max-width:240px;white-space:normal;">Motif: <?=htmlspecialchars(mb_strimwidth($payment_observation,0,120,'…','UTF-8'));?></div><?php endif; ?>
            </div>
          </a>
        <?php elseif(!empty($payment_pending)): ?>
          <!-- Paiement en attente -->
          <a class="dropdown-item d-flex align-items-center" href="justificatif_paiement.php">
            <div class="mr-3"><div class="icon-circle bg-warning"><i class="fas fa-hourglass-half text-white"></i></div></div>
            <div>
              <div class="small text-gray-500">Paiement</div>
              <span class="font-weight-bold">Justificatifs en cours de validation</span>
            </div>
          </a>
        <?php elseif(!empty($payment_validated_recent)): ?>
          <!-- Paiement validé récemment -->
          <a class="dropdown-item d-flex align-items-center payment-validated-item" data-payment-validated-item="1" href="mark_payment_validated_seen.php?redirect=infos.php">
            <div class="mr-3"><div class="icon-circle bg-success"><i class="fas fa-check text-white"></i></div></div>
            <div>
              <div class="small text-gray-500">Paiement</div>
              <span class="font-weight-bold">Paiement validé (expiration prolongée)</span>
            </div>
          </a>
        <?php endif; ?>
        <!-- Appels Paiements Aujourd'hui -->
        <?php if (!empty($total_clients_paiement_today) && $total_clients_paiement_today > 0): ?>
          <a class="dropdown-item d-flex align-items-center" href="appels_paiements_aujourdhui.php">
            <div class="mr-3">
              <div class="icon-circle bg-info">
                <i class="fas fa-coins text-white"></i>
              </div>
            </div>
            <div>
              <div class="small text-gray-500"><?php echo date('d/m/Y'); ?></div>
              <span class="font-weight-bold">Il y a<?php echo $total_clients_paiement_today; ?> client(s) à appeler pour paiement</span>
            </div>
          </a>
        <?php endif; ?>
        <!-- Suppression des liens "Voir toutes les échéances/appels" -->
      </div>
    </li>
    <div class="topbar-divider d-none d-sm-block"></div>
    <li class="nav-item dropdown no-arrow">
      <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        <img class="img-profile rounded-circle" src="img/boy.png" style="max-width: 60px">
        <?php
        if (empty($_SESSION['user_name']) && (!empty($_SESSION['first_name']) || !empty($_SESSION['last_name']))) {
          $_SESSION['user_name'] = trim(($_SESSION['first_name'] ?? '').' '.($_SESSION['last_name'] ?? ''));
        }
        $__uname = !empty($_SESSION['user_name']) ? $_SESSION['user_name'] : 'Guest';
        echo '<span class="ml-2 d-none d-lg-inline text-white small">' . htmlspecialchars($__uname) . '</span>';
        ?>
      </a>
      <div class="dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="userDropdown">
        <a class="dropdown-item" href="profile.php">
          <i class="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i>
          Mon Profil
        </a>
        <a class="dropdown-item" href="edit_profile.php">
          <i class="fas fa-edit fa-sm fa-fw mr-2 text-gray-400"></i>
          Modifier Profil
        </a>
        <a class="dropdown-item" href="change_password.php">
          <i class="fas fa-key fa-sm fa-fw mr-2 text-gray-400"></i>
          Changer Mot de Passe
        </a>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="javascript:void(0);" data-toggle="modal" data-target="#logoutModal">
          <i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
          Déconnexion
        </a>
      </div>
    </li>
  </ul>
</nav>
<script>
document.addEventListener('DOMContentLoaded', function(){
  var pv = document.querySelector('[data-payment-validated-item]');
  if(pv){
    pv.addEventListener('click', function(){
      var badge = this.closest('li.nav-item.dropdown').querySelector('.badge-counter');
      if(badge){
        var n = parseInt(badge.textContent.trim(),10); if(!isNaN(n) && n>0){ n--; badge.textContent = n>0? n : ''; if(n<=0) badge.style.display='none'; }
      }
      setTimeout(()=>{ this.parentNode && this.parentNode.removeChild(this); },50);
    });
  }
});
</script>
<!-- Modal avertissement inactivité -->
<div class="modal fade" id="sessionTimeoutModal" tabindex="-1" role="dialog" aria-labelledby="sessionTimeoutLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header bg-warning">
        <h5 class="modal-title" id="sessionTimeoutLabel"><i class="fas fa-hourglass-half"></i> Inactivité détectée</h5>
      </div>
      <div class="modal-body">
  <p>Aucune activité depuis 5 minutes. Vous allez être déconnecté dans <strong><span id="sessionCountdown">30</span>s</strong>.</p>
        <p class="mb-0">Cliquez sur <strong>Rester connecté</strong> pour prolonger votre session.</p>
      </div>
      <div class="modal-footer justify-content-center">
        <button type="button" class="btn btn-primary px-4" id="stayLoggedBtn"><i class="fas fa-sync"></i> Rester connecté</button>
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  const INACTIVITY_LIMIT_MS = 5 * 60 * 1000; // 5 min avant affichage modal
  const COUNTDOWN_SECONDS = 30;              // 30s avant déconnexion
  const logoutUrl = 'logout.php';
  let inactivityTimer = null;
  let countdownVisible = false;
  let countdownEndTs = 0; // timestamp absolu (ms)
  let ticking = false;

  function now(){ return Date.now(); }

  function resetInactivityTimer(){
    if(countdownVisible) return;
    if(inactivityTimer) clearTimeout(inactivityTimer);
    inactivityTimer = setTimeout(showCountdown, INACTIVITY_LIMIT_MS);
  }

  function showCountdown(){
    countdownVisible = true;
    countdownEndTs = now() + COUNTDOWN_SECONDS*1000;
    updateCountdownDisplay();
    showInactivityModal();
    tickCountdown();
  }

  function tickCountdown(){
    if(!countdownVisible) return;
    const remainingSec = Math.max(0, Math.ceil((countdownEndTs - now())/1000));
    updateCountdownDisplay(remainingSec);
    if(remainingSec <= 0){
      window.location.href = logoutUrl;
      return;
    }
    if(!ticking){
      ticking = true;
      setTimeout(()=>{ ticking=false; tickCountdown(); }, 500); // recalcul 2x par seconde
    }
  }

  // Recalcul immédiat quand l'onglet redevient actif
  document.addEventListener('visibilitychange', function(){
    if(!document.hidden && countdownVisible){ tickCountdown(); }
  });

  function showInactivityModal(){
    let attempts = 0;
    function tryShow(){
      if(typeof $ !== 'undefined' && $('#sessionTimeoutModal').modal){
        $('#sessionTimeoutModal').modal('show');
      } else if(attempts < 10){ attempts++; setTimeout(tryShow,200); }
      else { alert("Inactivité détectée: vous serez déconnecté dans 30s"); }
    }
    tryShow();
  }

  function updateCountdownDisplay(val){
    const el = document.getElementById('sessionCountdown');
    if(el && typeof val!=='undefined') el.textContent = val;
  }

  function stayLogged(){
    countdownVisible = false;
    fetch('session_ping.php?ts='+now()).catch(()=>{});
    if(typeof $ !== 'undefined' && $('#sessionTimeoutModal').modal){ $('#sessionTimeoutModal').modal('hide'); }
    resetInactivityTimer();
  }

  function cancelOnActivity(){
    if(countdownVisible) return; // laisser expirer si déjà affiché
    resetInactivityTimer();
  }

  ['mousemove','keydown','click','scroll','touchstart'].forEach(evt=>{
    window.addEventListener(evt,cancelOnActivity,{passive:true});
  });

  document.addEventListener('DOMContentLoaded', function(){
    resetInactivityTimer();
    const btn = document.getElementById('stayLoggedBtn');
    if(btn) btn.addEventListener('click', stayLogged);
    if(typeof $ !== 'undefined'){
      $('#sessionTimeoutModal').on('hidden.bs.modal', function(){
        if(countdownVisible){ // Fermeture manuelle => on annule la déconnexion
          countdownVisible=false; resetInactivityTimer();
        }
      });
    }
  });
})();
</script>