<?php
// Page d'affichage des conversations clôturées (admin)
require_once __DIR__ . '/session-config.php';
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
$page_title = 'Conversations clôturées';
$current_page = 'support-chat-closed';
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/db.php';
$db = getDbConnection();

// Récupérer toutes les conversations clôturées (max 100)
$convs = $db->query("SELECT conversation_id, MAX(created_at) as last_msg, MAX(id) as last_id FROM support_chat WHERE closed = 1 GROUP BY conversation_id ORDER BY last_msg DESC LIMIT 100")->fetchAll(PDO::FETCH_ASSOC);
foreach($convs as &$conv){
    $row = $db->prepare("SELECT user_name FROM support_chat WHERE conversation_id = ? AND sender = 'user' ORDER BY created_at ASC LIMIT 1");
    $row->execute([$conv['conversation_id']]);
    $conv['user_name'] = ($row = $row->fetch(PDO::FETCH_ASSOC)) ? $row['user_name'] : '';
}

ob_start();
?>
<div class="container-xxl flex-grow-1 container-p-y">
  <div class="row justify-content-center">
    <div class="col-lg-10">
      <div class="card mb-4">
        <div class="card-header bg-danger text-white d-flex align-items-center">
          <h4 class="mb-0 me-3"><i class="fa fa-archive"></i> Conversations clôturées</h4>
        </div>
        <div class="card-body p-0" style="background:#f7f7f7;border-radius:0 0 12px 12px;">
          <div class="py-4">
            <?php if (empty($convs)): ?>
              <div class="text-muted">Aucune conversation clôturée.</div>
            <?php else: ?>
              <?php foreach ($convs as $conv): ?>
                <a href="chat.php?conv=<?php echo $conv['conversation_id']; ?>" class="d-block mb-2 p-2 bg-light rounded shadow-sm text-dark" style="text-decoration:none;position:relative;opacity:0.85;">
                  <span style="background:#dc3545;color:#fff;border-radius:12px;padding:2px 10px;font-size:0.95em;font-weight:600;margin-right:10px;vertical-align:middle;display:inline-block;">Clôturée</span>
                  <strong>Conversation #<?php echo $conv['conversation_id']; ?></strong>
                  <?php if($conv['user_name']): ?>
                    <span class="ms-2" style="font-weight:500;color:#007bff;"><?php echo htmlspecialchars($conv['user_name']); ?></span>
                  <?php endif; ?>
                  <span class="text-muted ms-2" style="font-size:0.9em;">Dernier message : <?php echo date('d/m/Y H:i', strtotime($conv['last_msg'])); ?></span>
                </a>
              <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<?php
$page_content = ob_get_clean();
include __DIR__ . '/template.php';
