<?php
$page_title = 'Whatsapp Wiselie';
require_once('includes/load.php');
include_once('layouts/header.php'); ?>
<style>
body {
  background: linear-gradient(to right, #2c3e50, #34495e);
  color: #ecf0f1;
  font-family: Arial, sans-serif;
}

.chat-window {
  background-color: #34495e;
  height: 100vh;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  padding-left: 0px;
  padding-right: 0px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5);
}

.chat-header {
  background: linear-gradient(to right, #4caf50, #81c784);
  /* Gradient hijau */
  color: white;
  padding: 10px;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.chat-body {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.message {
  margin: 5px 0;
  padding: 10px;
  border-radius: 5px;
  max-width: 70%;
}

.sent {
  color: black !important;
  background-color: #dcf8c6;
  align-self: flex-start;
}

.received {
  color: black !important;
  background-color: #f1f0f0;
  align-self: flex-end;
}

.chat-input {
  display: flex;
  padding: 10px;
  background-color: #2c3e50;
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
}

.chat-input input {
  color: black !important;
  background-color: #ecf0f1;
  border: none;
  border-radius: 5px;
  padding: 10px;
  flex: 1;
  margin-right: 10px;
}

.chat-input button {
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 15px;
}

.chat-input button:hover {
  background-color: #0056b3;
}


.contact-list {
  background-color: #2c3e50;
  /* Warna latar belakang gelap */
  color: #ecf0f1;
  /* Warna teks terang */
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5);
}

.contact-list h3 {
  color: #4caf50;
  /* Warna hijau untuk judul */
}

.list-group-item {
  background-color: #34495e;
  /* Warna latar belakang item */
  color: #ecf0f1;
  /* Warna teks item */
  border: none;
  /* Menghilangkan border */
  border-radius: 5px;
  /* Membuat sudut item lebih halus */
  margin-bottom: 10px;
  /* Jarak antar item */
  transition: background-color 0.3s;
  /* Efek transisi saat hover */
}

.list-group-item:hover {
  background-color: #4caf50;
  /* Warna saat hover */
  color: white;
  /* Warna teks saat hover */
}

.list-group-item.active {
  background-color: #4caf50;
  /* Warna saat hover */
  color: white;
  /* Warna teks saat hover */
}

.chat-input {
  display: flex;
  padding: 10px;
  background-color: #2c3e50;
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
}

.chat-input input {
  background-color: #ecf0f1;
  /* Warna latar belakang input */
  border: none;
  /* Menghilangkan border default */
  border-radius: 5px;
  /* Sudut halus */
  padding: 10px;
  flex: 1;
  /* Mengisi ruang yang tersedia */
  margin-right: 10px;
  /* Jarak antara input dan tombol */
  transition: box-shadow 0.3s;
  /* Efek transisi saat fokus */
}

.chat-input input:focus {
  outline: none;
  /* Menghilangkan outline default */
  box-shadow: 0 0 5px rgba(76, 175, 80, 0.5);
  /* Efek bayangan saat fokus */
}

.chat-input button {
  background-color: #4caf50;
  /* Warna hijau untuk tombol */
  color: white;
  /* Warna teks tombol */
  border: none;
  /* Menghilangkan border default */
  border-radius: 5px;
  /* Sudut halus */
  padding: 10px 15px;
  /* Padding tombol */
  cursor: pointer;
  /* Menunjukkan bahwa tombol dapat diklik */
  transition: background-color 0.3s;
  /* Efek transisi saat hover */
}

.chat-input button:hover {
  background-color: #388e3c;
  /* Warna saat hover */
}

.message-time {
  font-size: 0.8em;
  /* Ukuran font lebih kecil */
  color: rgb(130, 134, 137);
  /* Warna abu-abu untuk waktu */
  margin-top: 5px;
  /* Jarak atas */
}


.attach-options {
  display: none;
  /* Sembunyikan tombol tambahan */
  position: absolute;
  /* Posisi tombol tambahan relatif terhadap tombol attach */
  bottom: 40px;
  /* Menempatkan tombol tambahan di atas tombol attach */
  left: 10px;
  z-index: 10;
  /* Menjamin tombol tambahan berada di atas tombol attach */
  text-align: center;
  margin-bottom: 20px;
}

#attachButton {
  position: relative;
}

.attach-options button {
  margin: 1px;
  font-size: 14px;
  transition: background-color 0.3s, transform 0.2s;
}

.attach-options button:hover {
  background-color: #4caf50;
  transform: scale(1.1);
}

.attach-options button i {
  font-size: 14px;
  transition: color 0.3s;
}

.attach-options button:hover i {
  color: white;
}

#emojiPicker {
  display: none;
  position: absolute;
  bottom: 60px;
  left: 10px;
  bottom: 110px;
  z-index: 200;
  width: 400px;
}

.container .row {
  display: flex;
  align-items: stretch;
  /* Pastikan semua elemen memiliki tinggi yang sama */
}

.contact-list,
.chat-window {
  display: flex;
  flex-direction: column;
  height: 100vh;
  /* Atur tinggi agar sesuai dengan viewport */
  overflow-y: auto;
  /* Tambahkan scroll jika kontennya panjang */
}
</style>
<?php
$contacts = $db->query("SELECT * FROM crm_contact where NOT id = 1");
$contact_id = isset($_GET['contact_id']) ? intval($_GET['contact_id']) : 1; // Default to the first contact
$messages = $db->query("SELECT * FROM crm_message WHERE receiver_id = $contact_id OR sender_id = $contact_id ORDER BY sent_at ASC");
?>
</div>
<div class="container">
  <div class="row">
    <div class="col-md-12 header">
      <h2>WhatsApp Wiselie</h2>
    </div>
  </div>
  <div class="row">
    <div class="col-md-4 contact-list">
      <h3>Kontak</h3>
      <ul class="list-group">
        <?php
        $namaContact = '';
        $phoneNumber = '';
        while ($contact = $contacts->fetch_assoc()): ?>
        <li
          class="list-group-item <?php echo (isset($_GET['contact_id']) && $contact['id'] == $_GET['contact_id']) ? 'active' : ''; ?>">
          <a href="view-wa.php?contact_id=<?php echo $contact['id']; ?>" class="text-secondary">
            <?php
              echo htmlspecialchars($contact['name']);
              if (isset($_GET['contact_id']) && $contact['id'] == $_GET['contact_id']) {
                $namaContact = htmlspecialchars($contact['name']);
                $phoneNumber = htmlspecialchars($contact['phone_number']);
              }
              ?>
          </a>
        </li>
        <?php endwhile; ?>
      </ul>
    </div>
    <div class="col-md-8 chat-window">
      <div class="chat-header">
        <h3><b><?php echo $namaContact; ?></b></h3>
      </div>
      <div class="chat-body">
        <?php if ($messages->num_rows > 0 && isset($_GET['contact_id'])): ?>
        <?php while ($message = $messages->fetch_assoc()): ?>
        <div class="message <?php echo ($message['sender_id'] == 1) ? 'sent' : 'received'; ?>">
          <?php echo htmlspecialchars($message['message_text']); ?>
          <div class="message-time"><?php echo date('H:i', strtotime($message['sent_at'])); ?></div>
        </div>
        <?php endwhile; ?>
        <?php endif; ?>
      </div>
      <emoji-picker id="emojiPicker" class="light"></emoji-picker>
      <div class="chat-input">
        <div class="attach-options">
          <button type="button" class="btn btn-secondary" id="selectImageButton">
            <i class="fas fa-image"></i>
          </button>
          <button type="button" class="btn btn-secondary" id="selectVideoButton">
            <i class="fas fa-video"></i>
          </button>
          <button class="btn btn-secondary" id="emojiButton">😊</button>
        </div>
        <button type="button" class="btn btn-secondary mr-3" id="attachButton">
          <i class="fas fa-paperclip"></i>
        </button>
        <input type="hidden" id="contactNumber" value="<?php echo $phoneNumber; ?>">
        <input type="text" id="messageInput" class="form-control" placeholder="Ketik pesan...">
        <input type="file" id="imageInput" class="form-control-file" accept="image/*" style="display:none;">
        <input type="file" id="videoInput" class="form-control-file" accept="video/*" style="display:none;">

        <button class="btn btn-primary" id="sendMessage">Kirim</button>
      </div>
    </div>
  </div>
</div>

<?php include_once('layouts/footer.php'); ?>
<script>
$(document).ready(function() {
  let isAttached = false;
  $('#attachButton').click(function() {
    if (!isAttached) {
      $('.attach-options').stop(true, true).fadeIn(300);
      $(this).css({
        'background-color': 'yellow',
        'color': 'black'
      });
      isAttached = true;
    } else {
      $('#emojiPicker').hide();
      $('.attach-options').stop(true, true).fadeOut(300);
      $(this).css({
        'background-color': '#4caf50',
        'color': 'white'
      });
      isAttached = false;
    }
  });

  $('#selectImageButton').click(function() {
    $('#imageInput').click();
  });

  $('#selectVideoButton').click(function() {
    $('#videoInput').click();
  });

  $('#emojiButton').click(function() {
    $('#emojiPicker').toggle(); // Toggle tampilan emoji picker
  });

  $('#emojiPicker').get(0).addEventListener('emoji-click', event => {
    var emoji = event.detail.unicode;
    $('#messageInput').val($('#messageInput').val() + emoji);
  });
  $('#imageInput').change(function() {
    var contactNumber = $('#contactNumber').val();
    handleFileUpload(contactNumber, this, 'image');
  });

  $('#videoInput').change(function() {
    var contactNumber = $('#contactNumber').val();
    handleFileUpload(contactNumber, this, 'video');
  });

  function handleFileUpload(phone, input, type) {
    var file = input.files[0];
    if (file) {
      var reader = new FileReader();
      reader.onload = function(e) {
        var formData = new FormData();
        formData.append('file', file);
        formData.append('type', type);
        formData.append('phone', phone);
        $.ajax({
          url: 'api_send_media.php',
          type: 'POST',
          data: formData,
          processData: false,
          contentType: false,
          success: function(response) {
            if (type === 'image') {
              $('#messageInput').val(''); // Clear message input
              $('.chat-body').append('<div class="message sent"><img src="' + e.target.result +
                '" class="media-msg"/><div class="message-time">' + new Date().toLocaleTimeString([], {
                  hour: '2-digit',
                  minute: '2-digit'
                }) + '</div></div>');
            } else if (type === 'video') {
              $('#messageInput').val(''); // Clear message input
              $('.chat-body').append('<div class="message sent"><video controls><source src="' + e.target
                .result +
                '" type="video/mp4"></video><div class="message-time">' + new Date().toLocaleTimeString(
                  [], {
                    hour: '2-digit',
                    minute: '2-digit'
                  }) + '</div></div>');
            }
          },
          error: function(xhr, status, error) {
            console.error('Error sending media:', error);
          }
        });
      };
      reader.readAsDataURL(file);
    }
  }
  $('#sendMessage').click(function() {
    var messageText = $('#messageInput').val();
    var contactNumber = $('#contactNumber').val();
    var receiverId = <?php echo $contact_id; ?>; // Replace with the actual receiver ID

    if (messageText !== '') {
      $.ajax({
        url: 'api_send_message.php',
        type: 'POST',
        data: {
          receiver_id: receiverId,
          message_text: messageText,
          contact_number: contactNumber
        },
        success: function(response) {
          var result = JSON.parse(response);
          if (result.status === 'success') {
            // Optionally, you can append the new message to the chat body
            $('.chat-body').append('<div class="message sent">' + messageText +
              '<div class="message-time">' + new Date().toLocaleTimeString([], {
                hour: '2-digit',
                minute: '2-digit'
              }) + '</div></div>');
            $('#messageInput').val(''); // Clear the input field
          } else {
            alert(result.message);
          }
        },
        error: function() {
          alert('Terjadi kesalahan saat mengirim pesan.');
        }
      });
    } else {
      alert('Pesan tidak boleh kosong.');
    }
  });
});
</script>