<?php
// Redirection si abonnement expiré
if (session_status() === PHP_SESSION_NONE) { @session_start(); }

$script = basename($_SERVER['SCRIPT_NAME']);
$skipPages = [
  'login.php','logout.php','abonnement_expire.php','verify-code.php','reset-password.php','forgot-password.php'
];
// Ne pas exécuter dans l'espace gestion_compagnies
if(strpos(__DIR__, 'gestion_compagnies') !== false){ return; }
if (in_array($script,$skipPages)) { return; }

if (!empty($_SESSION['compagnie_ref'])) {
  // Connexion base centrale
  $centralConnFile = __DIR__.'/../gestion_compagnies/config/connexion.php';
  if (is_file($centralConnFile)) {
    require_once $centralConnFile; // fournit $gc_pdo
    if (isset($gc_pdo) && $gc_pdo instanceof PDO) {
      try {
        $ref = $_SESSION['compagnie_ref'];
        $col = 'expiartion_date';
        $hasCol = $gc_pdo->query("SHOW COLUMNS FROM compagnies_table LIKE 'expiartion_date'")->fetch();
        if(!$hasCol){ $col = 'expiration_date'; }
        $st = $gc_pdo->prepare("SELECT $col AS exp FROM compagnies_table WHERE compagnie_ref=? LIMIT 1");
        $st->execute([$ref]);
        $row = $st->fetch();
        if($row && !empty($row['exp'])){
          $exp = $row['exp'];
          $today = date('Y-m-d');
          if ($exp < $today) {
            header('Location: abonnement_expire.php');
            exit;
          }
        }
      } catch(Throwable $e){ /* silencieux */ }
    }
  }
}
?>
