<!DOCTYPE html>
<html lang="en">
<?= view('shared/head') ?>
<body>
  <div class="wrapper">
    <?= view('home/navbar') ?>
    <div class="content-wrapper p-4 text-navy">
      <div class="conversation">
        <?php
          require_once APPPATH . 'Libraries/Parsedown.php';
          $Parsedown = new Parsedown();
          $Parsedown->setSafeMode(true);
        ?>

        <!-- Display Messages -->
        <?php if (empty($messages)): ?>
          <p>No messages yet. Start the conversation!</p>
        <?php else: ?>
          <?php foreach ($messages as $message): ?>
            <div class="message">
              <div class="user-message">
                <strong>You Said:</strong>
                <p style="white-space: pre-wrap;"><?= esc($message['to_this']) ?></p>
              </div>
              <div class="gpt-response">
                <strong>GPT Response:</strong>
                <div>
                  <?php
                  // Convert markdown to HTML
                  $htmlContent = $Parsedown->text($message['gpt_response']);

                  // Process the HTML to add copy buttons to code blocks
                  $doc = new \DOMDocument();

                  // Suppress warnings due to malformed HTML (optional)
                  libxml_use_internal_errors(true);
                  $doc->loadHTML('<?xml encoding="utf-8" ?>' . $htmlContent);
                  libxml_clear_errors();

                  // Get all <pre><code> elements
                  $xpath = new \DOMXPath($doc);
                  $codeBlocks = $xpath->query('//pre/code');

                  foreach ($codeBlocks as $codeBlock) {
                      // The parent of <code> is <pre>
                      $preElement = $codeBlock->parentNode;

                      // Create the copy button element
                      $copyButton = $doc->createElement('button', 'Copy');
                      $copyButton->setAttribute('class', 'copy-button');

                      // Insert the copy button into the <pre> element
                      $preElement->insertBefore($copyButton, $codeBlock);
                  }

                  // Output the modified HTML
                  // Extract body content to avoid duplicate tags
                  $body = $doc->getElementsByTagName('body')->item(0);
                  $htmlOutput = '';
                  foreach ($body->childNodes as $childNode) {
                      $htmlOutput .= $doc->saveHTML($childNode);
                  }
                  echo $htmlOutput;
                  ?>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>

      <!-- New Message Form -->
      <form action="/conversations/sendMessage" method="post" id="messageForm">
        <?= csrf_field() ?> <!-- Include CSRF protection if enabled -->
        <input type="hidden" name="conversation_id" value="<?= $conversation['id'] ?>">

        <div class="form-row">
          <!-- Choose Do This Field (Dropdown) -->
          <div class="form-group col-md-6">
            <label for="choose_do_this">Choose Do This:</label>
            <select name="choose_do_this" id="choose_do_this" class="form-control">
              <option value="">-- Select --</option>
              <?php foreach ($doThisOptions as $option): ?>
                <option value="<?= $option['id'] ?>"><?= esc($option['title']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <!-- Choose GPT Model Field (Dropdown) -->
          <div class="form-group col-md-6">
            <label for="gpt_model">Choose GPT Model:</label>
            <select name="gpt_model" id="gpt_model" class="form-control">
              <?php foreach ($gptModels as $model): ?>
                <option value="<?= $model['id'] ?>"><?= esc($model['model']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>

        <!-- Do This Field (Auto-resizing Textarea) -->
        <div class="form-group">
          <label for="do_this">Do This:</label>
          <textarea name="do_this" id="do_this" rows="2" class="form-control"></textarea>
        </div>

        <!-- To This Field (Required Auto-resizing Textarea) -->
        <div class="form-group">
          <label for="to_this">To This: <span style="color:red">*</span></label>
          <textarea name="to_this" id="to_this" rows="3" class="form-control" required></textarea>
        </div>

        <!-- Conversation ID Field (Integer Input) -->
        <div class="form-group">
          <label for="conversation_id_field">Conversation ID:</label>
          <input type="number" name="conversation_id_field" id="conversation_id_field" class="form-control" required value="<?= $conversation['id'] ?>">
        </div>

        <!-- Submit Button -->
        <button type="submit" class="btn btn-primary">Send Prompt</button>
      </form>
    </div>
  </div>

  <script>
    // Function to set a cookie
    function setCookie(name, value, days) {
      var expires = "";
      if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
      }
      document.cookie = name + "=" + (value || "")  + expires + "; path=/";
    }

    // Function to get a cookie by name
    function getCookie(name) {
      var nameEQ = name + "=";
      var ca = document.cookie.split(';');
      for(var i=0;i < ca.length;i++) {
          var c = ca[i];
          while (c.charAt(0)==' ') c = c.substring(1,c.length);
          if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
      }
      return null;
    }

    // Populate DoThisField based on selection
    document.getElementById('choose_do_this').addEventListener('change', function() {
      var selectedId = this.value;

      if (selectedId) {
        // Fetch the do_this text via AJAX
        fetch('/conversations/getDoThisText/' + selectedId)
          .then(response => response.json())
          .then(data => {
            document.getElementById('do_this').value = data.do_this;
          })
          .catch(error => {
            console.error('Error fetching do_this text:', error);
          });
      } else {
        document.getElementById('do_this').value = '';
      }
    });

    // Auto-resize textareas
    function autoResizeTextarea(textarea) {
      textarea.style.height = 'auto';
      textarea.style.height = (textarea.scrollHeight) + 'px';
    }

    var textareas = document.querySelectorAll('textarea');
    textareas.forEach(function(textarea) {
      textarea.addEventListener('input', function() {
        autoResizeTextarea(textarea);
      });
      // Initial resize
      autoResizeTextarea(textarea);
    });

    // Scroll to the last GPT response when the page loads
    window.onload = function() {
      var conversationDiv = document.querySelector('.conversation');
      var gptResponses = conversationDiv.querySelectorAll('.gpt-response');

      if (gptResponses.length > 0) {
        var lastGptResponse = gptResponses[gptResponses.length - 1];

        // Scroll the last GPT response into view at the top
        var topPosition = lastGptResponse.offsetTop - conversationDiv.offsetTop;
        conversationDiv.scrollTop = topPosition;
      }

      // When the page loads, set the selected GPT model based on the cookie
      var gptModelSelect = document.getElementById('gpt_model');
      var selectedGptModel = getCookie('selectedGptModel');
      if (selectedGptModel) {
        for (var i = 0; i < gptModelSelect.options.length; i++) {
            if (gptModelSelect.options[i].value === selectedGptModel) {
                gptModelSelect.selectedIndex = i;
                break;
            }
        }
      }
    };

    // Store the selected GPT model in a cookie when it changes
    document.getElementById('gpt_model').addEventListener('change', function() {
      var selectedModel = this.value;
      setCookie('selectedGptModel', selectedModel, 7); // The cookie will expire in 7 days
    });

    // Function to copy code content to clipboard
    function copyCode(event) {
        const button = event.target;
        // The sibling of the button is the code element
        const codeBlock = button.nextElementSibling;
        let codeText = '';
        if (codeBlock && codeBlock.tagName.toLowerCase() === 'code') {
            codeText = codeBlock.innerText;
        } else {
            // Fallback in case the structure is different
            codeText = button.parentElement.innerText.replace('Copy', '').trim();
        }

        // Copy to clipboard
        navigator.clipboard.writeText(codeText).then(function() {
            // Provide feedback to the user
            button.innerText = 'Copied!';
            setTimeout(() => {
                button.innerText = 'Copy';
            }, 2000);
        }, function(err) {
            console.error('Could not copy text: ', err);
        });
    }

    // Attach event listeners to all copy buttons
    document.addEventListener('DOMContentLoaded', function() {
        const copyButtons = document.querySelectorAll('.copy-button');
        copyButtons.forEach(function(button) {
            button.addEventListener('click', copyCode);
        });
    });
  </script>

  <style>
    .conversation {
      display: flex;
      flex-direction: column;
      max-height: calc(100vh - 150px);
      overflow-y: auto;
      padding: 20px;
    }
    .message {
      display: flex;
      flex-direction: column;
      margin-bottom: 20px;
    }
    .user-message, .gpt-response {
      padding: 15px;
      border-radius: 10px;
      max-width: 80%;
      word-wrap: break-word;
    }
    .user-message {
      background-color: #e6f7ff;
      align-self: flex-end;
      text-align: left;
    }
    .gpt-response {
      background-color: #f0f0f0;
      align-self: flex-start;
      text-align: left;
      margin-top: 10px;
    }
    .message strong {
      display: block;
      margin-bottom: 5px;
    }
    /* Styling for code blocks */
    .gpt-response pre {
      position: relative;
      background-color: #2d2d2d;
      color: #f8f8f2;
      padding: 15px;
      padding-top: 40px; /* Adjust to make room for the button */
      overflow-x: auto;
      border-radius: 5px;
    }
    .gpt-response code {
      background-color: transparent;
    }
    /* Styling for the copy button */
    .copy-button {
        position: absolute;
        top: 10px;
        right: 10px;
        background-color: #4CAF50;
        border: none;
        color: white;
        padding: 5px 10px;
        font-size: 12px;
        border-radius: 5px;
        cursor: pointer;
        opacity: 0.8;
    }
    .copy-button:hover {
        opacity: 1;
    }
    /* Styling for blockquotes */
    .gpt-response blockquote {
      border-left: 4px solid #ccc;
      margin: 1em;
      padding-left: 1em;
      color: #555;
    }
    /* Styling for tables */
    .gpt-response table {
      border-collapse: collapse;
      width: 100%;
      margin-bottom: 1em;
    }
    .gpt-response table, .gpt-response th, .gpt-response td {
      border: 1px solid #ddd;
    }
    .gpt-response th, .gpt-response td {
      padding: 8px;
      text-align: left;
    }
    /* Styling for headers */
    .gpt-response h1, .gpt-response h2, .gpt-response h3, .gpt-response h4, .gpt-response h5, .gpt-response h6 {
      margin: 1em 0 0.5em;
    }
    /* Styling for lists */
    .gpt-response ul, .gpt-response ol {
      margin: 1em 0;
      padding-left: 40px;
    }
    /* Styling for links */
    .gpt-response a {
      color: #1a0dab;
      text-decoration: none;
    }
    .gpt-response a:hover {
      text-decoration: underline;
    }
    /* Styling for images */
    .gpt-response img {
      max-width: 100%;
      height: auto;
    }

    /* Form styling */
    #messageForm {
      margin-top: 20px;
    }
    #messageForm .form-group {
      margin-bottom: 15px;
    }
    #messageForm label {
      font-weight: bold;
    }
    #messageForm textarea {
      overflow: hidden;
      resize: none;
    }

    /* New styles for form-row and form-group sizing */
    .form-row {
      display: flex;
      flex-wrap: wrap;
      margin-right: -15px;
      margin-left: -15px;
    }
    .form-row .form-group {
      flex: 0 0 50%;
      max-width: 50%;
      padding-right: 15px;
      padding-left: 15px;
    }
  </style>
</body>
</html>