<?php
// Support Chat admin page
require_once __DIR__ . '/session-config.php';
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
// Traitement de la réponse admin (nouvelle structure)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['conversation_id'], $_POST['admin_reply'])) {
  require_once __DIR__ . '/../config/db.php';
  $db = getDbConnection();
  $conversation_id = intval($_POST['conversation_id']);
  $admin_reply = trim($_POST['admin_reply']);
  // Récupérer le nom personnalisé de l'admin (support_name)
  $admin_name = isset($_SESSION['admin_support_name']) && strlen(trim($_SESSION['admin_support_name'])) > 0
    ? $_SESSION['admin_support_name']
    : 'Agent';
  if ($conversation_id && $admin_reply) {
    $stmt = $db->prepare("INSERT INTO support_chat (conversation_id, sender, user_name, message, created_at) VALUES (?, 'admin', ?, ?, NOW())");
    $stmt->execute([$conversation_id, $admin_name, $admin_reply]);
    header('Location: chat.php?conv=' . $conversation_id);
    exit;
  }
}
$page_title = 'Support Chat';
$current_page = 'support-chat';
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/db.php';
$db = getDbConnection();
$row = $db->query('SELECT enabled_chat FROM smtp_config WHERE id=1')->fetch(PDO::FETCH_ASSOC);
$enabled_chat = !empty($row) ? $row['enabled_chat'] : '0';

// Traitement du switch
// Traitement du switch
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $new_status = isset($_POST['toggle_chat']) && $_POST['toggle_chat'] === '1' ? '1' : '0';
  $db->prepare('UPDATE smtp_config SET enabled_chat=? WHERE id=1')->execute([$new_status]);
  // Forcer le rechargement pour afficher le bon état
  header('Location: chat.php');
  exit;
}

// Gestion de la clôture de conversation
if (isset($_GET['close_conv'])) {
  $close_id = intval($_GET['close_conv']);
  $db->prepare("UPDATE support_chat SET closed=1 WHERE conversation_id = ?")->execute([$close_id]);
  header('Location: chat.php');
  exit;
}
$conversation_id = isset($_GET['conv']) ? intval($_GET['conv']) : 0;
if ($conversation_id) {
  $messages = $db->prepare("SELECT * FROM support_chat WHERE conversation_id = ? ORDER BY created_at ASC");
  $messages->execute([$conversation_id]);
  $messages = $messages->fetchAll(PDO::FETCH_ASSOC);
} else {
  // Liste des conversations (affichage par défaut)
  $convs = $db->query("SELECT conversation_id, MAX(created_at) as last_msg, MAX(id) as last_id FROM support_chat GROUP BY conversation_id ORDER BY last_msg DESC LIMIT 100")->fetchAll(PDO::FETCH_ASSOC);
  // Récupérer le nom du client et si la conversation est en attente (aucune réponse admin)
  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'] : '';
    $row2 = $db->prepare("SELECT 1 FROM support_chat WHERE conversation_id = ? AND sender = 'admin' LIMIT 1");
    $row2->execute([$conv['conversation_id']]);
    $conv['pending'] = !$row2->fetch(PDO::FETCH_ASSOC);
    $row3 = $db->prepare("SELECT closed FROM support_chat WHERE conversation_id = ? ORDER BY id DESC LIMIT 1");
    $row3->execute([$conv['conversation_id']]);
    $conv['closed'] = ($row3 = $row3->fetch(PDO::FETCH_ASSOC)) ? intval($row3['closed']) : 0;
  }
  $messages = [];
}

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-primary text-white d-flex align-items-center" style="position:relative;">
          <h4 class="mb-0 me-3"><i class="fa fa-comments"></i> Support Chat - Clients
            <!-- Switch activation widget chat -->
            <form method="post" style="display:inline-block;margin-left:24px;vertical-align:middle;">
              <div class="form-check form-switch" style="display:inline-block;">
                <input class="form-check-input" type="checkbox" id="toggle_chat" name="toggle_chat" value="1" <?php echo ($enabled_chat == '1') ? 'checked' : ''; ?> onchange="this.form.submit();">
                <label class="form-check-label" for="toggle_chat">Widget chat <?php echo ($enabled_chat == '1') ? 'activé' : 'désactivé'; ?></label>
              </div>
            </form>
          </h4>
          <!-- Le badge du nom personnalisé est déjà affiché dans le titre, on évite le doublon ici -->
          <?php // Afficher la liste toujours, même si une conversation est sélectionnée
          ?>
            <div id="pendingConvList" style="display:none;position:absolute;top:54px;left:40px;z-index:1000;background:#fff;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.12);padding:16px 18px;min-width:260px;">
              <div style="font-weight:600;color:#ffc107;margin-bottom:8px;">Conversations en attente :</div>
              <?php if($pendingCount == 0): ?>
                <div style="color:#888;font-size:0.98em;">Aucune conversation en attente.</div>
              <?php else: ?>
                <?php foreach($pendingConvs as $pc): ?>
                  <div style="margin-bottom:8px;">
                    <a href="chat.php?conv=<?php echo $pc['conversation_id']; ?>" style="color:#007bff;font-weight:500;text-decoration:none;">
                      <?php echo htmlspecialchars($pc['user_name'] ?: 'Utilisateur'); ?> (#<?php echo $pc['conversation_id']; ?>)
                    </a>
                  </div>
                <?php endforeach; ?>
              <?php endif; ?>
            </div>
            <script>
              document.addEventListener('DOMContentLoaded', function(){
                var btn = document.getElementById('pendingConvBtn');
                var list = document.getElementById('pendingConvList');
                if(btn && list){
                  btn.addEventListener('click', function(e){
                    list.style.display = (list.style.display === 'none' || !list.style.display) ? 'block' : 'none';
                  });
                  document.addEventListener('click', function(e){
                    if(!btn.contains(e.target) && !list.contains(e.target)){
                      list.style.display = 'none';
                    }
                  });
                }
              });
            </script>
          
        </div>
  <div class="card-body p-0" style="background:#f7f7f7;border-radius:0 0 12px 12px;">
  <div id="chat-messages" style="max-height:380px;overflow-y:auto;padding:16px 12px 12px 12px;">
          <?php if ($conversation_id && empty($messages)): ?>
            <div class="text-center py-4 text-muted">Aucune conversation pour ce client.</div>
          <?php elseif (!$conversation_id): ?>
            <div class="py-4">
              <h5 class="mb-3">Sélectionnez une conversation :</h5>
              <?php foreach ($convs as $conv): ?>
                <?php
                  // Exclure les conversations clôturées et manquées
                  // Manquée = email_send=1 et aucune réponse admin
                  $isMissed = false;
                  if ($conv['pending']) {
                    // Vérifier si email_send=1 pour cette conversation
                    $stmtMissed = $db->prepare("SELECT email_send FROM support_chat WHERE conversation_id = ? ORDER BY id DESC LIMIT 1");
                    $stmtMissed->execute([$conv['conversation_id']]);
                    $rowMissed = $stmtMissed->fetch(PDO::FETCH_ASSOC);
                    $isMissed = $rowMissed && intval($rowMissed['email_send']) === 1;
                  }
                  if(!$conv['closed'] && !$isMissed):
                ?>
                  <a href="chat.php?conv=<?php echo $conv['conversation_id']; ?>" class="d-block mb-2 p-2 bg-white rounded shadow-sm text-dark" style="text-decoration:none;position:relative;">
                    <?php if($conv['pending']): ?>
                      <span title="En attente de réponse" style="position:absolute;left:8px;top:8px;font-size:1.2em;color:#ffc107;display:inline-block;"><i class="iconify" data-icon="mdi:clock-outline"></i></span>
                    <?php endif; ?>
                    <strong style="margin-left:<?php echo $conv['pending'] ? '28px':'0'; ?>;">Conversation #<?php echo $conv['conversation_id']; ?></strong>
                    <?php if($conv['pending']): ?>
                      <span style="background:#ffc107;color:#fff;border-radius:12px;padding:2px 10px;font-size:0.95em;font-weight:600;margin-left:10px;vertical-align:middle;display:inline-block;">En attente</span>
                    <?php endif; ?>
                    <?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 endif; ?>
              <?php endforeach; ?>
            </div>

            <!-- Conversations clôturées supprimées : rien à afficher ici -->
          <?php else: ?>
            <?php foreach ($messages as $msg): ?>
              <?php if ($msg['sender'] === 'user'): ?>
                <div class="d-flex mb-3 align-items-end">
                  <span class="badge bg-primary text-white me-2" style="font-size:0.72em;font-weight:500;padding:4px 10px;border-radius:12px;">
                    <?php echo htmlspecialchars($msg['user_name'] ?: 'Utilisateur'); ?>
                  </span>
                  <div style="max-width:70%;">
                    <div style="background:#f1f0f0;border-radius:16px 16px 16px 4px;padding:10px 16px;color:#222;box-shadow:0 1px 2px rgba(0,0,0,0.04);">
                      <?php echo nl2br(htmlspecialchars($msg['message'])); ?>
                    </div>
                    <div class="text-muted" style="font-size:0.85em;margin-top:2px;">
                      <?php echo date('d/m/Y H:i', strtotime($msg['created_at'])); ?>
                    </div>
                  </div>
                </div>
              <?php else: ?>
                <div class="d-flex mb-3 justify-content-end align-items-end">
                  <div style="max-width:70%;">
                    <div style="background:#d1f5e0;border-radius:16px 16px 4px 16px;padding:10px 16px;color:#155724;box-shadow:0 1px 2px rgba(0,0,0,0.04);text-align:right;">
                      <?php echo nl2br(htmlspecialchars($msg['message'])); ?>
                    </div>
                    <div class="text-muted" style="font-size:0.85em;margin-top:2px;text-align:right;">
                      <?php echo date('d/m/Y H:i', strtotime($msg['created_at'])); ?>
                    </div>
                  </div>
                  <span class="badge bg-success text-white ms-2" style="font-size:0.72em;font-weight:500;padding:4px 10px;border-radius:12px;">
                    <?php 
                    if ($msg['sender'] === 'admin') {
                      // Affiche le nom stocké dans la base pour ce message (user_name), sinon la session
                      echo htmlspecialchars($msg['user_name'] && strtolower($msg['user_name']) !== 'admin' ? $msg['user_name'] : (isset($_SESSION['admin_support_name']) && strlen(trim($_SESSION['admin_support_name'])) > 0 ? $_SESSION['admin_support_name'] : 'Agent'));
                    } else {
                      echo htmlspecialchars($msg['user_name'] && strtolower($msg['user_name']) !== 'admin' ? $msg['user_name'] : 'Agent');
                    }
                    ?>
                  </span>
                </div>
              <?php endif; ?>
            <?php endforeach; ?>
          <?php endif; ?>
    </div>
  </div>
      </div>
    </div>
  </div>

<?php if ($conversation_id): ?>
<form id="adminChatForm" method="post" action="chat.php?conv=<?php echo $conversation_id; ?>" style="position:sticky;bottom:0;left:0;right:0;z-index:10;background:#fff;padding:16px 0 0 0;box-shadow:0 -2px 8px rgba(0,0,0,0.04);margin-top:-16px;">
  <div class="container-xxl">
    <div class="row justify-content-center">
      <div class="col-lg-10">
        <div class="input-group" style="align-items:center;">
          <input type="hidden" name="conversation_id" value="<?php echo $conversation_id; ?>">
          <!-- Bouton retour à la liste des messages -->
          <a href="chat.php" class="btn btn-light me-2" style="border-radius:8px;padding:0 14px;height:38px;min-width:38px;max-width:38px;display:flex;align-items:center;justify-content:center;" title="Retour à la liste">
            <i class="ri ri-list-check" style="font-size:1.5rem;color:#696cff;"></i>
          </a>
          <!-- Bouton clôturer à gauche -->
          <button class="btn btn-danger me-2" type="button" id="closeConvBtn" style="border-radius:8px;padding:0 14px;height:38px;min-width:38px;max-width:120px;display:flex;align-items:center;justify-content:center;font-weight:600;" title="Clôturer la conversation">
            <i class="fa fa-times me-1"></i> Clôturer
          </button>
          <textarea name="admin_reply" class="form-control" placeholder="Écrire une réponse..." required style="resize:none;min-height:38px;max-height:60px;"></textarea>
          <button class="btn p-0 border-0 bg-transparent" type="submit" style="height:38px;width:38px;display:flex;align-items:center;justify-content:center;" title="Envoyer">
            <i class="ri ri-send-plane-2-fill" style="font-size:2rem;color:#696cff;transition:color 0.2s;"></i>
          </button>
          <style>
            #adminChatForm .ri-send-plane-2-fill:hover {
              color: #5a5fe7;
            }
          </style>
        </div>
      </div>
    </div>
  </div>
</form>
<script>
document.addEventListener('DOMContentLoaded', function(){
  var form = document.getElementById('adminChatForm');
  var textarea = form.querySelector('textarea[name="admin_reply"]');
  // Focus après envoi
  form.addEventListener('submit', function(e){
    setTimeout(function(){ textarea.value = ''; textarea.focus(); }, 100);
  });
  // Envoi par Enter, retour à la ligne avec Shift+Enter
  textarea.addEventListener('keydown', function(e){
    if(e.key === 'Enter'){
      if(e.shiftKey){
        // Retour à la ligne
        return;
      }else{
        e.preventDefault();
        form.submit();
      }
    }
  });

  // Bouton clôture conversation
  var closeBtn = document.getElementById('closeConvBtn');
  if(closeBtn){
    closeBtn.addEventListener('click', function(){
      if(confirm('Voulez-vous vraiment clôturer cette conversation ?')){
        window.location.href = 'chat.php?close_conv=<?php echo $conversation_id; ?>';
      }
    });
  }
});
</script>
<?php endif; ?>
<?php
$page_content = ob_get_clean();

// JS spécifique (optionnel)

$page_js = 'document.addEventListener("DOMContentLoaded", function(){
  var chatBody = document.getElementById("chat-messages");
  if(chatBody) {
    chatBody.scrollTop = chatBody.scrollHeight;
  }

  // Rafraîchissement automatique des messages (polling AJAX)
  var conversationId = (typeof window.conversation_id !== "undefined" ? window.conversation_id : (document.querySelector("input[name=conversation_id]") ? document.querySelector("input[name=conversation_id]").value : ""));
  if(conversationId){
    setInterval(function(){
      fetch("chat.php?conv="+conversationId+"&ajax=1")
        .then(function(resp){ return resp.text(); })
        .then(function(html){
          var parser = new DOMParser();
          var doc = parser.parseFromString(html, "text/html");
          var newMessages = doc.getElementById("chat-messages");
          if(newMessages && chatBody){
            chatBody.innerHTML = newMessages.innerHTML;
            chatBody.scrollTop = chatBody.scrollHeight;
          }
        });
    }, 2000);
  }

  // (commentaire supprimé)
  if(!conversationId){
    setInterval(function(){
      fetch("api-support-chat-pending.php")
        .then(function(resp){ return resp.json(); })
        .then(function(data){
          var pendingCount = data.success && data.pending ? data.pending.length : 0;
          if(pendingCount > 0){
            document.title = "("+pendingCount+") Support Chat";
          }else{
            document.title = "Support Chat";
          }
        });
    }, 2000);
  }
});';

include __DIR__ . '/template.php';
