{{>adminHeader}}
<title>ALL LYRIC WRITERS</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;
        }
    }

    /* Styling for select fields */
    select {
        background-color: #121212;
        color: #CBA255;
        padding: 0%;
        width: 100%;
        border: none;
        border-radius: 5px;
        cursor: pointer;
    }

    select:hover {
        background-color: #1a1a1a;
        color: #CBA255;
    }

    /* Styling for options inside select */
    option {
        background-color: #121212;
        color: #CBA255;
    }

    /* Styling for hovered options */
    select option:hover {
        background-color: #1a1a1a;
        color: #CBA255;
    }

    /* Adding focus state for better interaction */
    select:focus {
        outline: none;
        box-shadow: 0 0 5px rgba(203, 162, 85, 0.8);
    }

    .switch {
        position: relative;
        display: inline-block;
        width: 60px;
        height: 34px;
    }

    /* Hide default HTML checkbox */
    .switch input {
        opacity: 0;
        width: 0;
        height: 0;
    }

    /* The slider */
    .slider {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: red;
        /* Red for off state */
        transition: .4s;
    }

    .slider:before {
        position: absolute;
        content: "";
        height: 26px;
        width: 26px;
        left: 4px;
        bottom: 4px;
        background-color: white;
        transition: .4s;
    }

    input:checked+.slider {
        background-color: green;
        /* Green for on state */
    }

    input:focus+.slider {
        box-shadow: 0 0 1px #2196F3;
    }

    input:checked+.slider:before {
        transform: translateX(26px);
    }

    /* Rounded sliders */
    .slider.round {
        border-radius: 34px;
    }

    .slider.round:before {
        border-radius: 50%;
    }
</style>

<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">
                <h4><b>ALL LYRIC WRITERS</b></h4>
            </div>
            <div class="card-body p-2">
                <div id="example1_wrapper">
                    <div class="row">
                        <div class="col-sm-12">
                            <ol class="float-sm-right">
                                <button id="addMemberButton" 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 Lyric Writer
                                </button>
                            </ol>
                        </div>
                        <div class="col-sm-12 table-responsive">
                            <table id="example2" aria-describedby="example1_info">
                                <thead>
                                    <tr>
                                        <th class="si-no" style="text-align: center;">S.No</th>
                                        <th class="banner" style="text-align: center;">Name</th>
                                        <th class="banner" style="text-align: center;">Picture</th>
                                        <th class="action" style="text-align: center;">Action</th>
                                    </tr>
                                </thead>
                                <tbody id="tableBody">
                                    {{#each allWriters}}
                                    <tr draggable="true" ondragstart="drag(event)" id="row-{{@index}}"
                                        data-id="{{this._id}}">
                                        <td>{{inc @index}}</td>
                                        <td>{{this.name}}</td>
                                        <td><img src="/{{this.picture}}" height="60px" alt="Profile Picture"></td>
                                        <td>
                                            <div class="d-flex justify-content-center">
                                                <a href="javascript:void(0);" data-bs-toggle="modal"
                                                    data-bs-target="#updateModal" class="btn btn-md btn-info m-1"
                                                    data-id="{{this._id}}" data-name="{{this.name}}"
                                                    data-picture="{{this.picture}}"
                                                    data-recommendation="{{this.recommendation}}">
                                                    <i class="fa-solid fa-edit"
                                                        style="background-color: #121212; color: #CBA255"></i>
                                                </a>
                                                <a href="javascript:void(0);" data-bs-toggle="modal"
                                                    data-bs-target="#deleteModal" class="btn btn-md btn-danger m-1"
                                                    data-id="{{this._id}}">
                                                    <i class="fa-solid fa-trash"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                    {{/each}}
                                </tbody>
                            </table>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Artist Modal -->
<div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h3><b>Add Lyric Writer</b></h3>
            </div>
            <form id="addMemberForm" action="/admin/addwriter" method="post" enctype="multipart/form-data">
                <div class="modal-body">
                    <label for="name">Name</label>
                    <input type="text" class="form-control" name="name" minlength="3" maxlength="30" required>
                </div>
                <div class="modal-body">
                    <label for="picture">Picture</label>
                    <input type="file" id="addMemberPicture" class="modal-file" name="picture"
                        accept=".jpg, .img, .jpeg, .png" required>
                    <p style="color: #CBA255; margin-top: 5px;">Recommended dimensions must be 100 * 100 pixels.</p>
                </div>
                {{!-- <div class="modal-body">
                    <label>Preference</label>
                    <div class="form-check form-switch">
                        <label class="switch">
                            <input type="checkbox" name="recommendation">
                            <span class="slider round"></span>
                        </label>
                    </div>
                </div> --}}
                <div class="modal-footer">
                    <button type="submit" class="btn btn-success" style="background-color: #121212; color: #CBA255;">Add
                        Lyric Writer</button>
                </div>
            </form>
        </div>
    </div>
</div>


<script>
    document.addEventListener('DOMContentLoaded', () => {
        const addMemberForm = document.getElementById('addMemberForm'); // Form element
        const submitButton = addMemberForm.querySelector('button[type="submit"]'); // Submit button

        // Add an event listener for the form submission
        addMemberForm.addEventListener('submit', function (e) {
            e.preventDefault(); // Prevent the default form submission

            // Change button text to "Adding..."
            submitButton.textContent = 'Adding...';
            submitButton.disabled = true; // Disable the button to prevent multiple clicks

            // Optionally, submit the form after a slight delay to allow UI changes
            setTimeout(function () {
                addMemberForm.submit(); // Submit the form
            }, 500); // Adjust delay if needed
        });
    });
</script>


<!-- Update Artist 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><b>Update Lyric Writer</b></h3>
                {{!-- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> --}}
            </div>
            <form id="updateMemberForm" action="" method="post" enctype="multipart/form-data">
                {{!-- <div class="modal-body">
                    <label for="role">Select Role</label>
                    <select class="form-control" name="role">
                        <option value="music director">Music Director</option>
                        <option value="singer">Singer</option>
                        <option value="lyric writer">Lyric Writer</option>
                    </select>
                </div> --}}
                <div class="modal-body">
                    <label for="name">Name</label>
                    <input type="text" class="form-control" name="name" minlength="3" maxlength="30" required>
                </div>
                <div class="modal-body">
                    <label for="picture">New Picture (optional)</label>
                    <input type="file" id="updateMemberPicture" class="modal-file" accept=".jpg, .jpeg, .png"
                        name="picture">
                    <p style="color: #CBA255; margin-top: 5px;">Recommended dimensions must be 100 * 100 pixels.</p>
                </div>
                <div class="modal-body">
                    <label for="currentPicture">Current Picture</label><br>
                    <img src="" id="currentPicture" height="60px" alt="Current Picture" style="margin-bottom: 10px;">
                </div>
                {{!-- <div class="modal-body">
                    <label>Preference</label>
                    <div class="form-check form-switch">
                        <label class="switch">
                            <input type="checkbox" name="recommendation">
                            <span class="slider round"></span>
                        </label>
                    </div>
                </div> --}}
                <div class="modal-footer">
                    <button type="submit" class="btn btn-success"
                        style="background-color: #121212; color: #CBA255;">Update Lyric Writer</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete 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" id="deleteModalLabel" style="color: black; font-weight: 480;">Are you sure you
                    want to delete this Lyric writer?</h4>
            </div>
            <form id="deleteMemberForm" action="" method="get">
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"
                        style="background-color:  rgb(255, 25, 25); color: white">No</button>
                    <button type="submit" class="btn btn-danger"
                        style="background-color: #121212; color: #CBA255;">Yes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        const addModal = document.getElementById('addModal');
        const addMemberForm = document.getElementById('addMemberForm');
        const addMemberPicture = document.getElementById('addMemberPicture');

        // Reset the form and clear the file input preview
        addModal.addEventListener('hidden.bs.modal', () => {
            addMemberForm.reset(); // Reset all fields
            if (addMemberPicture) {
                addMemberPicture.value = ''; // Clear the file input
            }
        });
    });
</script>


<script>
    $(document).ready(function () {
        if (!$.fn.DataTable.isDataTable('#example2')) {
            $('#example2').addClass('table table-bordered table-striped').DataTable({
                "paging": true,
            });
        }
    });
</script>

<script>
    document.getElementById("toggleStatus").addEventListener("change", function () {
        const toggleLabel = document.getElementById("toggleLabel");
        toggleLabel.textContent = this.checked ? "Active" : "Inactive";
    });
</script>

<script>
    const updateModal = document.getElementById('updateModal');
    updateModal.addEventListener('show.bs.modal', function (event) {
        const button = event.relatedTarget; // Button that triggered the modal
        const id = button.getAttribute('data-id');
        const name = button.getAttribute('data-name');
        const picture = button.getAttribute('data-picture');
        const recommendation = button.getAttribute('data-recommendation'); // Get recommendation data

        const form = updateModal.querySelector('form');
        form.action = `/admin/updatewriters/${id}`; // Update the action URL with the artist ID

        form.querySelector('input[name="name"]').value = name; // Set artist name
        form.querySelector('img#currentPicture').src = '/' + picture;

        // Set the recommendation toggle button state
        const recommendationCheckbox = form.querySelector('input[name="recommendation"]');
        recommendationCheckbox.checked = (recommendation === 'on'); // Check if recommendation is 'on'
    });



    // Delete Modal Form Script
    const deleteModal = document.getElementById('deleteModal');
    deleteModal.addEventListener('show.bs.modal', function (event) {
        const button = event.relatedTarget;
        const id = button.getAttribute('data-id');
        const form = deleteModal.querySelector('form');
        form.action = `/admin/deletewriters/${id}`; // Update the action URL with the artist ID
    });
</script>

<script>
    let draggedRow = null;

    function drag(event) {
        draggedRow = event.target; // Store the row being dragged
    }

    function allowDrop(event) {
        event.preventDefault(); // Prevent default to allow drop
    }

    function drop(event) {
        event.preventDefault(); // Prevent default behavior
        const targetRow = event.target.closest('tr'); // Get the closest row to the drop target

        if (targetRow && draggedRow !== targetRow) {
            const tableBody = document.getElementById('tableBody');

            // Insert dragged row before or after the target row based on where it's dropped
            if (event.offsetY < targetRow.offsetHeight / 2) {
                tableBody.insertBefore(draggedRow, targetRow); // Insert before
            } else {
                tableBody.insertBefore(draggedRow, targetRow.nextSibling); // Insert after
            }

            // After dropping, save the new order
            saveOrder();
        }
    }

    async function saveOrder() {
        const tableBody = document.getElementById('tableBody');
        const rows = tableBody.querySelectorAll('tr');
        const dragOrder = [];

        rows.forEach((row, index) => {
            const singerId = row.getAttribute('data-id'); // Assuming you have data-id attribute for each row
            dragOrder.push({ id: singerId, rank: index + 1 }); // Save the new rank (index + 1)
        });

        try {
            const response = await fetch('/admin/dragoption2', { // Adjust the URL to match your API endpoint
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(dragOrder),
            });

            if (!response.ok) {
                throw new Error('Network response was not ok');
            }

            const result = await response.json();
            console.log(result.message); // Log success message

            // Refresh the page after successful save
            window.location.reload();
        } catch (error) {
            console.error('Error saving order:', error);
        }
    }

    // Attach event listeners to each row in the table body
    const rows = document.querySelectorAll('#tableBody tr');
    rows.forEach(row => {
        row.addEventListener('dragstart', drag);
        row.addEventListener('dragover', allowDrop);
        row.addEventListener('drop', drop);
        row.setAttribute('draggable', 'true'); // Ensure the rows can be dragged
    });


</script>
{{>adminFooter}}