<!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>Brand</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">Brand</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 Brand</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="#tambahBrand">
                                    + Tambah Brand
                                </button>
                            </div>
                            <table class="table table-striped table-bordered" id="brandTable">
                                <thead>
                                    <tr>
                                        <th>No</th>
                                        <th>Nama Brand</th>
                                        <th>Jumlah Produk</th>
                                        <th>Tanggal Dibuat</th>
                                        <th>Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($brand as $b)
                                        <tr>
                                            <td>{{ $loop->iteration }}</td>
                                            <td>{{ $b->nama_brand }}</td>
                                            <td>{{ $b->jumlah_produk }}</td>
                                            <td>{{ $b->createdAt }}</td>
                                            <td>
                                                <button type="button" class="btn btn-primary btn-sm"
                                                    data-bs-toggle="modal"
                                                    data-bs-target="#editBrand{{ $b->id }}">
                                                    Edit
                                                </button>
                                                <!-- Tombol Hapus -->
                                                <button type="button" class="btn btn-danger btn-sm"
                                                    onclick="confirmDelete({{ $b->id }})">Hapus</button>

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

    <!-- Modal Tambah-->
    <div class="modal fade" id="tambahBrand" tabindex="-1" aria-labelledby="modaltambahbrandLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTambahBrandLabel">Tambah Data Brand</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form action="{{ route('brand.store') }}" method="POST" enctype="multipart/form-data">
                        @csrf
                        <div class="mb-3">
                            <label for="nama_brand" class="form-label">Nama Brand</label>
                            <input type="text" class="form-control" id="nama_brand" name="nama_brand" required>
                        </div>
                        {{-- <div class="mb-3">
                            <label for="email" class="form-label">Email</label>
                            <input type="text" class="form-control" id="email" name="email"
                                accept="image/*" required>
                        </div>
                        <div class="mb-3">
                            <label for="password" class="form-label">Password</label>
                            <input type="text" class="form-control" id="password" name="password" required>
                        </div>
                        <div class="mb-3">
                            <label for="role" class="form-label">Role</label>
                            <select class="form-select" id="role" name="role" required>
                                <option value="Admin">Admin</option>
                                <option value="Kasir">Kasir</option>
                            </select>
                        </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>
                        <input type="hidden" name="status" value="Aktif"> --}}
                </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 ($brand as $b)
        <div class="modal fade" id="editBrand{{ $b->id }}" tabindex="-1"
            aria-labelledby="modalEditBrandLabel{{ $b->id }}" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalEditBrandLabel{{ $b->id }}">Edit Data Brand</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"
                            aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form action="{{ route('brand.update', $b->id) }}" method="POST"
                            enctype="multipart/form-data">
                            @csrf
                            @method('PUT')
                            <div class="mb-3">
                                <label for="nama_brand" class="form-label">Nama Brand</label>
                                <input type="text" class="form-control" id="nama_brand" name="nama_brand"
                                    value="{{ $b->nama_brand }}" required>
                            </div>
                            {{-- <div class="mb-3">
                                <label for="email" class="form-label">Email</label>
                                <input type="email" class="form-control" id="email" name="email"
                                    value="{{ $b->email }}" required>
                            </div>
                            <div class="mb-3">
                                <label for="role" class="form-label">Role</label>
                                <select class="form-select" id="role" name="role" required>
                                    <option value="Admin" {{ $b->role == 'Admin' ? 'selected' : '' }}>Admin</option>
                                    <option value="Kasir" {{ $b->role == 'Kasir' ? 'selected' : '' }}>Kasir</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="image" class="form-label">Foto Produk (Opsional)</label>
                                <input type="file" class="form-control" id="image" name="image"
                                    accept="image/*">
                            </div>
                            <input type="hidden" name="status" value="Aktif"> --}}
                    </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(brandId) {
            Swal.fire({
                title: 'Apakah Anda Yakin?',
                text: "Brand 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(`/brand/delete/${brandId}`, {
                            method: 'DELETE',
                            headers: {
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            }
                        }).then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                Swal.fire(
                                    'Dihapus!',
                                    'Brand berhasil dihapus.',
                                    'success'
                                ).then(() => {
                                    location.reload(); // Reload halaman setelah konfirmasi berhasil
                                });
                            } else {
                                Swal.fire(
                                    'Gagal!',
                                    'Brand 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("brandTable");
            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>
