<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/
?>
<?php echo $this->partial('_admin_breadcrumb.tpl', 'core', array('parentMenu' => "core_admin_main_layout", 'parentMenuItemName' => 'core_admin_main_layout_files', 'childMenuItemName' => 'core_admin_main_layout_files_manager')); ?>

<?php if( engine_count($this->navigation) ): ?>
  <div class='tabs'>
    <?php echo $this->navigation()->menu()->setContainer($this->navigation)->render(); ?>
  </div>
<?php endif; ?>

<?php $this->headLink()->appendStylesheet($this->layout()->staticBaseUrl . '/externals/uploader/uploader.css'); ?>

<script type="text/javascript">

  var fileCopyUrl = function(url) {
    Smoothbox.open('<div><input type=\'text\' style=\'width:400px\' /><br /><br /><button onclick="Smoothbox.close();">Close</button></div>', {autoResize : true});
    Smoothbox.instance.content.find('input').val(url).focus();
    Smoothbox.instance.content.find('input').select();
    Smoothbox.instance.doAutoResize();
  }

  var uploadFile = function()
  {
    scriptJquery('#upload_file').trigger("click");
  }

  window.addEventListener('load', function() {
    scriptJquery('.admin_file_name').on('onclick onmouseout onmouseover',function(event){
      previewFile(event);
    });
    scriptJquery('.admin_file_preview').click(function(event){
      previewFile(event);
    });
  });

var BaseFileUpload = {
  uploadFile: function (obj, file, iteration, total) {
    var url = obj.attr('data-url');
    var xhr = new XMLHttpRequest();
    var fd = new FormData();
    xhr.open("POST", url, true);
    scriptJquery('#files-status-overall').css('display', 'block');

    // progress bar
    xhr.upload.addEventListener('progress', function (e) {
      var per = (total <= 1 ? e.loaded/e.total : iteration/total) * 100;
      var overAllFileProgress = -400 + ((per) * 2.5);
      scriptJquery('div#files-status-overall img').css('background-position', overAllFileProgress + 'px 0px');
      scriptJquery('div#files-status-overall span').html(per + '%');
    }, false);

    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        try {
          var res = JSON.parse(xhr.responseText);
        } catch (err) {
          BaseFileUpload.processUploadError('An error occurred.');
          return false;
        }

        if (res['error'] !== undefined) {
          BaseFileUpload.processUploadError(res['error']);
          return false;
        }
        BaseFileUpload.processUploadSuccess(res);

        if (iteration === total) {
          location.reload();
          //BaseFileUpload.showRefresh();
        }
      }
    };
    fd.append('ajax-upload', 'true');
    fd.append(obj.attr('name'), file);
    xhr.send(fd);
  },

  showRefresh: function () {
    scriptJquery('#files-status-overall').css('display', 'none');
    scriptJquery('#upload-complete-message').css('display', '');
  },

  processUploadSuccess: function(response) {
    var uploadedFileList = document.getElementById("uploaded-file-list");
    var uploadedFile = scriptJquery.crtEle('li', {
      'class': 'file file-success',
    }).html('<span class="file-name">' + response['fileName'] + '</span>').appendTo(uploadedFileList);
    if (uploadedFile.offsetParent === null) {
      uploadedFileList.style.display = "block";
    }
  },
  processUploadError: function(errorMessage) {
    var uploadedFileList = document.getElementById("uploaded-file-list");
    var uploadedFile = scriptJquery.crtEle('li', {
      'class': 'file file-error',
      events: {
        click: function() {
          this.destroy();
        }
      }
    }).html('<span class="validation-error" title="Click to remove this entry.">' + errorMessage + '</span>').prependTo(uploadedFileList, 'top');
    // If hidden show upload list
    if (uploadedFile.offsetParent === null) {
      uploadedFileList.style.display = "block";
    }
    scriptJquery('#files-status-overall').css('display', 'none');
    return false;
  },
};

en4.core.runonce.add(function () {
  scriptJquery('#upload-complete-message').css('display', 'none');
  scriptJquery('.file-input').on('change', function () {
    var files = this.files;
    var total = files.length;
    var iteration = 0;
    for(var i = 0; i < files.length; i++) {
      iteration++;
      BaseFileUpload.uploadFile(scriptJquery(this), this.files[i], iteration, total);
    }
  });
  scriptJquery('.file-input').on('click', function () {
    this.value = '';
  });
});

function multiDelete() {
  return confirm("<?php echo $this->translate("Are you sure you want to delete the selected files ?") ?>");
}
// Select/Deselect all
function selectAll(obj) {
  // only affect child checkboxes, not the master itself
  scriptJquery(".checkbox").not("#selectall").prop("checked", scriptJquery(obj).prop("checked"));
}

// Update master when any child checkbox is toggled
en4.core.runonce.add(function () {
  scriptJquery(document).on("change", ".checkbox", function () {
    if (this.id === "selectall") return; // skip master itself

    let total   = scriptJquery(".checkbox").not("#selectall").length;
    let checked = scriptJquery(".checkbox:checked").not("#selectall").length;

    // If all children are checked → check master
    // If any unchecked → uncheck master
    scriptJquery("#selectall").prop("checked", total === checked);
  });
});
</script>
<div class="admin_common_top_section">
  <h2 class="page_heading"><?php echo $this->translate("File & Media Manager") ?></h2>
  <p><?php echo $this->translate('You may want to quickly upload images, icons, or other media for use in your layout, announcements, blog entries, etc. You can upload and manage these files here. Move your mouse over a filename to preview an image.') ?></p>
  <?php
  $settings = Engine_Api::_()->getApi('settings', 'core');
	$user_admin = Zend_Registry::isRegistered('user_admin') ? Zend_Registry::get('user_admin') : null;
  if( $settings->getSetting('user.support.links', 0) == 1 ) {
    echo 'More info: <a href="https://community.socialengine.com/blogs/597/64/file-media-manager" target="_blank">See KB article</a>';
  } 
  ?>	
</div>  
<div>
	<?php if(!empty($user_admin)): ?>
		<?php echo $this->htmlLink('javascript:void(0);', $this->translate('Upload New Files'), array('id' => 'demo-browse', 'class' => 'admin_link_btn admin_files_upload', 'onclick' => 'uploadFile();')) ?>

		<?php if($this->existingFiles > 0) { ?>
			<a href="<?php echo $this->url(array('action' => 'sink')) ?>" class="smoothbox admin_link_btn"><?php echo $this->translate('Sink Existing Files') ?></a>
		<?php } ?>
	<?php endif; ?>
</div>
<div id="file-status">
  <div id="files-status-overall" style="display: none;">
    <div class="overall-title"><?php echo $this->translate("Overall Progress"); ?></div>
    <img src='<?php echo $this->layout()->staticBaseUrl . "/externals/fancyupload/assets/progress-bar/bar.gif" ?>' class="progress overall-progress">
    <span>0%</span>
  </div>

  <ul id="uploaded-file-list"></ul>
  <div id="base-uploader-progress"></div>
  <div class="base-uploader">
    <input class="file-input" id="upload_file" type="file" multiple="multiple" data-url="<?php echo $this->url(array('action' => 'upload'))?>" data-form-id="#form-upload" name='Filedata'>
  </div>

  <div id="upload-complete-message" style="display:none;">
    <?php echo $this->htmlLink(array('reset' => false), 'Refresh the page to display new files') ?>
  </div>
</div>
<div class='admin_search'>
  <?php echo $this->formFilter->render($this) ?>
</div>
<?php if(!empty($user_admin) && engine_count($this->paginator) ): ?>
  <div class="mb-2">
    <div>
      <?php echo $this->translate(array('%s file found.', '%s files found.', $this->paginator->getTotalItemCount()), $this->locale()->toNumber($this->paginator->getTotalItemCount())) ?>
    </div>
  </div>
  <form id='multidelete_form' method="post" action="<?php echo $this->url();?>" onSubmit="return multiDelete()">
    <div class="fmm_media_listing_head mb-3 d-flex justify-content-between align-items-center">
      <label for="selectall" class="select_fmm_all"><input id="selectall" onclick="selectAll(this);" type="checkbox" class="checkbox" /><?php echo $this->translate("Select All"); ?></label>
      <div class="listing_switcher d-flex align-items-center">
        <a onclick="showHide('list');" href="javascript:void(0);" class="active" id="list_switcher">
          <i class="fa-solid fa-bars"></i>
        </a>
        <a onclick="showHide('grid');" href="javascript:void(0);" id="grid_switcher">
          <i class="fa-solid fa-border-all"></i>
        </a>
      </div>
    </div>
  
    <ul id="file_grid_content" class="fmm_media_list">
      <?php foreach ($this->paginator as $item): ?>
        <?php $storage = Engine_Api::_()->getItem('storage_file', $item->storage_file_id);
        if($storage) {
        $path = $storage->map();
        $copyPath = ($storage->service_id == 2) ?  $path : $path; 
        ?>
        <li class="fmm_media_file">
         <div class="fmm_media_item">
          <div class="fmm_file_preview fmm_file_preview_image">
            <a href="<?php echo $this->url(array('action' => 'rename', 'file_id' => $item->file_id)) ?>" data-addclass="attachment_preview" class="ajaxsmoothbox">
              <?php if($item->extension == 'pdf'): ?>
                <img src="application/modules/Core/externals/images/admin/file-icons/pdf.png" alt="<?php echo $item->alt_text; ?>">
              <?php elseif(engine_in_array($item->extension, array('text', 'txt'))): ?>
                <img src="application/modules/Core/externals/images/admin/file-icons/text.png" alt="<?php echo $item->alt_text; ?>">
              <?php elseif(engine_in_array($item->extension, array('mpeg', 'x-realaudio', 'wav', 'amr', 'mp3', 'ogg','midi','x-ms-wma', 'x-ms-wax', 'x-matroska'))): ?>
                <img src="application/modules/Core/externals/images/admin/file-icons/audio.png" alt="<?php echo $item->alt_text; ?>">
              <?php elseif(engine_in_array($item->extension, array('mp4', 'flv'))): ?>
                <img src="application/modules/Core/externals/images/admin/file-icons/video.png" alt="<?php echo $item->alt_text; ?>">
              <?php elseif(engine_in_array($item->extension, array('zip', 'tar'))): ?>
                <img src="application/modules/Core/externals/images/admin/file-icons/zip.png" alt="<?php echo $item->alt_text; ?>">
              <?php elseif(engine_in_array($item->extension, array('jpeg', 'jpg', 'gif', 'png', 'tiff','webp','svg','SVG'))): ?>
                <img src="<?php echo $path; ?>" alt="<?php echo $item->alt_text; ?>" />
              <?php else: ?>
                <img src="application/modules/Core/externals/images/admin/file-icons/default.png" alt="<?php echo $item->alt_text; ?>">
              <?php endif; ?>
            </a>
          </div>
          <div class="fmm_media_item_footer">
            <div class="fmm_file_checkbox">
							<input type='checkbox' class='checkbox m-0' name='selectedItems[]' value='<?php echo $item->file_id ?>' />
						</div>
            <div class="fmm_file_name"><?php echo $item->name . '.'.$item->extension; ?></div>
            <div class="fmm_file_options">
              <a href="<?php echo $path; ?>" target="_blank" class="fa fmm_icon_preview" title="<?php echo $this->translate('Preview') ?>"></a>
              <a href="<?php echo $this->url(array('action' => 'rename', 'file_id' => $item->file_id)) ?>" data-addclass="attachment_preview"  class="ajaxsmoothbox fa fmm_icon_rename" title="<?php echo $this->translate('Rename') ?>"></a>
              <a href="<?php echo $this->url(array('action' => 'delete', 'file_id' => $item->file_id)) ?>" class="smoothbox fa fmm_icon_delete" title="<?php echo $this->translate('Delete') ?>"></a>
              <a href="<?php echo $this->url(array('action' => 'download', 'file_id' => $item->file_id)) ?>" class="fa fmm_icon_download" title="<?php echo $this->translate('Download') ?>"></a>
              <a href="javascript:void(0);" onclick="fileCopyUrl('<?php echo $copyPath; ?>');" class="fa fmm_icon_url" title="<?php echo $this->translate('Copy URL') ?>"></a>
            </div>
          </div>
          </div>
        </li>
      <?php } endforeach; ?>
    </ul>

    <div id="file_list_content" class="admin_table_form" style="display: none;">
      <table class="admin_table admin_responsive_table">
        <thead>
          <tr>
            <th style="width: 1%;"></th>
            <th><?php echo $this->translate("File"); ?></th>
            <th><?php echo $this->translate("File Name"); ?></th>
						<th><?php echo $this->translate("Alternative Text"); ?></th>
            <th><?php echo $this->translate("Date"); ?></th>
            <th style="" class="admin_table_options"><?php echo $this->translate("Options"); ?></th>
          </tr>
        </thead>
        <tbody>

          <?php foreach ($this->paginator as $item): ?>
            <?php $storage = Engine_Api::_()->getItem('storage_file', $item->storage_file_id);
            if($storage) {
            $path = $storage->map();
            $copyPath = ($storage->service_id == 2) ?  $path : $path; 
            ?>
            <tr>
              <td><input type='checkbox' class='checkbox m-0' name='delete_<?php echo $item->file_id;?>' value='<?php echo $item->file_id ?>' /></td>
              <td data-label="File">
                <div class="fmm_file_preview fmm_file_preview_image">
                  <a href="<?php echo $this->url(array('action' => 'rename', 'file_id' => $item->file_id)) ?>" data-addclass="attachment_preview" class="ajaxsmoothbox">
                    <?php if($item->extension == 'pdf'): ?>
                      <img src="application/modules/Core/externals/images/admin/file-icons/pdf.png" alt="<?php echo $item->alt_text; ?>">
                    <?php elseif(engine_in_array($item->extension, array('text', 'txt'))): ?>
                      <img src="application/modules/Core/externals/images/admin/file-icons/text.png" alt="<?php echo $item->alt_text; ?>">
                    <?php elseif(engine_in_array($item->extension, array('mpeg', 'x-realaudio', 'wav', 'amr', 'mp3', 'ogg','midi','x-ms-wma', 'x-ms-wax', 'x-matroska'))): ?>
                      <img src="application/modules/Core/externals/images/admin/file-icons/audio.png" alt="<?php echo $item->alt_text; ?>">
                    <?php elseif(engine_in_array($item->extension, array('mp4', 'flv'))): ?>
                      <img src="application/modules/Core/externals/images/admin/file-icons/video.png" alt="<?php echo $item->alt_text; ?>">
                    <?php elseif(engine_in_array($item->extension, array('zip', 'tar'))): ?>
                      <img src="application/modules/Core/externals/images/admin/file-icons/zip.png" alt="<?php echo $item->alt_text; ?>">
                    <?php elseif(engine_in_array($item->extension, array('jpeg', 'jpg', 'gif', 'png', 'tiff','webp'))): ?>
                      <img src="<?php echo $path; ?>" alt="<?php echo $item->alt_text; ?>" />
                    <?php else: ?>
                      <img src="application/modules/Core/externals/images/admin/file-icons/default.png" alt="<?php echo $item->alt_text; ?>">
                    <?php endif; ?>
                  </a>
                </div>
              </td>
              <td data-label='<?php echo $this->translate("File Name")?>'><?php echo $item->name . '.'.$item->extension; ?></td>
							<td data-label='<?php echo $this->translate("Alternative Text");?>'><?php echo $item->alt_text ?? '---'; ?></td>
              <td data-label='<?php echo $this->translate("Date");?>'><?php echo $this->locale()->toDateTime($item->creation_date) ?></td>
              <td class="admin_table_options">
                <a href="<?php echo $path; ?>" target="_blank"><?php echo $this->translate('View') ?></a>
                &nbsp;|&nbsp;
                <a href="<?php echo $this->url(array('action' => 'rename', 'file_id' => $item->file_id)) ?>" data-addclass="attachment_preview" class="ajaxsmoothbox"><?php echo $this->translate('Edit') ?></a>
                &nbsp;|&nbsp;
                <a href="<?php echo $this->url(array('action' => 'download', 'file_id' => $item->file_id)) ?>" title=""><?php echo $this->translate('Download') ?></a>
                &nbsp;|&nbsp;
                <a href="<?php echo $this->url(array('action' => 'delete', 'file_id' => $item->file_id)) ?>" class="smoothbox text-danger"><?php echo $this->translate('Delete') ?></a>
              </td>
            </tr>
          <?php } endforeach; ?>
        </tbody>
      </table>
    </div>
    <div class='buttons'>
      <button type='submit'><?php echo $this->translate("Delete Selected") ?></button>
    </div>

		<input type="hidden" name="file_view_type" value="<?php echo $this->file_view_type; ?>">
  </form>
  <div>
		<?php echo $this->paginationControl(
    $this->paginator, null, null, array('pageAsQuery' => false, 'query' => array('page' => $this->page, 'file_view_type' => $this->file_view_type))); ?>
    <?php //echo $this->paginationControl($this->paginator); ?>
  </div>
<?php else: ?>
  <div class="tip">
    <span>
      <?php echo $this->translate("There are no files uploaded by you yet.") ?>
    </span>
  </div>
<?php endif; ?> 
<script type="application/javascript">
	function showHide(value) {
		if(value == 'list') {
			scriptJquery('#grid_switcher').addClass('active');
			scriptJquery('#list_switcher').removeClass('active');
			scriptJquery('#file_list_content').show();
			scriptJquery('#file_grid_content').hide();
		} else {
			scriptJquery('#list_switcher').addClass('active');
			scriptJquery('#grid_switcher').removeClass('active');
			scriptJquery('#file_list_content').hide();
			scriptJquery('#file_grid_content').show();
		}
	}

  scriptJquery('.core_admin_main_layout').parent().addClass('active');
  scriptJquery('.core_admin_main_layout_files').addClass('active');
</script>
