<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">

    <title>Ellia Cellular</title>
    <meta content="" name="description">
    <meta content="" name="keywords">

    <!-- Favicons -->
    <link href="{{ asset('assets/img/favicon.png') }}" rel="icon">
    <link href="{{ asset('assets/img/apple-touch-icon.png') }}" rel="apple-touch-icon">

    <!-- Google Fonts -->
    <link href="https://fonts.gstatic.com" rel="preconnect">
    <link
        href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i"
        rel="stylesheet">

    <!-- Tambahkan ini di bagian <head> atau sebelum penutup </body> -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>


    <!-- Vendor CSS Files -->
    <link href="{{ asset('assets/vendor/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
    <link href="{{ asset('assets/vendor/bootstrap-icons/bootstrap-icons.css') }}" rel="stylesheet">
    <link href="{{ asset('assets/vendor/boxicons/css/boxicons.min.css') }}" rel="stylesheet">
    <link href="{{ asset('assets/vendor/quill/quill.snow.css') }}" rel="stylesheet">
    <link href="{{ asset('assets/vendor/quill/quill.bubble.css') }}" rel="stylesheet">
    <link href="{{ asset('assets/vendor/remixicon/remixicon.css') }}" rel="stylesheet">
    <link href="{{ asset('assets/vendor/simple-datatables/style.css') }}" rel="stylesheet">

    <!-- Template Main CSS File -->
    <link href="{{ asset('assets/css/style.css') }}" rel="stylesheet">
</head>

<body>

    <!-- ======= Header ======= -->
    @include('header')
    <!-- ======= Sidebar ======= -->
    @include('sidebar')

    <main id="main" class="main">
        <div class="pagetitle">
            <h1>List Produk</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.html">Home</a></li>
                    <li class="breadcrumb-item">Manajemen Barang</li>
                    <li class="breadcrumb-item">Produk</li>
                </ol>
            </nav>
        </div><!-- End Page Title -->

        <section class="section">
            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Data Produk</h5>
                            <div class="mb-2">
                                <input type="text" class="form-control" id="searchInput" placeholder="Cari..."
                                    style="width: 200px;">
                            </div>
                            <div class="mb-1 d-flex align-items-center">
                                <label class="me-2">Tampilkan:</label>
                                <select id="entriesPerPage" class="form-select w-auto">
                                    <option value="5">5</option>
                                    <option value="10">10</option>
                                    <option value="all">Semua</option>
                                </select>
                            </div>
                            <div class="d-flex justify-content-end align-items-center mb-3">
                                <button type="button" class="btn btn-success" data-bs-toggle="modal"
                                    data-bs-target="#tambahProduct">
                                    + Tambah Produk
                                </button>
                            </div>
                            <table class="table table-striped table-bordered" id="productTable">
                                <thead>
                                    <tr>
                                        <th>No</th>
                                        <th>Nama Produk</th>
                                        <th>Brand</th>
                                        <th>Kategori</th>
                                        <th>Harga</th>
                                        <th>Stok</th>
                                        <th>Tanggal Dibuat</th>
                                        <th>Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($product as $p)
                                        <tr>
                                            <td>{{ $loop->iteration }}</td>
                                            <td>{{ $p->nama_produk }}</td>
                                            <td>{{ $p->brand }}</td>
                                            <td>{{ $p->kategori }}</td>
                                            <td>Rp {{ number_format($p->harga, 0, ',', '.') }}</td>
                                            <td>{{ $p->stok }}</td>
                                            <td>{{ $p->createdAt }}</td>
                                            <td>
                                                <button type="button" class="btn btn-primary btn-sm"
                                                    data-bs-toggle="modal"
                                                    data-bs-target="#editProduct{{ $p->id }}">
                                                    Edit
                                                </button>
                                                <!-- Tombol Hapus -->
                                                <button type="button" class="btn btn-danger btn-sm"
                                                    onclick="confirmDelete({{ $p->id }})">Hapus</button>

                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </main><!-- End #main -->

    <!-- Modal Tambah-->
    <div class="modal fade" id="tambahProduct" tabindex="-1" aria-labelledby="modaltambahproductLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTambahProductLabel">Tambah Data Produk</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form action="{{ route('product.store') }}" method="POST" enctype="multipart/form-data">
                        @csrf
                        <div class="mb-3">
                            <label for="nama_produk" class="form-label">Nama Produk</label>
                            <input type="text" class="form-control" id="nama_produk" name="nama_produk" required>
                        </div>
                        {{-- <div class="mb-3">
                            <label for="deskripsi" class="form-label">Deskripsi Produk</label>
                            <input type="text" class="form-control" id="deskripsi" name="deskripsi" required>
                        </div> --}}
                        <div class="mb-3">
                            <label for="brand_id" class="form-label">Brand</label>
                            <select class="form-select" id="brand_id" name="brand_id" required>
                                <option value="" disabled selected>Pilih Brand</option>
                                @foreach ($brand as $b)
                                    <option value="{{ $b->id }}">{{ $b->nama_brand }}</option>
                                @endforeach
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="category_id" class="form-label">Kategori</label>
                            <select class="form-select" id="category_id" name="category_id" required>
                                <option value="" disabled selected>Pilih Kategori</option>
                                @foreach ($category as $c)
                                    <option value="{{ $c->id }}">{{ $c->nama_kategori }}</option>
                                @endforeach
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="harga" class="form-label">Harga Produk</label>
                            <input type="text" class="form-control" id="harga" name="harga" required>
                        </div>
                        <div class="mb-3">
                            <label for="stok" class="form-label">Stok Produk</label>
                            <input type="text" class="form-control" id="stok" name="stok" required>
                        </div>
                        <div class="mb-3">
                            <label for="image" class="form-label">Foto Produk</label>
                            <input type="file" class="form-control" id="image" name="image"
                                accept="image/*">
                        </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-primary">Simpan Data</button>
                </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Edit -->
@foreach ($product as $p)
<div class="modal fade" id="editProduct{{ $p->id }}" tabindex="-1"
    aria-labelledby="modalEditProductLabel{{ $p->id }}" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalEditProductLabel{{ $p->id }}">Edit Data Produk</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form action="{{ route('product.update', $p->id) }}" method="POST" enctype="multipart/form-data">
                    @csrf
                    @method('PUT')
                    <div class="mb-3">
                        <label for="nama_produk" class="form-label">Nama Produk</label>
                        <input type="text" class="form-control" id="nama_produk" name="nama_produk" 
                            value="{{ $p->nama_produk }}" required>
                    </div>

                    <div class="mb-3">
                        <label for="brand_id" class="form-label">Brand</label>
                        <select class="form-select" id="brand_id" name="brand_id" required>
                            <option value="" disabled>Pilih Brand</option>
                            @foreach ($brand as $b)
                                <option value="{{ $b->id }}" {{ $p->brand_id == $b->id ? 'selected' : '' }}>
                                    {{ $b->nama_brand }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="category_id" class="form-label">Kategori</label>
                        <select class="form-select" id="category_id" name="category_id" required>
                            <option value="" disabled>Pilih Kategori</option>
                            @foreach ($category as $c)
                                <option value="{{ $c->id }}" {{ $p->category_id == $c->id ? 'selected' : '' }}>
                                    {{ $c->nama_kategori }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="harga" class="form-label">Harga Produk</label>
                        <input type="text" class="form-control" id="harga" name="harga"
                            value="{{ $p->harga }}" required>
                    </div>

                    <div class="mb-3">
                        <label for="image" class="form-label">Foto Produk</label>
                        <input type="file" class="form-control" id="image" name="image" accept="image/*">
                    </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
            </div>
            </form>
        </div>
    </div>
</div>
@endforeach





    <!-- ======= Footer ======= -->
    @include('footer')

    <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i
            class="bi bi-arrow-up-short"></i></a>

    <!-- Vendor JS Files -->
    <script src="{{ asset('assets/vendor/apexcharts/apexcharts.min.js') }}"></script>
    <script src="{{ asset('assets/vendor/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
    <script src="{{ asset('assets/vendor/chart.js/chart.umd.js') }}"></script>
    <script src="{{ asset('assets/vendor/echarts/echarts.min.js') }}"></script>
    <script src="{{ asset('assets/vendor/quill/quill.js') }}"></script>
    <script src="{{ asset('assets/vendor/simple-datatables/simple-datatables.js') }}"></script>
    <script src="{{ asset('assets/vendor/tinymce/tinymce.min.js') }}"></script>
    <script src="{{ asset('assets/vendor/php-email-form/validate.js') }}"></script>

    <!-- Template Main JS File -->
    <script src="{{ asset('assets/js/main.js') }}"></script>

    <script>
        document.getElementById('searchInput').addEventListener('keyup', function() {
            let filter = this.value.toLowerCase();
            let rows = document.querySelectorAll('tbody tr');

            rows.forEach(row => {
                let text = row.innerText.toLowerCase();
                row.style.display = text.includes(filter) ? '' : 'none';
            });
        });
    </script>


    <!-- Ini buat sweet alert Konfirmasi Hapus-->
    <script>
        function confirmDelete(productId) {
            Swal.fire({
                title: 'Apakah Anda Yakin?',
                text: "Produk ini akan dihapus!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Ya, Hapus!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Mengirimkan request delete ke server
                    fetch(`/product/delete/${productId}`, {
                            method: 'DELETE',
                            headers: {
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            }
                        }).then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                Swal.fire(
                                    'Dihapus!',
                                    'Pengguna berhasil dihapus.',
                                    'success'
                                ).then(() => {
                                    location.reload(); // Reload halaman setelah konfirmasi berhasil
                                });
                            } else {
                                Swal.fire(
                                    'Gagal!',
                                    'Pengguna gagal dihapus.',
                                    'error'
                                );
                            }
                        })
                        .catch(error => console.error('Terjadi kesalahan:', error));
                }
            })
        }
    </script>

<!-- Ini buat datatables Custom Rownya dengan Sorting -->
<script>
    document.addEventListener("DOMContentLoaded", function() {
        const table = document.getElementById("productTable");
        const tbody = table.querySelector("tbody");
        const rows = Array.from(tbody.querySelectorAll("tr"));
        const headers = table.querySelectorAll("thead th");
        const paginationContainer = document.createElement("div");
        paginationContainer.className = "pagination-container mt-3 d-flex justify-content-end";

        const searchInput = document.getElementById("searchInput");
        const entriesPerPageSelect = document.getElementById("entriesPerPage");

        let currentPage = 1;
        let rowsPerPage = parseInt(entriesPerPageSelect.value) || 5;
        let currentSortColumn = null;
        let currentSortDirection = "asc"; // Default sorting: ascending

        // Fungsi untuk memfilter baris berdasarkan pencarian
        function filterRows() {
            const filter = searchInput.value.toLowerCase();
            return rows.filter(row => row.innerText.toLowerCase().includes(filter));
        }

        // Fungsi untuk mengurutkan baris
        function sortRows(columnIndex, direction) {
            rows.sort((a, b) => {
                const aText = a.cells[columnIndex].innerText.trim().toLowerCase();
                const bText = b.cells[columnIndex].innerText.trim().toLowerCase();

                if (!isNaN(aText) && !isNaN(bText)) {
                    return direction === "asc" ? aText - bText : bText - aText;
                }

                return direction === "asc" ? aText.localeCompare(bText) : bText.localeCompare(aText);
            });
        }

        // Fungsi untuk menampilkan halaman tabel
        function displayTablePage(page) {
            const filteredRows = filterRows();
            const totalPages = Math.ceil(filteredRows.length / rowsPerPage);

            if (page > totalPages) page = totalPages;
            if (page < 1) page = 1;

            tbody.innerHTML = "";

            if (entriesPerPageSelect.value === "all") {
                filteredRows.forEach(row => tbody.appendChild(row));
            } else {
                const startIndex = (page - 1) * rowsPerPage;
                const endIndex = startIndex + rowsPerPage;

                const rowsToDisplay = filteredRows.slice(startIndex, endIndex);
                rowsToDisplay.forEach(row => tbody.appendChild(row));

                updatePagination(page, totalPages);
            }
        }

        // Fungsi untuk memperbarui pagination
        function updatePagination(currentPage, totalPages) {
            paginationContainer.innerHTML = "";

            if (totalPages <= 1) return;

            // Batasi jumlah nomor halaman yang ditampilkan (maksimal 5)
            const maxPagesToShow = 5;
            let startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2));
            let endPage = Math.min(totalPages, startPage + maxPagesToShow - 1);

            // Jika jumlah halaman yang ditampilkan kurang dari 5, geser startPage
            if (endPage - startPage + 1 < maxPagesToShow) {
                startPage = Math.max(1, endPage - maxPagesToShow + 1);
            }

            // Tampilkan nomor halaman
            for (let i = startPage; i <= endPage; i++) {
                const button = document.createElement("button");
                button.textContent = i;
                button.className = "btn btn-sm btn-outline-primary mx-1";
                if (i === currentPage) button.classList.add("active");

                button.addEventListener("click", () => {
                    displayTablePage(i);
                });

                paginationContainer.appendChild(button);
            }
        }

        // Event listener untuk header kolom (sorting)
        headers.forEach((header, index) => {
            header.addEventListener("click", () => {
                if (currentSortColumn === index) {
                    currentSortDirection = currentSortDirection === "asc" ? "desc" : "asc";
                } else {
                    currentSortColumn = index;
                    currentSortDirection = "asc"; // Default sorting: ascending
                }

                sortRows(index, currentSortDirection);
                displayTablePage(1);
            });
        });

        // Event listener untuk pencarian
        searchInput.addEventListener("keyup", () => displayTablePage(1));

        // Event listener untuk perubahan jumlah entri per halaman
        entriesPerPageSelect.addEventListener("change", function() {
            rowsPerPage = entriesPerPageSelect.value === "all" ? rows.length : parseInt(
                entriesPerPageSelect.value);
            displayTablePage(1);
        });

        // Tampilkan halaman pertama saat pertama kali dimuat
        displayTablePage(1);
        table.parentNode.appendChild(paginationContainer);
    });
</script>


    {{-- <!-- Ini buat datatables Custom Rownya dengan Sorting -->
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const table = document.getElementById("productTable");
            const tbody = table.querySelector("tbody");
            const rows = Array.from(tbody.querySelectorAll("tr"));
            const headers = table.querySelectorAll("thead th");
            const paginationContainer = document.createElement("div");
            paginationContainer.className = "pagination-container mt-3 d-flex justify-content-end";

            const searchInput = document.getElementById("searchInput");
            const entriesPerPageSelect = document.getElementById("entriesPerPage");

            let currentPage = 1;
            let rowsPerPage = parseInt(entriesPerPageSelect.value) || 5;
            let currentSortColumn = null;
            let currentSortDirection = "asc";

            function filterRows() {
                const filter = searchInput.value.toLowerCase();
                return rows.filter(row => row.innerText.toLowerCase().includes(filter));
            }

            function sortRows(columnIndex, direction) {
                rows.sort((a, b) => {
                    const aText = a.cells[columnIndex].innerText.trim().toLowerCase();
                    const bText = b.cells[columnIndex].innerText.trim().toLowerCase();

                    if (!isNaN(aText) && !isNaN(bText)) {
                        return direction === "asc" ? aText - bText : bText - aText;
                    }

                    return direction === "asc" ? aText.localeCompare(bText) : bText.localeCompare(aText);
                });
            }

            function displayTablePage(page) {
                const filteredRows = filterRows();
                const totalPages = Math.ceil(filteredRows.length / rowsPerPage);

                if (page > totalPages) page = totalPages;
                if (page < 1) page = 1;

                tbody.innerHTML = "";

                if (entriesPerPageSelect.value === "all") {
                    filteredRows.forEach(row => tbody.appendChild(row));
                } else {
                    const startIndex = (page - 1) * rowsPerPage;
                    const endIndex = startIndex + rowsPerPage;

                    const rowsToDisplay = filteredRows.slice(startIndex, endIndex);
                    rowsToDisplay.forEach(row => tbody.appendChild(row));

                    updatePagination(page, totalPages);
                }
            }

            function updatePagination(currentPage, totalPages) {
                paginationContainer.innerHTML = "";

                if (totalPages <= 1) return;

                for (let i = 1; i <= totalPages; i++) {
                    const button = document.createElement("button");
                    button.textContent = i;
                    button.className = "btn btn-sm btn-outline-primary mx-1";
                    if (i === currentPage) button.classList.add("active");

                    button.addEventListener("click", () => {
                        displayTablePage(i);
                    });

                    paginationContainer.appendChild(button);
                }
            }

            headers.forEach((header, index) => {
                header.addEventListener("click", () => {
                    if (currentSortColumn === index) {
                        currentSortDirection = currentSortDirection === "asc" ? "desc" : "asc";
                    } else {
                        currentSortColumn = index;
                        currentSortDirection = "asc";
                    }

                    sortRows(index, currentSortDirection);
                    displayTablePage(1);
                });
            });

            searchInput.addEventListener("keyup", () => displayTablePage(1));
            entriesPerPageSelect.addEventListener("change", function() {
                rowsPerPage = entriesPerPageSelect.value === "all" ? rows.length : parseInt(
                    entriesPerPageSelect.value);
                displayTablePage(1);
            });

            displayTablePage(1);
            table.parentNode.appendChild(paginationContainer);
        });
    </script> --}}



</body>

</html>
