<?php
require_once('config.php');

if (isset($_GET['delete'])) {
  $tt_delete_id = $_GET['delete'];
  $tt_media_file = '../uploads/'.getSingleValue('tt_media', 'MediaId', $tt_delete_id, 'MediaName');

  if (file_exists($tt_media_file)) {
      // Attempt to delete the file
      if (unlink($tt_media_file)) {

        if (deleteData('tt_media', 'MediaId', $tt_delete_id)) {
          header('Location:media-library.php');
          exit;
        }

      } else {
        $tt_alert = ttAlert('warning', 'Error deleting the file.');
      }
  }else {
    if (deleteData('tt_media', 'MediaId', $tt_delete_id)) {
      header('Location:media-library.php');
      exit;
    }
  }
}

require_once('inc/header.php');
?>
<main id="main" class="main">
  <div class="row">
    <div class="col-6 align-items-center">
      <div class="pagetitle mb-0">
        <h1><?php echo $page_title ?></h1>
      </div>
    </div>
    <div class="col-6 text-end">
      <a href="add-media.php" class="btn btn-primary btn-sm"><i class="ri-arrow-left-line"></i>Add Media  </a>
    </div>
  </div>
  <?php
    echo $tt_alert;
  ?>
  <section class="section dashboard">
    <div class="row">
      <div class="col-lg-12">
        <div class="searchbar_container p-2 mt-3">
            <div class="row" style="--bs-gutter-x:0">
                <div class="col-3 d-flex">
                    <select id="articleCategory" class="form-select">
                        <option value="all">All</option>
                        <option value="7">Image</option>
                        <option value="34">Video</option>
                        <option value="34">Document</option>
                    </select>
                </div>
                <div class="col-7 col-md-8 d-flex">
                    <i class="ab_line"></i>
                    <i class="bi bi-search search_icon"></i>
                    <div class="img_search_input">
                      <input id="articleSearchvalue" type="text" class="form-control" placeholder="Search Image Name...">
                    </div>
                </div>
                <div class="col-2 col-md-1 d-flex text-end">
                    <i class="ab_line ms-3"></i>
                    <span data-grid="list" id="changeView" class="view_type_button"><i class="bi bi-hdd-stack-fill"></i></span>
                </div>
            </div>
        </div>
       </div>
    </div>
    <div class="page-body mt-3">
      <div id="content">
          <?php
          $media_library = showAllttdata('tt_media', 'ORDER BY  MediaId  DESC LIMIT 24');
          if (!empty($media_library)){
            echo "<div class='row' id='mediaContainer'>";
            foreach ($media_library as $the_media) {
              ?>
              <div class="col-4 col-sm-4 col-md-3 col-lg-2  mb-2">
                <div class="attachment-preview " data-bs-toggle="modal" data-bs-target="#mediaInformation<?php echo $the_media['MediaId'] ?>">
                  <div class="thumbnail">
                    <?php
                    $tt_file_type = isImage($the_media['MediaName']);
                    if ($tt_file_type == 'image') {
                      ?>
                      <div class="centered">
                        <img src="<?php echo $the_media['MediaURL'] ?>" alt="<?php echo $the_media['MediaName'] ?>">
                      </div>
                      <?php
                    }else {
                      ?>
                      <div class="text-center">
                        <span class="p-1 mb-2 bg-primary text-white d-block"><i class="fs-3 ri-file-warning-line"></i></span>
                        <span class="fs-6"><?php echo $the_media['MediaName'] ?></span>
                      </div>
                      <?php
                    }
                    ?>
                  </div>
                </div>
              </div>
              <div class="modal fade" id="mediaInformation<?php echo $the_media['MediaId'] ?>" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-dialog-scrollable modal-xl">
                  <div class="modal-content border-0 rounded-0">
                    <div class="modal-header p-2">
                      <h5 class="modal-title">Media details</h5>
                      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="bg-white" style="overflow-x:hidden;">
                      <div class="row">
                        <div class="col-lg-8">
                          <div class="p-3">
                            <?php
                            if ($tt_file_type == 'image') {
                              ?>
                              <div class=" thumbnail-image">
                                <img class="details-image" src="<?php echo $the_media['MediaURL'] ?>" draggable="false"  alt="<?php echo $the_media['MediaName'] ?>">
                              </div>
                              <?php
                            }else {
                              ?>
                              <div class="text-center bg-light rounded-3 p-4">
                                <span style="text-transform:uppercase" class="p-2 fs-3 bg-primary text-white rounded-3"><?php echo $tt_file_type ?></span>
                                <br>
                                <span class="mt-3 fs-6 d-block"><?php echo $the_media['MediaName'] ?></span>
                              </div>
                              <?php
                            }
                             ?>
                          </div>
                        </div>
                        <div class="col-lg-4 bg-light">
                          <div class="p-2">
                            <p class="mb-2 rounded-2">
                              <strong>Uploaded on:</strong> <?php echo date('F j, Y', strtotime($the_media['MediaUploadedTime'])); ?>
                            </p>
                            <p class="mb-2 rounded-2">
                              <strong>Uploaded by:</strong> <?php echo getSingleValue('admin_user', 'admin_id', $the_media['MediaUploader'], 'admin_name') ?>
                            </p>
                            <p class="mb-2 rounded-2">
                              <strong>File name:</strong> <?php echo $the_media['MediaName'] ?>
                            </p>
                            <p class="mb-2 rounded-2">
                              <strong>File type:</strong>
                              <?php
                              if ($tt_file_type == 'image') {
                                echo "Image file";
                              }else {
                                echo $tt_file_type. ' file';
                              }
                              ?>
                            </p>
                            <p class="mb-2 rounded-2">
                              <strong>File size:</strong>
                              <?php
                              $fileSizeBytes = filesize('../uploads/'.$the_media['MediaName']);
                              if ($fileSizeBytes < 1024) {
                                  echo  $fileSizeBytes . ' bytes';
                              } elseif ($fileSizeBytes < (1024 * 1024)) {
                                  echo  round($fileSizeBytes / 1024, 2) . ' KB';
                              } else {
                                  echo  round($fileSizeBytes / (1024 * 1024), 2) . ' MB';
                              }
                               ?>
                            </p>
                            <?php
                            if ($tt_file_type == 'image') {
                              ?>
                              <p class="mb-2 rounded-2">
                                <strong>Dimensions:</strong>
                                <?php
                                $imageSize = getimagesize('../uploads/'.$the_media['MediaName']);
                                echo   $imageSize[0].' by '.$imageSize[1].'pixels';
                                ?>
                              </p>
                              <?php
                            }
                             ?>
                             <div class="input-group my-3">
                                 <input id="textToCopy" value="<?php echo $the_media['MediaURL'] ?>" type="url" class="form-control form-control-sm rounded-0 border-success">
                                 <a href="javascript:void(0);" class="btn-sm input-group-text border-success bg-success text-white rounded-0 copy_link" onclick="navigator.clipboard.writeText('<?php echo $the_media['MediaURL']; ?>')">
                                     <i class="ri-links-line pe-2"></i> Copy Link
                                 </a>
                             </div>
                            <div class="row mb-3">
                              <div class="col-6">
                                <a  onclick="confirmDelete(event)" href="media-library.php?delete=<?php echo $the_media['MediaId'] ?>" class="btn btn-danger rounded-0 btn-sm w-100 text-center"><i class="ri-delete-bin-2-fill"></i> Delete Media</a>
                              </div>
                              <div class="col-6">
                                <a  href="<?php echo $the_media['MediaURL'] ?>"  target="_blank" class="delete-action btn btn-primary rounded-0 btn-sm w-100 text-center"> <i class=" ri-arrow-right-line"></i> View Media</a>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <?php
            }
            ?>
            </div>
            <div class="col-12 text-center mt-2">
              <div id="loader" class="col-md-12 text-center py-4" style="display: none;"><img src="assets/img/loading.gif" style=" height:40px;"></div>

              <button id="loadMoreBtn" class="btn btn-primary" type="button">Load More</button>
            </div>
            <?php
          }else {
            ?>
            <div class="col-12">
                <p class="m-0 text-muted  rounded-3 p-3 text-center bg-white">No Media Found !</p>
            </div>
            <?php
          }
           ?>
      </div>
    </div>
  </section>
</main>
<script>
$(document).ready(function() {
    var page = 3;
    var data_type = 'all_media';

    $('#loadMoreBtn').on('click', function() {
      $('#loader').show();
        // Make an AJAX request when the button is clicked
        $.ajax({
            url: 'inc/fetch-media.php',
            type: 'POST',
            data: {
              page: page,
              data_type :data_type
            },
            dataType: 'html',
            success: function(data) {
                // Append the fetched data to the media container
                $('#loader').hide();
                $('#mediaContainer').append(data);

                page++; // Increment the page for the next request
            },
            error: function() {
                alert('Error loading more content.');
            }
        });
    });
});
</script>
<?php require_once('inc/footer.php'); ?>
