
<!-- Widget de chat support (WhatsApp-like) -->
<div id="supportChatWidget" style="position:fixed;bottom:30px;right:30px;z-index:9999;">
  <button id="openChatBtn" style="background:#007bff;color:#fff;border:none;border-radius:50%;width:60px;height:60px;box-shadow:0 2px 8px rgba(0,0,0,0.15);font-size:2rem;cursor:pointer;">
    <i class="fa fa-comments"></i>
  </button>
  <div id="chatPopup" style="display:none;width:340px;background:#fff;border-radius:12px;box-shadow:0 4px 16px rgba(0,0,0,0.12);padding:0;position:absolute;bottom:70px;right:0;">
    <div style="background:#007bff;padding:16px 24px;border-radius:12px 12px 0 0;color:#fff;">
      <h4 style="margin:0;font-size:1.2rem;">Support Chat</h4>
    </div>
    <div id="chatHistory" style="height:320px;overflow-y:auto;padding:16px;background:#f5f6fa;"></div>
    <form id="supportChatForm" style="padding:16px;border-top:1px solid #eee;background:#fff;">
      <div id="userFields">
        <input type="text" name="user_name" class="form-control mb-2" placeholder="Votre nom" required>
        <input type="email" name="user_email" class="form-control mb-2" placeholder="Votre email (optionnel)">
      </div>
      <div class="input-group mb-2" style="align-items:center;">
        <textarea name="message" class="form-control" rows="2" placeholder="Votre message..." required style="resize:none;min-height:38px;max-height:60px;"></textarea>
        <button type="submit" style="background:none;border:none;padding:0;margin-left:8px;display:flex;align-items:center;justify-content:center;" title="Envoyer">
          <i class="fa fa-paper-plane" style="font-size:1.3rem;color:#007bff;"></i>
        </button>
      </div>
    </form>
    <div id="chatResponse" style="margin:10px 16px 0 16px;font-size:0.95rem;"></div>
  <button id="closeChatBtn" style="background:none;border:none;color:#fff;font-size:1.5rem;position:absolute;top:12px;right:16px;display:flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:50%;"><i class="fa fa-times"></i></button>
  </div>
</div>
<script src="js/jquery.min.js"></script>
<script>
function renderChatBubble(msg) {
  var isAdmin = msg.sender === 'admin';
  var isUser = msg.sender === 'user';
  var avatar = isAdmin ? '<div style="width:32px;height:32px;background:#007bff;color:#fff;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:700;">'+(msg.user_name?msg.user_name[0].toUpperCase():'A')+'</div>' : '<div style="width:32px;height:32px;background:#6c757d;color:#fff;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:700;">'+(msg.user_name?msg.user_name[0].toUpperCase():'U')+'</div>';
  var bubble = '<div style="display:flex;margin-bottom:12px;'+(isUser?'justify-content:flex-end;':'justify-content:flex-start;')+'">';
  if(isAdmin) bubble += avatar;
  bubble += '<div style="max-width:70%;margin-left:'+(isUser?"auto":"8px")+';background:'+(isAdmin?'#e9f7ef':'#fff')+';border-radius:12px;padding:10px 14px;box-shadow:0 1px 4px rgba(0,0,0,0.07);color:'+(isAdmin?'#155724':'#333')+';">';
  bubble += '<div style="font-size:0.98em;font-weight:500;">'+(msg.user_name?msg.user_name:(isAdmin?'Agent':'Utilisateur'))+'</div>';
  bubble += '<div style="margin:6px 0;">'+msg.message+'</div>';
  bubble += '<div style="font-size:0.85em;color:#888;text-align:right;">'+msg.time+'</div>';
  bubble += '</div>';
  if(isUser) bubble += avatar;
  bubble += '</div>';
  return bubble;
}

function loadChatHistory() {
  var convId = localStorage.getItem('supportChatConvId') || '';
  var userEmail = $('input[name=user_email]').val();
  var userName = $('input[name=user_name]').val();
  if(!userEmail && !userName) { $('#chatHistory').html('<div style="color:#888;text-align:center;margin-top:40px;">Identifiez-vous pour voir la conversation.</div>'); return; }
  var params = convId ? { conversation_id: convId } : { user_email: userEmail, user_name: userName };
  $.get('support-chat.php', params, function(res) {
    var html = '';
    var hasAdminReply = false;
    var isClosed = false;
    if(res && res.length) {
      res.forEach(function(msg){
        if(msg.sender === 'admin') hasAdminReply = true;
        html += renderChatBubble(msg);
        if(msg.closed == 1) isClosed = true;
      });
      // Stocker l'id de conversation si présent
      if(res[0] && res[0].conversation_id) localStorage.setItem('supportChatConvId', res[0].conversation_id);
      // Si conversation clôturée, afficher le message d'information
      if(isClosed) {
        html += '<div style="max-width:70%;margin:12px auto;background:#ffe3e3;border-radius:12px;padding:10px 14px;box-shadow:0 1px 4px rgba(0,0,0,0.07);color:#c82333;text-align:center;font-size:0.98em;">Cette conversation est clôturée. Pour une nouvelle demande, veuillez saisir votre nom et votre email.</div>';
        $('#supportChatForm textarea, #supportChatForm button[type=submit]').prop('disabled',true);
        $('#userFields').slideDown();
      } else {
        $('#supportChatForm textarea, #supportChatForm button[type=submit]').prop('disabled',false);
        // Si pas de réponse admin, afficher le message d'attente après le premier message client
        if(!hasAdminReply && res.some(function(m){return m.sender==='user';})) {
          html += '<div id="waitingMsg" style="max-width:70%;margin:12px auto;background:#fffbe6;border-radius:12px;padding:10px 14px;box-shadow:0 1px 4px rgba(0,0,0,0.07);color:#856404;text-align:center;font-size:0.98em;">Votre message a été envoyé. Tous nos agents sont occupés, merci de patienter...</div>';
          setTimeout(function(){
            // Empêche la duplication du formulaire et du message
            if($('#waitingMsg').length && !$('#chatHistory').find('#excuseForm').length && !$('#chatHistory').find('#excuseMsg').length && !$('#chatHistory').find('.admin-reply').length){
              // Supprimer le premier message client et le message de patience
              var $chatHistory = $('#chatHistory');
              $chatHistory.find('.justify-content-flex-end').first().remove(); // premier message client
              $('#waitingMsg').remove();
              // Masquer le champ message et le bouton d'envoi
              $('#supportChatForm .input-group').hide();
              var excuseHtml = '<div id="excuseMsg" style="max-width:70%;margin:12px auto;background:#ffe3e3;border-radius:12px;padding:10px 14px;box-shadow:0 1px 4px rgba(0,0,0,0.07);color:#c82333;text-align:center;font-size:0.98em;">Nous sommes désolés, aucun agent n\'a pu répondre à votre demande. Veuillez expliquer votre demande ci-dessous :</div>';
              excuseHtml += '<form id="excuseForm" style="margin:12px auto;max-width:90%;background:#fff;border-radius:10px;padding:12px 10px;box-shadow:0 1px 4px rgba(0,0,0,0.07);">';
              excuseHtml += '<input type="text" name="user_name" class="form-control mb-2" placeholder="Votre nom" required value="'+$('input[name=user_name]').val()+'">';
              excuseHtml += '<input type="email" name="user_email" class="form-control mb-2" placeholder="Votre email" required value="'+$('input[name=user_email]').val()+'">';
              excuseHtml += '<textarea name="demande" class="form-control mb-2" rows="3" placeholder="Expliquez votre demande..." required></textarea>';
              excuseHtml += '<button type="submit" class="btn btn-danger w-100">Envoyer la demande</button>';
              excuseHtml += '</form>';
              $chatHistory.append(excuseHtml);
              $('#excuseForm').on('submit',function(e){
                e.preventDefault();
                var form = $(this);
                var btn = form.find('button[type=submit]');
                btn.prop('disabled',true);
                var name = form.find('input[name=user_name]').val();
                var email = form.find('input[name=user_email]').val();
                var demande = form.find('textarea[name=demande]').val();
                $.post('support-chat.php',{
                  user_name: name,
                  user_email: email,
                  demande: demande,
                  closed: 1,
                  email_send: 1
                },function(res){
                  if(res.success){
                    $('#chatHistory').html('<div style="color:#28a745;text-align:center;margin-top:40px;">Votre demande a été enregistrée. Nous vous répondrons par email dès que possible.</div>');
                    $('#supportChatForm textarea, #supportChatForm button[type=submit]').prop('disabled',false);
                    $('#supportChatForm .input-group').show();
                    $('#userFields').slideDown();
                    localStorage.removeItem('supportChatConvId');
                  }else{
                    $('#chatResponse').html('<span style="color:#dc3545;">'+res.message+'</span>');
                  }
                },'json').always(function(){
                  btn.prop('disabled',false);
                });
              });
            }
          }, 40000); // 40 sec
        }
      }
    } else {
      html = '<div style="color:#888;text-align:center;margin-top:40px;">Commencer une nouvelle convresation</div>';
      $('#supportChatForm textarea, #supportChatForm button[type=submit]').prop('disabled',false);
      localStorage.removeItem('supportChatConvId');
    }
    $('#chatHistory').html(html);
    $('#chatHistory').scrollTop($('#chatHistory')[0].scrollHeight);
  },'json');
}

$(function(){
  // Restore user info from localStorage
  if(localStorage.getItem('supportChatName')) {
    $('input[name=user_name]').val(localStorage.getItem('supportChatName'));
    $('input[name=user_email]').val(localStorage.getItem('supportChatEmail'));
    $('#userFields').hide();
  }

  $('#openChatBtn').on('click',function(){
    if($('#chatPopup').is(':visible')) {
      $('#chatPopup').fadeOut();
      if(window.supportChatPoll) clearInterval(window.supportChatPoll);
    } else {
      $('#chatPopup').fadeIn();
      loadChatHistory();
      if(window.supportChatPoll) clearInterval(window.supportChatPoll);
      window.supportChatPoll = setInterval(function(){
        // Ne pas actualiser si le formulaire d'excuse est affiché
        if($('#excuseForm').length === 0){
          loadChatHistory();
        }
      }, 2000);
    }
  });
  $('#closeChatBtn').on('click',function(){
    $('#chatPopup').fadeOut();
    if(window.supportChatPoll) clearInterval(window.supportChatPoll);
  });
  $('#supportChatForm').on('submit',function(e){
    e.preventDefault();
    var form = $(this);
    var btn = form.find('button[type=submit]');
    // Si le champ message est désactivé (conversation clôturée), demander nom/email et réinitialiser l'id de conversation
    if($('#supportChatForm textarea').prop('disabled')) {
      $('#chatResponse').html('<span style="color:#c82333;">La conversation est clôturée. Veuillez saisir votre nom et votre email pour démarrer une nouvelle demande.</span>');
      $('#userFields').slideDown();
      localStorage.removeItem('supportChatConvId');
      return;
    }
    // Save user info if not already
    if($('#userFields').is(':visible')) {
      var name = form.find('input[name=user_name]').val();
      var email = form.find('input[name=user_email]').val();
      localStorage.setItem('supportChatName', name);
      localStorage.setItem('supportChatEmail', email);
      $('#userFields').slideUp();
      localStorage.removeItem('supportChatConvId'); // Nouvelle conversation
    }
    btn.prop('disabled',true);
    $.post('support-chat.php',form.serialize(),function(res){
      var msgText = form.find('textarea[name=message]').val();
      if(res.success){
        $('#chatResponse').html('<span style="color:#28a745;"></span>');
        form.find('textarea[name=message]').val('').focus();
        // Affichage instantané du message dans le widget
        var userName = form.find('input[name=user_name]').val();
        var now = new Date();
        var time = now.getDate().toString().padStart(2,'0')+'/'+(now.getMonth()+1).toString().padStart(2,'0')+'/'+now.getFullYear()+' '+now.getHours().toString().padStart(2,'0')+':'+now.getMinutes().toString().padStart(2,'0');
        var msg = { sender:'user', user_name:userName, message:msgText, time:time };
        var html = $('#chatHistory').html();
        html += renderChatBubble(msg);
        $('#chatHistory').html(html);
        $('#chatHistory').scrollTop($('#chatHistory')[0].scrollHeight);
        setTimeout(loadChatHistory, 1500);
      }else{
        $('#chatResponse').html('<span style="color:#dc3545;">'+res.message+'</span>');
      }
    },'json').always(function(){
      btn.prop('disabled',false);
    });
  });
  $('#supportChatForm input[name=user_name], #supportChatForm input[name=user_email]').on('input',function(){
    localStorage.removeItem('supportChatConvId');
    loadChatHistory();
  });
  $('#supportChatForm textarea').on('change',function(){
    loadChatHistory();
  });

  // Envoi par Enter, retour à la ligne avec Shift+Enter
  $('textarea[name=message]').on('keydown', function(e){
    if(e.key === 'Enter'){
      if(e.shiftKey){
        // Retour à la ligne
        return;
      }else{
        e.preventDefault();
        $(this).closest('form').submit();
      }
    }
  });
});
</script>
