<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/
?>

<?php
  $baseUrl = $this->url(array('module' => 'core', 'controller' => 'savecollection', 'action' => 'collections'), 'default', true);
  $apiUrl = $this->url(array('module' => 'core', 'controller' => 'savecollection'), 'default', true) . '/';
?>
<div class="layout_middle">
  <div class="generic_layout_container layout_core_content">
    <h2 class="mb-0"><?php echo $this->translate("Saved Items"); ?></h2>

    <div class="section_tabs">
      <ul>
        <li><a href="<?php echo $this->url(array('module' => 'core', 'controller' => 'savecollection', 'action' => 'index'), 'default', true); ?>"><?php echo $this->translate("Saved Items"); ?></a></li>
        <li><a href="<?php echo $this->url(array('module' => 'core', 'controller' => 'savecollection', 'action' => 'collections'), 'default', true); ?>" class="active"><?php echo $this->translate("Collections"); ?></a></li>
      </ul>
    </div>

    <div class="savecollection_listing_header">
      <div class="savecollection_listing_header_search position-relative">
        <i class="fas fa-search"></i>
        <input type="text" id="savecollection_search_input" placeholder="<?php echo $this->translate('Search collections...'); ?>" value="<?php echo $this->escape($this->search); ?>" />
      </div>
      <div class="savecollection_listing_header_actions">
        <a href="javascript:void(0);" id="savecollection_create_btn" class="btn btn-primary savecollection_create_btn">
          <i class="icon_add"></i>
          <span><?php echo $this->translate("Create Collection"); ?></span>
        </a>
      </div>
    </div>

    <?php if ($this->paginator->getTotalItemCount() > 0): ?>
      <ul class="savecollection_grid grid_listing">
        <?php foreach ($this->paginator as $collection): ?>
          <?php
            $itemCount = Engine_Api::_()->getDbtable('collectionitems', 'core')->countByCollection($collection->collection_id);
            // Get thumbnail from the first item in the collection
            $thumbnail = '';
            if ($itemCount > 0) {
              try {
                $collectionitemsTable = Engine_Api::_()->getDbtable('collectionitems', 'core');
                $firstItemSelect = $collectionitemsTable->select()
                  ->where('collection_id = ?', $collection->collection_id)
                  ->order('created_at DESC')
                  ->limit(1);
                $firstMapping = $collectionitemsTable->fetchRow($firstItemSelect);
                if ($firstMapping) {
                  $saveditemsTable = Engine_Api::_()->getDbtable('saveditems', 'core');
                  $savedItem = $saveditemsTable->find($firstMapping->saveditem_id)->current();
                  if ($savedItem) {
                    $contentItem = Engine_Api::_()->getItem($savedItem->content_type, $savedItem->content_id);
                    $displayInfo = Engine_Api::_()->getApi('savecollection', 'core')->getContentDisplayInfo($contentItem);
                    $thumbnail = $displayInfo['photo'];
                  }
                }
              } catch (Exception $e) {}
            }
          ?>
          <li class="grid_listing_item grid_listing_item" data-collection-id="<?php echo $collection->collection_id; ?>">
            <article>
              <div class="grid_listing_item_thumb savecollection_card_thumb position-relative">
                <a href="<?php echo $this->url(array('module' => 'core', 'controller' => 'savecollection', 'action' => 'detail', 'collection_id' => $collection->collection_id), 'default', true); ?>">
                  <div class="savecollection_card_thumb savecollection_card_thumb_short">
                    <?php if ($thumbnail): ?>
                      <img src="<?php echo $thumbnail; ?>" alt="<?php echo $this->escape($collection->name); ?>" loading="lazy" />
                    <?php else: ?>
                      <i class="fi fi-rr-folder savecollection_card_thumb_icon"></i>
                    <?php endif; ?>
                  </div>
                </a>
                <div class="dropdown options_menu">
                  <button class="btn btn-alt" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="icon_option_menu"></i>
                  </button>
                  <ul class="dropdown-menu dropdown-option-menu dropdown-menu-end">
                    <li><a href="javascript:void(0);" class="dropdown-item savecollection_edit_btn" data-id="<?php echo $collection->collection_id; ?>" data-name="<?php echo $this->escape($collection->name); ?>"><i class="fi fi-rr-edit"></i> <?php echo $this->translate("Edit"); ?></a></li>
                    <li><a href="javascript:void(0);" class="dropdown-item savecollection_delete_btn" data-id="<?php echo $collection->collection_id; ?>" data-name="<?php echo $this->escape($collection->name); ?>"><i class="fi fi-rr-trash"></i> <?php echo $this->translate("Delete"); ?></a></li>
                  </ul>
                </div>
              </div>
              <div class="grid_listing_item_info">
                <div class="grid_listing_item_title">
                  <a href="<?php echo $this->url(array('module' => 'core', 'controller' => 'savecollection', 'action' => 'detail', 'collection_id' => $collection->collection_id), 'default', true); ?>"><?php echo $this->escape($collection->name); ?></a>
                </div>
                <div class="grid_listing_item_stats">
                  <span><?php echo $this->translate(array('%s item', '%s items', $itemCount), $itemCount); ?></span>
                </div>
              </div>
            </article>
          </li>
        <?php endforeach; ?>
      </ul>

      <?php if ($this->paginator->count() > 1): ?>
        <div class="savecollection_pagination">
          <?php echo $this->paginationControl($this->paginator, null, null, array(
            'pageAsQuery' => true,
            'query' => array('search' => $this->search),
          )); ?>
        </div>
      <?php endif; ?>
    <?php else: ?>
      <div class="no_result_tip">
        <i class="noicon center_item"><svg viewBox="0 0 24 24" fill="currentColor"><path d="m0,18V5C0,2.794,1.794,1,4,1h2c.464,0,.928.109,1.342.316l3.155,1.578c.138.069.293.105.447.105h5.056c2.757,0,5,2.243,5,5h-10.976c-2.638,0-5.003,1.766-5.754,4.303l-2.673,9.339c-.977-.913-1.597-2.203-1.597-3.642Zm23.493-6.983c-.479-.643-1.209-1.012-2.008-1.025-.015,0-.027.008-.042.008h-11.419c-1.758,0-3.335,1.177-3.834,2.862l-2.818,9.843c.513.178,1.055.295,1.628.295h12.558c2.226,0,4.15-1.432,4.802-3.607l1.532-6.116c.234-.782.089-1.605-.398-2.26Z"/></svg></i>
        <?php if (!empty($this->search)): ?>
          <p><?php echo $this->translate("No collections found matching your search."); ?></p>
        <?php else: ?>
          <p><?php echo $this->translate("You haven't created any collections yet."); ?></p>
          <p><?php echo $this->translate("Collections help you organize your saved items into groups."); ?></p>
        <?php endif; ?>
      </div>
    <?php endif; ?>
  </div>
</div>

<?php // Create Collection Modal ?>
<div id="savecollection_create_modal" class="savecollection_modal_overlay">
  <div class="savecollection_modal">
    <div class="savecollection_modal_header">
      <h3 class="savecollection_modal_title"><?php echo $this->translate("Create Collection"); ?></h3>
    </div>
    <div class="savecollection_modal_body">
      <label class="savecollection_modal_label"><?php echo $this->translate("Collection Name"); ?></label>
      <input type="text" id="create_collection_name" class="savecollection_modal_input" minlength="5" maxlength="50" placeholder="<?php echo $this->translate('Enter collection name'); ?>" />
      <div id="create_name_error" class="savecollection_modal_error"></div>
    </div>
    <div class="savecollection_modal_actions">
      <button type="button" id="create_cancel_btn" class="btn btn-alt"><span><?php echo $this->translate("Cancel"); ?></span></button>
      <button type="button" id="create_submit_btn" class="btn btn-primary" disabled><span><?php echo $this->translate("Create"); ?></span></button>
    </div>
  </div>
</div>

<?php // Edit Collection Modal ?>
<div id="savecollection_edit_modal" class="savecollection_modal_overlay">
  <div class="savecollection_modal">
    <div class="savecollection_modal_header">
      <h3 class="savecollection_modal_title"><?php echo $this->translate("Edit Collection"); ?></h3>
    </div>
    <input type="hidden" id="edit_collection_id" />
    <div class="savecollection_modal_body">
      <label class="savecollection_modal_label"><?php echo $this->translate("Collection Name"); ?></label>
      <input type="text" id="edit_collection_name" class="savecollection_modal_input" minlength="5" maxlength="50" />
      <div id="edit_name_error" class="savecollection_modal_error"></div>
    </div>
    <div class="savecollection_modal_actions">
      <button type="button" id="edit_cancel_btn" class="btn btn-alt"><span><?php echo $this->translate("Cancel"); ?></span></button>
      <button type="button" id="edit_submit_btn" class="btn btn-primary"><span><?php echo $this->translate("Save"); ?></span></button>
    </div>
  </div>
</div>

<?php // Delete Confirmation Modal ?>
<div id="savecollection_delete_modal" class="savecollection_modal_overlay">
  <div class="savecollection_modal">
    <div class="savecollection_modal_header">
      <h3 class="savecollection_modal_title"><?php echo $this->translate("Delete Collection"); ?></h3>
    </div>
    <div class="savecollection_modal_body">
      <input type="hidden" id="delete_collection_id" />
      <p id="delete_confirmation_text" class="savecollection_modal_text"></p>
    </div>
    <div class="savecollection_modal_actions">
      <button type="button" id="delete_cancel_btn" class="btn btn-alt"><span><?php echo $this->translate("Cancel"); ?></span></button>
      <button type="button" id="delete_confirm_btn" class="btn btn-danger"><span><?php echo $this->translate("Delete"); ?></span></button>
    </div>
  </div>
</div>

<script type="text/javascript">
en4.core.runonce.add(function() {
  var baseUrl = <?php echo json_encode($baseUrl); ?>;
  var apiUrl = <?php echo json_encode($apiUrl); ?>;
  var searchTimer = null;
  var currentSearch = <?php echo json_encode($this->search); ?>;
  var searchInput = document.getElementById('savecollection_search_input');
  if (searchInput) {
    searchInput.addEventListener('keydown', function(e) {
      if (e.key === 'Enter') {
        e.preventDefault();
        clearTimeout(searchTimer);
        var val = searchInput.value.trim();
        window.proxyLocation.href = baseUrl + (val ? '?search=' + encodeURIComponent(val) : '');
      }
    });
    searchInput.addEventListener('input', function() {
      clearTimeout(searchTimer);
      var val = searchInput.value.trim();
      if (val === currentSearch) return;
      searchTimer = setTimeout(function() {
        window.proxyLocation.href = baseUrl + (val ? '?search=' + encodeURIComponent(val) : '');
      }, 800);
    });
  }
  var createModal = document.getElementById('savecollection_create_modal');
  var createNameInput = document.getElementById('create_collection_name');
  var createSubmitBtn = document.getElementById('create_submit_btn');
  var createError = document.getElementById('create_name_error');
  document.getElementById('savecollection_create_btn').addEventListener('click', function() {
    createNameInput.value = '';
    createError.style.display = 'none';
    createSubmitBtn.disabled = true;
    createModal.style.display = 'flex';
    createNameInput.focus();
  });
  document.getElementById('create_cancel_btn').addEventListener('click', function() { createModal.style.display = 'none'; });
  createNameInput.addEventListener('input', function() {
    var len = this.value.trim().length;
    createSubmitBtn.disabled = len < 5;
    if (len > 0 && len < 5) {
      createError.textContent = '<?php echo $this->translate("Collection name must be at least 5 characters"); ?>';
      createError.style.display = 'block';
    } else {
      createError.style.display = 'none';
    }
  });
  createSubmitBtn.addEventListener('click', function() {
    var name = createNameInput.value.trim();
    if (!name) return;
    createSubmitBtn.disabled = true;
    var fd = new FormData(); fd.append('name', name);
    fetch(apiUrl + 'collection-create', { method: 'POST', body: fd })
      .then(function(r) { return r.json(); })
      .then(function(data) {
        if (data.error == '0') { createModal.style.display = 'none'; window.proxyLocation.reload(); }
        else { createError.textContent = data.error_message || '<?php echo $this->translate("Error"); ?>'; createError.style.display = 'block'; createSubmitBtn.disabled = false; }
      }).catch(function() { createError.textContent = '<?php echo $this->translate("Something went wrong."); ?>'; createError.style.display = 'block'; createSubmitBtn.disabled = false; });
  });
  var editModal = document.getElementById('savecollection_edit_modal');
  var editNameInput = document.getElementById('edit_collection_name');
  var editSubmitBtn = document.getElementById('edit_submit_btn');
  var editError = document.getElementById('edit_name_error');
  document.querySelectorAll('.savecollection_edit_btn').forEach(function(btn) {
    btn.addEventListener('click', function(e) { e.preventDefault(); document.getElementById('edit_collection_id').value = this.dataset.id; editNameInput.value = this.dataset.name; editError.style.display = 'none'; editModal.style.display = 'flex'; editNameInput.focus(); });
  });
  document.getElementById('edit_cancel_btn').addEventListener('click', function() { editModal.style.display = 'none'; });
  editNameInput.addEventListener('input', function() {
    var len = this.value.trim().length;
    editSubmitBtn.disabled = len < 5;
    if (len > 0 && len < 5) {
      editError.textContent = '<?php echo $this->translate("Collection name must be at least 5 characters"); ?>';
      editError.style.display = 'block';
    } else {
      editError.style.display = 'none';
    }
  });
  editSubmitBtn.addEventListener('click', function() {
    var id = document.getElementById('edit_collection_id').value; var name = editNameInput.value.trim();
    if (!name) return; editSubmitBtn.disabled = true;
    var fd = new FormData(); fd.append('collection_id', id); fd.append('name', name);
    fetch(apiUrl + 'collection-edit', { method: 'POST', body: fd })
      .then(function(r) { return r.json(); })
      .then(function(data) {
        if (data.error == '0') { editModal.style.display = 'none'; window.proxyLocation.reload(); }
        else { editError.textContent = data.error_message || '<?php echo $this->translate("Error"); ?>'; editError.style.display = 'block'; editSubmitBtn.disabled = false; }
      }).catch(function() { editError.textContent = '<?php echo $this->translate("Something went wrong."); ?>'; editError.style.display = 'block'; editSubmitBtn.disabled = false; });
  });
  var deleteModal = document.getElementById('savecollection_delete_modal');
  var deleteConfirmBtn = document.getElementById('delete_confirm_btn');
  document.querySelectorAll('.savecollection_delete_btn').forEach(function(btn) {
    btn.addEventListener('click', function(e) { e.preventDefault(); document.getElementById('delete_collection_id').value = this.dataset.id; document.getElementById('delete_confirmation_text').textContent = '<?php echo $this->translate("Are you sure you want to delete"); ?> "' + this.dataset.name + '"? <?php echo $this->translate("Your saved items will not be removed."); ?>'; deleteModal.style.display = 'flex'; });
  });
  document.getElementById('delete_cancel_btn').addEventListener('click', function() { deleteModal.style.display = 'none'; });
  deleteConfirmBtn.addEventListener('click', function() {
    var id = document.getElementById('delete_collection_id').value; deleteConfirmBtn.disabled = true;
    var fd = new FormData(); fd.append('collection_id', id);
    fetch(apiUrl + 'collection-delete', { method: 'POST', body: fd })
      .then(function(r) { return r.json(); })
      .then(function(data) { if (data.error == '0') { deleteModal.style.display = 'none'; window.proxyLocation.reload(); } else { deleteModal.style.display = 'none'; deleteConfirmBtn.disabled = false; } })
      .catch(function() { deleteModal.style.display = 'none'; deleteConfirmBtn.disabled = false; });
  });
  [createModal, editModal, deleteModal].forEach(function(modal) { modal.addEventListener('click', function(e) { if (e.target === modal) modal.style.display = 'none'; }); });
});
</script>
