@extends('layouts.dashboard')

@section('title', 'Gigs')

@section('content')
<div class="bg-white shadow-md rounded-lg p-4 mb-4 flex justify-between items-center">

    <div class="flex items-center space-x-2">

        <label for="entriesPerPage" class="text-sm font-medium text-gray-700">Show</label>

        <select id="entriesPerPage" class="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring focus:border-blue-500 text-sm">

            <option value="10" selected>10</option>

            <option value="25">25</option>

            <option value="50">50</option>

            <option value="100">100</option>

        </select>

        <span class="text-sm font-medium text-gray-700">entries</span>
</div>
        <input type="text" id="searchInput" placeholder="Search..." 
        class="border border-gray-300 rounded-lg px-4 py-2 w-64 focus:ring focus:border-blue-500 shadow-sm">
</div>
    <div class="bg-white shadow rounded-lg p-6">
        <div class="flex justify-between mb-4">
            <h2 class="text-xl font-bold">Gigs</h2>
            <button onclick="openModal()" class="bg-blue-500 text-white px-4 py-2 rounded">Add Gig</button>
        </div>

        @if ($errors->any())
            <div class="bg-red-500 text-white p-4 mb-4 rounded">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <div id="successModal" class="fixed inset-0 bg-gray-900 bg-opacity-50 hidden flex items-center justify-center">
            <div class="bg-white p-6 rounded-lg w-96 text-center">
                <h2 class="text-lg font-bold text-green-600">Success!</h2>
                <p id="successMessage" class="mt-2"></p>
                <button onclick="closeSuccessModal()" class="mt-4 px-4 py-2 bg-blue-500 text-white rounded">OK</button>
            </div>
        </div>

        <table class="w-full border-collapse border border-gray-200">
            <thead>
                <tr class="bg-gray-100">
                    <th class="border px-4 py-2">S/N</th>
                    <th class="border px-4 py-2">Website</th>
                    <th class="border px-4 py-2">Price</th>
                    <th class="border px-4 py-2">Gig Link</th>
                    <th class="border px-4 py-2">Gig On</th>
                    <th class="border px-4 py-2">Created By</th>
                    <th class="border px-4 py-2">Actions</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($gigs as $gig)
                    <tr id="gig-{{ $gig->id }}">
                        <td class="border px-4 py-2">{{ $loop->iteration }}</td>
                        <td class="border px-4 py-2">{{ $gig->website }}</td>
                        <td class="border px-4 py-2">{{ $gig->price }}</td>
                        <td class="border px-4 py-2"><a href="{{ $gig->gig_link }}" target="_blank" class="text-blue-500 underline">{{ $gig->gig_link }}</a></td>
                        <td class="border px-4 py-2">{{ $gig->gig_on }}</td>
                        <td class="border px-4 py-2">By: {{ $gig->creator?->name ?? 'N/A' }}<br>At: {{ $gig->created_at }}</td>
                        <td class="border px-4 py-2">
                            <button onclick="editGig({{ $gig->id }})" class="bg-yellow-500 text-white px-3 py-1 rounded">Edit</button>
                            <button onclick="deleteGig({{ $gig->id }})" class="bg-red-500 text-white px-3 py-1 rounded">Delete</button>
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>

        <div class="mt-4">
            {{ $gigs->links() }}
        </div>
    </div>

    <div id="gigModal" class="fixed inset-0 bg-gray-900 bg-opacity-50 hidden flex items-center justify-center">
        <div class="bg-white p-6 rounded-lg w-11/12 md:w-1/3 max-h-[80vh] overflow-y-auto relative">
            <button onclick="closeModal()" class="absolute top-3 right-3 text-xl text-gray-500 hover:text-black">&times;</button>
            <h2 class="text-xl font-bold mb-4" id="modalTitle">Add Gig</h2>
            <form id="gigForm">
                @csrf
                <input type="hidden" id="gigId">
                
                <div>
                    <label for="website" class="block text-sm font-medium text-gray-700">Website</label>
                    <input type="text" id="website" name="website" class="w-full px-3 py-2 border rounded">
                </div>
                
                <div class="mt-3">
                    <label for="price" class="block text-sm font-medium text-gray-700">Price</label>
                    <input type="number" id="price" name="price" class="w-full px-3 py-2 border rounded">
                </div>
                
                <div class="mt-3">
                    <label for="gig_link" class="block text-sm font-medium text-gray-700">Gig Link</label>
                    <input type="url" id="gig_link" name="gig_link" class="w-full px-3 py-2 border rounded">
                </div>
                
                <div class="mt-3">
                    <label for="gig_on" class="block text-sm font-medium text-gray-700">Gig On</label>
                    <select id="gig_on" name="gig_on" class="w-full px-3 py-2 border rounded">
                        <option value="Fiverr">Fiverr</option>
                        <option value="PPH">PPH</option>
                        <option value="Upwork">Upwork</option>
                        <option value="Other">Other</option>
                    </select>
                </div>

                <div class="flex justify-end space-x-2 mt-4">
                    <button type="button" onclick="closeModal()" class="px-4 py-2 bg-gray-500 text-white rounded">Cancel</button>
                    <button type="submit" class="px-4 py-2 bg-blue-500 text-white rounded">Save</button>
                </div>
            </form>
        </div>
    </div>
@endsection
@section('scripts')
<script>
    function openModal() {
        document.getElementById("gigModal").classList.remove("hidden");
        document.getElementById("modalTitle").innerText = "Add Gig";
        document.getElementById("gigId").value = "";
        document.getElementById("website").value = "";
        document.getElementById("price").value = "";
        document.getElementById("gig_link").value = "";
        document.getElementById("gig_on").value = "";
    }

    function closeModal() {
        let modal = document.getElementById("gigModal");
        modal.classList.add("hidden");
        modal.classList.remove("flex");
    }

    document.addEventListener("DOMContentLoaded", function () {
        document.getElementById("gigForm").addEventListener("submit", function (e) {
            e.preventDefault();

            let gigId = document.getElementById("gigId").value;
            let formData = new FormData(this);

            let url = gigId ? `/gigs/${gigId}` : "/gigs";
            let method = gigId ? "POST" : "POST";

            if (gigId) {
                formData.append("_method", "PUT");
            }

            fetch(url, {
                method: method,
                body: formData,
                headers: {
                    "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute("content"),
                },
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    closeModal(); // Close the form modal
                    showSuccessModal(data.message); // Show success message
                }
            })
            .catch(error => console.error("Error:", error));
        });
    });

    // Function to show success modal
    function showSuccessModal(message) {
        document.getElementById("successMessage").innerText = message;
        document.getElementById("successModal").classList.remove("hidden");
    }

    // Function to close success modal
    function closeSuccessModal() {
        document.getElementById("successModal").classList.add("hidden");
        location.reload(); // Refresh the page to update the listing
    }

    function editGig(id) {
    fetch(`/gigs/${id}/edit`, {
        method: "GET",
        headers: {
            "X-Requested-With": "XMLHttpRequest",
            "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute("content"),
        }
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById("gigId").value = data.id;
        document.getElementById("website").value = data.website;
        document.getElementById("price").value = data.price || "";
        document.getElementById("gig_link").value = data.gig_link || "";
        document.getElementById("gig_on").value = data.gig_on || "";

        document.getElementById("modalTitle").innerText = "Edit Gig";

        let modal = document.getElementById("gigModal");
        modal.classList.remove("hidden");
        modal.classList.add("flex"); // Ensure it displays properly
    })
    .catch(error => console.error("Error fetching gig:", error));
}

    function deleteGig(id) {
        if (!confirm("Are you sure you want to delete this gig?")) {
            return;
        }

        fetch(`/gigs/${id}`, {
            method: "DELETE",
            headers: {
                "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute("content"),
                "X-Requested-With": "XMLHttpRequest",
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById(`gig-${id}`).remove(); // Remove row from table
                showSuccessModal(data.message); // Show success message
            } else {
                alert("Error: Could not delete gig.");
            }
        })
        .catch(error => console.error("Error:", error));
    }
    document.addEventListener("DOMContentLoaded", function () {
    let searchInput = document.getElementById("searchInput");
    let entriesSelect = document.getElementById("entriesPerPage");
    let table = document.querySelector("table tbody");
    let rows = table.getElementsByTagName("tr");

    // Function to filter table rows based on search input
    function filterTable() {
        let searchText = searchInput.value.toLowerCase();

        Array.from(rows).forEach(row => {
            let textContent = row.innerText.toLowerCase();
            row.style.display = textContent.includes(searchText) ? "" : "none";
        });
    }

    // Function to control entries per page
    function updateEntriesPerPage() {
        let numEntries = parseInt(entriesSelect.value);
        let totalRows = rows.length;

        // Show only selected number of rows
        Array.from(rows).forEach((row, index) => {
            row.style.display = index < numEntries ? "" : "none";
        });
    }

    // Event listeners
    searchInput.addEventListener("keyup", filterTable);
    entriesSelect.addEventListener("change", updateEntriesPerPage);

    // Initialize the table with the default entries per page
    updateEntriesPerPage();
});
</script>
@endsection
