<?php
// Page d'information application / abonnement
@session_start();

// Connexion base locale (compagnie spécifique)
include __DIR__.'/config/connexion.php'; // fournit $pdo (local) ou null

// Connexion base centrale pour expiration (utilise module gestion_compagnies)
require_once __DIR__.'/gestion_compagnies/config/connexion.php'; // fournit $gc_pdo

$appVersion = '1.0.0'; // TODO: mettre à jour si nécessaire
$agencyName = 'Agence';
$agencyRef  = isset($_SESSION['compagnie_ref']) ? $_SESSION['compagnie_ref'] : '';
$expirationDate = null;
$daysRemaining = null;
$statusLabel = 'Inconnu';

// Récupérer nom agence depuis base locale compagnie_table
if(isset($pdo) && $pdo instanceof PDO){
  try {
    $row = $pdo->query('SELECT compagnie_name, compagnie_ref FROM compagnie_table LIMIT 1')->fetch();
    if($row){
      $agencyName = $row['compagnie_name'] ?: $agencyName;
      if(empty($agencyRef) && !empty($row['compagnie_ref'])) $agencyRef = $row['compagnie_ref'];
    }
  } catch(Throwable $e){ /* silencieux */ }
}

// Récupérer date d'expiration abonnement dans base centrale (compagnies_table)
if($gc_pdo instanceof PDO && !empty($agencyRef)){
  try {
    // La colonne demandée: expiartion_date (orthographe fournie). On supporte aussi expiration_date si correction future.
    $stCols = $gc_pdo->query("SHOW COLUMNS FROM compagnies_table LIKE 'expiartion_date'");
    $colExists = (bool)$stCols->fetch();
    $colName = $colExists ? 'expiartion_date' : 'expiration_date';
    $st = $gc_pdo->prepare("SELECT $colName AS exp_date FROM compagnies_table WHERE compagnie_ref=? LIMIT 1");
    $st->execute([$agencyRef]);
    $expRow = $st->fetch();
    if($expRow && !empty($expRow['exp_date'])){
      $expirationDate = $expRow['exp_date'];
      $today = new DateTime('today');
      try { $expDT = new DateTime($expirationDate); } catch(Throwable $e){ $expDT=null; }
      if(isset($expDT)){
        $interval = (int)$today->diff($expDT)->format('%r%a');
        $daysRemaining = $interval; // peut être négatif
        if($interval < 0){ $statusLabel = 'Expiré'; }
        elseif($interval === 0){ $statusLabel = 'Expire aujourd\'hui'; }
        elseif($interval <= 7){
          $d = max(0,$interval);
          $statusLabel = 'Bientôt ('.$d.' jour'.($d>1?'s':'').' restants)';
        }
        else { $statusLabel = 'Actif'; }
      }
    }
  } catch(Throwable $e){ /* silencieux */ }
}

function h($s){ return htmlspecialchars($s??'',ENT_QUOTES,'UTF-8'); }
// Préparer données barre progression (base 365 jours)
$totalCycleDays = 365;
$progressPercent = null; $barClass='bg-secondary'; $progressDays = null; $realDaysDisplay = null;
if($daysRemaining !== null){
  $norm = $daysRemaining;
  if($norm < 0) $norm = 0; // expiré -> barre vide
  $capped = $norm;
  if($capped > $totalCycleDays) $capped = $totalCycleDays; // limiter largeur
  $progressDays = $capped; // utilisé pour largeur relative
  $progressPercent = round(($capped / $totalCycleDays) * 100,2);
  $realDaysDisplay = max(0,$daysRemaining); // valeur réelle (sans cap) affichée dans la barre (pas négative)
  if($daysRemaining <= 30){ $barClass='bg-danger'; }
  elseif($daysRemaining <= 182){ $barClass='bg-warning'; }
  else { $barClass='bg-success'; }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <title>Infos Application</title>
  <link rel="stylesheet" href="vendor/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="vendor/fontawesome-free/css/all.min.css">
  <link rel="stylesheet" href="css/ruang-admin.min.css">
  <style>
    .card-info{border-left:4px solid #4e73df;}
    .status-badge{padding:6px 14px;border-radius:20px;font-size:.85rem;font-weight:600;}
    .status-actif{background:linear-gradient(135deg,#1cc88a,#13855c);color:#fff;}
    .status-expire{background:linear-gradient(135deg,#e74a3b,#c0392b);color:#fff;}
    .status-soon{background:linear-gradient(135deg,#f6c23e,#dda20a);color:#212529;}
    .status-today{background:linear-gradient(135deg,#36b9cc,#258391);color:#fff;}
  .progress{height:14px; background:#e9ecef;}
  .progress-bar{font-size:10px; line-height:14px;}
  </style>
</head>
<body id="page-top">
<div id="wrapper">
  <?php include __DIR__.'/includes/sidebar.php'; ?>
  <div id="content-wrapper" class="d-flex flex-column">
    <div id="content">
      <?php include __DIR__.'/includes/topbar.php'; ?>
      <div class="container-fluid">
        <div class="d-sm-flex align-items-center justify-content-between mb-4">
          <h1 class="h3 mb-0 text-gray-800"><i class="fas fa-info-circle text-primary"></i> Infos Application</h1>
          <a href="dashboard.php" class="btn btn-sm btn-secondary"><i class="fas fa-home"></i> Dashboard</a>
        </div>
        <!-- Section À propos de l'application -->
        <div class="row">
          <div class="col-lg-12 mb-4">
            <div class="card shadow card-info">
              <div class="card-header py-2"><strong>À propos de l'application</strong></div>
              <div class="card-body">
                <ul class="list-unstyled mb-3">
                  <li><strong>Développeur :</strong> Youssef Lahrach</li>
                  <li><strong>Email :</strong> <a href="mailto:lahrach82@gmail.com">lahrach82@gmail.com</a></li>
                  <li><strong>WhatsApp :</strong> 
                    <a href="https://wa.me/212665446585" target="_blank" class="btn btn-success btn-sm" style="margin-left:8px;">
                      <i class="fab fa-whatsapp"></i> Contacter sur WhatsApp
                    </a>
                  </li>
                  <li><strong>Site :</strong> <a href="https://services-ae.net" target="_blank">https://services-ae.net</a></li>
                </ul>
                <small class="text-muted">Pour toute question, assistance ou évolution, contactez le développeur.</small>
              </div>
            </div>
          </div>
        </div>

        <div class="row">
          <div class="col-lg-12 mb-4">
            <div class="card shadow card-info">
              <div class="card-header py-2"><strong>Détails</strong></div>
              <div class="card-body">
                <?php if($daysRemaining !== null): ?>
                  <?php if($daysRemaining < 0): ?>
                    <div class="alert alert-danger py-2 mb-3 d-flex align-items-center justify-content-center text-center" style="min-height:60px;">
                      <i class="fas fa-exclamation-triangle mr-2"></i>
                      <span>Abonnement expiré. Veuillez renouveler immédiatement pour éviter l'interruption de service.</span>
                    </div>
                  <?php elseif($daysRemaining < 30): ?>
                    <div class="alert alert-danger py-2 mb-3 d-flex align-items-center justify-content-center text-center flex-wrap" style="min-height:60px;">
                      <i class="fas fa-bell mr-2"></i>
                      <span class="mb-1">Il reste <strong><?=h($daysRemaining)?></strong> jour(s) avant l'expiration de votre abonnement. Pensez au renouvellement.</span>
                      <div class="w-100"></div>
                      <a href="justificatif_paiement.php" class="btn btn-sm btn-light mt-1"><i class="fas fa-file-upload"></i> Envoyer justificatif paiement</a>
                    </div>
                  <?php endif; ?>
                <?php endif; ?>
                <table class="table table-sm mb-0">
                  <tbody>
                    <tr><th style="width:220px">Version Application</th><td><?=h($appVersion)?></td></tr>
                    <tr><th>Nom Agence</th><td><?=h($agencyName)?></td></tr>
                    <tr><th>Référence Agence</th><td><?=h($agencyRef ?: '-')?></td></tr>
                    <tr><th>Date Expiration Abonnement</th><td><?= $expirationDate? h(date('d/m/Y', strtotime($expirationDate))) : '<span class="text-muted">Non définie</span>'; ?></td></tr>
                    <tr><th>Jours Restants</th><td><?= $daysRemaining!==null? h($daysRemaining) : '<span class="text-muted">-</span>'; ?></td></tr>
                    <tr><th>Progression (0-365j)</th><td>
                      <?php if($progressPercent!==null): ?>
                        <div class="progress" title="<?=h($realDaysDisplay)?> jour(s) restants (largeur basée sur min(jours,365))">
                          <div class="progress-bar <?=$barClass?>" role="progressbar" style="width: <?=$progressPercent?>%;" aria-valuenow="<?=$progressPercent?>" aria-valuemin="0" aria-valuemax="100">
                            <?=h($realDaysDisplay)?> <?=($realDaysDisplay==1?'jour':'jours')?>
                          </div>
                        </div>
                      <?php else: ?>
                        <span class="text-muted">Indisponible</span>
                      <?php endif; ?>
                    </td></tr>
                    <tr><th>Statut</th><td>
                      <?php
                        $cls='status-actif';
                        if($statusLabel==='Expiré') $cls='status-expire';
                        elseif(strpos($statusLabel,'Bientôt (')===0) $cls='status-soon';
                        elseif($statusLabel==='Expire aujourd\'hui') $cls='status-today';
                      ?>
                      <span class="status-badge <?=$cls?>"><?=h($statusLabel)?></span>
                    </td></tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>

      </div>
    </div>
    <?php include __DIR__.'/includes/footer.php'; ?>
  </div>
</div>
<a class="scroll-to-top rounded" href="#page-top"><i class="fas fa-angle-up"></i></a>
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<script src="js/ruang-admin.min.js"></script>
</body>
</html>
