{{> adminHeader}}
<title>All ALBUMS</title>
<style>
    table {
        width: 100%;
        border-collapse: collapse;
    }

    th,
    td {
        padding: 8px 12px;
        text-align: left;
        border: 1px solid #ddd;
    }

    th.si-no,
    td.si-no {
        width: 50px;
    }

    th.action,
    td.action {
        width: 100px;
    }

    th.banner,
    td.banner {
        width: 300px;
    }

    th.banner {
        white-space: nowrap;
    }

    @media screen and (max-width: 768px) {

        th,
        td {
            font-size: 14px;
        }
    }

    .bg-success {
        background-color: #28a745 !important;
        /* Bootstrap default green */
    }

    .toast-body {
        font-weight: bold;
    }

    .select2-container--default .select2-selection--multiple .select2-selection__rendered li:first-child.select2-search.select2-search--inline .select2-search__field {
        width: 45px !important;
    }
</style>

<style>
    /* Hide the clear "x" button in the select2 input */
    .select2-selection__clear {
        display: none !important;
    }
</style>

<div id="toastContainer" class="toast-container position-fixed bottom-0 end-0 p-3" style="z-index: 1050;">Album
    <!-- Toast notifications will be appended here -->
</div>


<div class="row p-2" style="margin: 0px !important;">
    <div class="col-md-12">
        <div class="card mt-2" style="border-left: 2px solid black;">
            <div class="card-header" style="background-color: white; color:white;">
                <h4><b>ALL ALBUMS</b></h4>
            </div>
            <div class="card-body p-2">
                <div id="example1_wrapper">
                    <div class="row">
                        <div class="col-12">
                            <ol class="float-sm-right">
                                <form action="/admin/posterpage">
                                    <button data-bs-toggle="modal" data-bs-target="#addModal"
                                        style="background-color: #121212; color: #CBA255; border:none; border-radius:5px; width: 180px; height: 40px;">
                                        <i class="fa-solid fa-plus"></i> Add Album
                                    </button>
                                </form>
                            </ol>
                        </div>
                        <div class="col-sm-12 table-responsive">
                            <table id="example2" aria-describedby="example1_info">
                                <thead>
                                    <tr>
                                        <th class="si-no" style="width: 70px; text-align: center;">S.No</th>
                                        {{!-- <th class="si-no" style="width: 70px; text-align: center;">S.No</th> --}}
                                        <th class="banner" style="text-align: center;">Album Name</th>
                                        <th class="banner" style="text-align: center;">Album Picture</th>
                                        <th class="banner" style="text-align: center;">Languages</th>
                                        <th class="banner" style="text-align: center;">Release Date</th>
                                        {{!-- <th class="banner" style="text-align: center;">To Date</th> --}}
                                        <th class="action" style="text-align: center;">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    

                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Update Poster Modal -->
<div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                {{!-- <h3 class="modal-title" style="color: #CBA255; font-weight: bold; font-size: 20px;">Update Banner
                </h3> --}}
                <h3><b>Update Album</b></h3>
            </div>
            <form id="updatePosterForm" action="" method="post" enctype="multipart/form-data">
                <div class="modal-body">
                    <label for="albumName">Album Name</label>
                    <input type="text" id="albumName" class="form-control" name="albumName" value="" required>
                </div>
                <div class="modal-body">
                    <label>Release Date</label>
                    <input type="date" class="form-control" name="fromDate" required placeholder="Select Start Date">
                </div>
                <div class="modal-body">
                    <label for="languagesDropdown" class="languages">Languages</label><br>
                    <select id="languagesDropdown" name="languages[]" class="form-control" multiple>
                        <option value="Telugu">Telugu</option>
                        <option value="Tamil">Tamil</option>
                        <option value="Kannada">Kannada</option>
                        <option value="Hindi">Hindi</option>
                        <option value="Sanskrit">Sanskrit</option>
                        <option value="Urdu">Urdu</option>
                    </select>
                </div>
                <div class="modal-body">
                    <label for="albumPic">New Album Picture</label>
                    <input type="file" id="updateposterPicture" class="modal-file" name="albumPic"
                        accept=".jpg, .jpeg, .png">
                    <p style="color: #CBA255; margin-top: 5px;">Recommended dimensions must be width 250 & height 300
                        pixels.</p>
                </div>
                <div class="modal-body">
                    <label for="currentPosterPicture">Current Poster Picture</label>
                    <img id="currentPosterPicture" src="" height="60px" alt="Album Picture">
                </div>
                <div class="modal-body">
                    <label for="sno">Serial Number</label>
                    <input type="number" id="sno" class="form-control" name="sno" required
                        placeholder="Enter Serial Number" value="">
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-success"
                        style="background-color: #121212; color: #CBA255;">Update</button>
                </div>
            </form>
        </div>
    </div>
</div>


<!-- Delete Poster Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" style="color: black; font-weight: 480;">Are you sure you want to delete this
                    Featured album?</h4>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-info" style="background-color: #c82333; color: white;"
                    data-bs-dismiss="modal">No</button>
                <a href="" id="deleteConfirmButton" type="button" style="background-color: black; color: #CBA255;"
                    class="btn btn-danger">Yes</a>
            </div>
        </div>
    </div>
</div>

{{> adminFooter}}

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>

<script>
    $(document).ready(function () {
        $('#languagesDropdown').select2({
            allowClear: true // Allow clearing selections if needed
        });
    });

</script>


{{!-- seatch --}}
{{!--
<script>
    $(document).ready(function () {
        // DataTables Initialization
        if (!$.fn.DataTable.isDataTable('#example2')) {
            $('#example2').addClass('table table-bordered table-striped').DataTable({
                "paging": true,
            });
        }
    });
</script> --}}

{{!--
<script>
    $(document).ready(function () {
        // Initialize DataTable with search enabled
        if (!$.fn.DataTable.isDataTable('#example2')) {
            $('#example2').addClass('table table-bordered table-striped').DataTable({
                "paging": true, // Enable pagination
                "searching": true, // Enable searching (default is true)
            });
        }
    });
</script>

<script>
    var table = $('#example2').DataTable();

    $('#customSearchBox').on('keyup', function () {
        table.search(this.value).draw();
    });

</script> --}}


{{!-- <script>
    $(document).ready(function () {
        // Initialize DataTable
        var table = $('#example2').addClass('table table-bordered table-striped').DataTable({
            "paging": true, // Enable pagination
            "searching": true, // Enable search functionality
        });

        // Custom search logic for matching strings regardless of spaces
        $.fn.dataTable.ext.search.push(
            function (settings, data) {
                var searchValue = table.search().trim(); // Get the current value in the search box
                if (searchValue) {
                    // Normalize the search input (remove spaces, convert to lowercase)
                    var normalizedSearch = searchValue.replace(/\s+/g, '').toLowerCase();

                    // Check if any column in the row matches the normalized search value
                    for (var i = 0; i < data.length; i++) {
                        // Normalize the cell content
                        var normalizedCell = data[i].replace(/\s+/g, '').toLowerCase();
                        var originalCell = data[i].toLowerCase();

                        // Check if either normalized cell or original cell includes the search term
                        if (
                            normalizedCell.includes(normalizedSearch) ||
                            originalCell.includes(searchValue.toLowerCase())
                        ) {
                            return true; // Show the row if a match is found
                        }
                    }
                    return false; // Hide the row if no match is found
                }
                return true; // Show all rows if the search box is empty
            }
        );

        // Trigger table redraw when the search input changes
        $('#example2_filter input').on('input', function () {
            table.draw();
        });
    });
</script> --}}
<script>
  const allPosters = {{{json allPosters}}}; // This helper must safely stringify JSON in Handlebars
</script>

<script>
  $(document).ready(function () {
    const table = $('#example2').DataTable({
      data: allPosters,
      pageLength: 10,
      lengthChange: true,
      paging: true,
      searching: true,
      ordering: true,
      info: true,
      autoWidth: false,
      responsive: true,
      deferRender: true,
      processing: true,
      dom: '<"top"lf>rt<"bottom"ip><"clear">',
      stripeClasses: ['odd', 'even'],
      columns: [
        {
          data: null,
          className: 'text-center',
          render: function (data, type, row, meta) {
            return `JSE-${data.sno.toString()}`;
          }
        },
        { data: 'albumName', defaultContent: '' },
        {
          data: 'albumPic',
          defaultContent: '',
          render: function (data) {
            return data ? `<img src="/${data}" height="60px" alt="Album Image">` : '';
          }
        },
        { data: 'languages', defaultContent: '' },
        {
          data: 'fromDate',
          defaultContent: '',
          render: function (data) {
            if (!data) return '';
            const date = new Date(data);
            return isNaN(date) ? '' : date.toLocaleDateString('en-IN');
          }
        },
        {
          data: '_id',
          defaultContent: '',
          render: function (id, type, row) {
            return `
              <div class="actions d-flex justify-content-start align-items-center">
                <a href="/admin/poster/${id}" class="btn btn-md btn-secondary me-1">
                  <i class="fas fa-eye"></i>
                </a>
                <a href="#" class="btn btn-md btn-secondary me-1"
                   data-bs-toggle="modal" data-bs-target="#updateModal"
                   data-id="${id}"
                   data-albumName="${row.albumName || ''}"
                   data-languages="${row.languages || ''}"
                   data-posterPicture="${row.albumPic || ''}"
                   data-sno="${row.sno || ''}"
                   data-fromdate="${row.fromDate || ''}">
                  <i class="fas fa-edit" style="color: #CBA255;"></i>
                </a>
                <a href="#" class="btn btn-md btn-danger"
                   data-bs-toggle="modal" data-bs-target="#deleteModal"
                   data-id="${id}">
                  <i class="fas fa-trash" style="color: #CBA255;"></i>
                </a>
              </div>
            `;
          }
        }
      ]
    });

    // Optional: Fuzzy search logic
    $.fn.dataTable.ext.search.push(function (settings, data) {
      const searchValue = table.search().trim().toLowerCase().replace(/\s+/g, '');
      if (!searchValue) return true;
      return data.some(cell => cell.toString().toLowerCase().replace(/\s+/g, '').includes(searchValue));
    });

    // Redraw table on search input
    $('#example2_filter input').on('input', function () {
      table.draw();
    });
  });
</script>

{{!-- update --}}
{{!--
<script>
    $(document).ready(function () {
        // Show modal and prefill data
        $('#updateModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget); // Button that triggered the modal
            var posterId = button.data('id');
            var albumName = button.data('albumname');
            var languages = button.data('languages').split(',');
            var fromDate = button.data('fromdate'); // Matches `data-fromdate` in HTML
            var posterPicture = button.data('posterpicture');
            var posterPicturePath = '/' + posterPicture;

            // Ensure date format is correct
            if (fromDate) {
                // Convert to YYYY-MM-DD format if necessary
                const dateObj = new Date(fromDate);
                fromDate = dateObj.toISOString().split('T')[0];
            }

            var modal = $(this);
            modal.find('form#updatePosterForm').attr('action', '/admin/updateposters/' + posterId);
            modal.find('#albumName').val(albumName);
            modal.find('input[name="fromDate"]').val(fromDate);
            modal.find('#currentPosterPicture').attr('src', posterPicturePath);

            // Reset and check appropriate languages
            modal.find('#languagesDropdown').val([]); // Reset dropdown
            languages.forEach(function (language) {
                modal.find(`#languagesDropdown option[value="${language.trim()}"]`).prop('selected', true);
            });

            modal.find('#languagesDropdown').trigger('change');
        });


        // Handle form submission via AJAX
        $('#updatePosterForm').on('submit', function (e) {
            e.preventDefault();

            const form = $(this);
            const formData = new FormData(this);
            const actionUrl = form.attr('action');

            // Append languages to the formData
            const selectedLanguages = $('#languagesDropdown').val();
            formData.append('languages', selectedLanguages);

            $.ajax({
                url: actionUrl,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    if (response.success) {
                        // Close modal
                        $('#updateModal').modal('hide');

                        // Show success message
                        showToast('Album updated successfully!', 'success'); // Green toast


                        // Refresh or update the relevant table row
                        const updatedPoster = response.data;
                        const row = $(`#example2`).find(`[data-id="${updatedPoster._id}"]`).closest('tr');
                        row.find('td:nth-child(2)').text(updatedPoster.albumName);
                        row.find('td:nth-child(3)').text(updatedPoster.fromDate);
                        row.find('td:nth-child(4)').text(updatedPoster.languages.join(', '));

                        // Optionally reload the table
                        // location.reload();
                    } else {
                        showToast('Failed to update album. Please try again.', 'danger');
                    }
                },
                error: function (error) {
                    console.error('Error:', error);
                    showToast('An error occurred while updating the album.', 'danger');
                }
            });
        });

        // Clear modal data on close
        $('#updateModal').on('hidden.bs.modal', function () {
            $(this).find('form')[0].reset();
            $(this).find('#languagesDropdown').val([]).trigger('change');
            $(this).find('#currentPosterPicture').attr('src', '');
        });

        // Toast notification function
        function showToast(message, type) {
            const bgClass = type === 'success' ? 'bg-success text-light' : 'bg-danger text-light'; // Green for success, red for danger
            const toastId = `toast-${Date.now()}`; // Unique ID for each toast
            const toastHTML = `
        <div id="${toastId}" class="toast align-items-center ${bgClass} border-0" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="5000" data-bs-autohide="true">
            <div class="d-flex">
                <div class="toast-body">
                    ${message}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        </div>
    `;
            $('#toastContainer').append(toastHTML);

            const toastElement = $(`#${toastId}`);
            // Initialize and show the toast
            const bsToast = new bootstrap.Toast(toastElement[0], {
                delay: 3000, // Ensure delay is set for 5 seconds
                //autohide: true
            });
            bsToast.show();

            // Remove toast after it is hidden
            toastElement.on('hidden.bs.toast', function () {
                $(this).remove();
            });
        }
    });
</script> --}}
<script>
    $(document).ready(function () {
        // Show modal and prefill data
        $('#updateModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget); // Button that triggered the modal
            var posterId = button.data('id');
            var albumName = button.data('albumname');
            var serialNo = button.data('sno');
            var languages = button.data('languages').split(',');
            var fromDate = button.data('fromdate'); // Matches `data-fromdate` in HTML
            var posterPicture = button.data('posterpicture');
            var posterPicturePath = '/' + posterPicture;

            // Ensure date format is correct
            if (fromDate) {
                // Convert to YYYY-MM-DD format if necessary
                const dateObj = new Date(fromDate);
                fromDate = dateObj.toISOString().split('T')[0];
            }

            var modal = $(this);
            modal.find('form#updatePosterForm').attr('action', '/admin/updateposters/' + posterId);
            modal.find('#albumName').val(albumName);
            modal.find('#sno').val(serialNo);
            modal.find('input[name="fromDate"]').val(fromDate);
            modal.find('#currentPosterPicture').attr('src', posterPicturePath);

            // Reset and check appropriate languages
            modal.find('#languagesDropdown').val([]); // Reset dropdown
            languages.forEach(function (language) {
                modal.find(`#languagesDropdown option[value="${language.trim()}"]`).prop('selected', true);
            });

            modal.find('#languagesDropdown').trigger('change');
        });


        // Handle form submission via AJAX
        $('#updatePosterForm').on('submit', function (e) {
            e.preventDefault();

            const form = $(this);
            const formData = new FormData(this);
            const actionUrl = form.attr('action');

            // Append languages to the formData
            const selectedLanguages = $('#languagesDropdown').val();
            formData.append('languages', selectedLanguages);

            $.ajax({
                url: actionUrl,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    if (response.success) {
                        // Close modal
                        $('#updateModal').modal('hide');

                        // Show success message
                        showToast('Album updated successfully!', 'success'); // Green toast

                        // Reload the page after a short delay to ensure user sees the success message
                        setTimeout(function () {
                            location.reload();
                        }, 1000);
                    } else {
                        showToast("Album with serialNo already exists", 'danger');
                    }
                },
                error: function (error) {
                    console.error('Error:', error);
                    showToast('An error occurred while updating the album.', 'danger');
                }
            });
        });

        // Clear modal data on close
        $('#updateModal').on('hidden.bs.modal', function () {
            $(this).find('form')[0].reset();
            $(this).find('#languagesDropdown').val([]).trigger('change');
            $(this).find('#currentPosterPicture').attr('src', '');
        });

        // Toast notification function
        function showToast(message, type) {
            const bgClass = type === 'success' ? 'bg-success text-light' : 'bg-danger text-light'; // Green for success, red for danger
            const toastId = `toast-${Date.now()}`; // Unique ID for each toast
            const toastHTML = `
            <div id="${toastId}" class="toast align-items-center ${bgClass} border-0" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="5000" data-bs-autohide="true">
                <div class="d-flex">
                    <div class="toast-body">
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            </div>
        `;
            $('#toastContainer').append(toastHTML);

            const toastElement = $(`#${toastId}`);
            // Initialize and show the toast
            const bsToast = new bootstrap.Toast(toastElement[0], {
                delay: 3000, // Ensure delay is set for 5 seconds
            });
            bsToast.show();

            // Remove toast after it is hidden
            toastElement.on('hidden.bs.toast', function () {
                $(this).remove();
            });
        }
    });

</script>


{{!-- delete --}}
<script>
    $('#deleteModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget);
        var posterId = button.data('id');
        var modal = $(this);
        modal.find('#deleteConfirmButton').attr('href', '/admin/deleteposters/' + posterId);
    });
</script>

