@extends('layouts.app')

@section('title', 'All Barcode List')

<style>
    .barcode-sheet {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 22px;
        overflow: hidden;
    }

    .barcode-sheet-head {
        padding: 20px 22px;
        background: linear-gradient(135deg, #f8fbff 0%, #eef5ff 100%);
        border-bottom: 1px solid #e5e7eb;
    }

    .barcode-sheet-title {
        font-size: 1.3rem;
        font-weight: 700;
        color: #111827;
        margin: 0;
    }

    .barcode-sheet-subtitle {
        color: #6b7280;
        font-size: 0.95rem;
        margin-top: 4px;
    }

    .barcode-sheet-badge {
        display: inline-block;
        padding: 8px 14px;
        border-radius: 999px;
        background: #dbeafe;
        color: #1d4ed8;
        font-weight: 700;
        font-size: 0.85rem;
    }

    .barcode-sheet-body {
        padding: 20px 22px;
    }

    .barcode-sheet-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 18px;
    }

    .barcode-card {
        border: 1px solid #eceff3;
        border-radius: 18px;
        background: #fff;
        overflow: hidden;
    }

    .barcode-card-head {
        padding: 12px 16px;
        background: #f9fafb;
        border-bottom: 1px solid #eceff3;
        font-weight: 700;
        color: #1f2937;
    }

    .barcode-card-body {
        padding: 14px 16px;
    }

    .barcode-row {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        gap: 16px;
        padding: 10px 0;
        border-bottom: 1px dashed #e5e7eb;
    }

    .barcode-row:last-child {
        border-bottom: 0;
    }

    .barcode-row-key {
        min-width: 42%;
        color: #6b7280;
        font-weight: 600;
        font-size: 0.9rem;
    }

    .barcode-row-value {
        text-align: right;
        color: #111827;
        font-weight: 600;
        word-break: break-word;
    }

    .barcode-note {
        border: 1px solid #eceff3;
        border-radius: 18px;
        background: #f8fafc;
        padding: 16px;
        color: #1f2937;
        line-height: 1.65;
    }

    .barcode-measure-strip {
        display: grid;
        grid-template-columns: repeat(5, minmax(0, 1fr));
        gap: 12px;
    }

    .barcode-measure-box {
        border: 1px solid #eceff3;
        border-radius: 16px;
        background: #f8fafc;
        padding: 14px 12px;
        text-align: center;
    }

    .barcode-measure-label {
        font-size: 0.76rem;
        color: #6b7280;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.03em;
        margin-bottom: 6px;
    }

    .barcode-measure-value {
        font-size: 0.98rem;
        color: #111827;
        font-weight: 700;
    }

    .barcode-gallery {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 16px;
    }

    .barcode-gallery-card {
        border: 1px solid #eceff3;
        border-radius: 18px;
        background: #f8fafc;
        padding: 14px;
        text-align: center;
    }

    .barcode-gallery-title {
        font-weight: 700;
        color: #374151;
        margin-bottom: 10px;
    }

    .barcode-gallery-card img {
        max-height: 220px;
        width: auto;
        border-radius: 12px;
        border: 1px solid #dbe2ea;
        background: #fff;
    }

    @media (max-width: 991px) {
        .barcode-sheet-grid {
            grid-template-columns: 1fr;
        }

        .barcode-measure-strip {
            grid-template-columns: repeat(2, minmax(0, 1fr));
        }
    }

    @media (max-width: 767px) {

        .barcode-gallery,
        .barcode-measure-strip {
            grid-template-columns: 1fr;
        }
    }
</style>

@php
    $auth_role = auth()->user()->role;
    $auth_role_name = $auth_role?->name;
    $auth_level = auth()->user()->level;
    $auth_level_code = $auth_level?->code;
    $auth_level_name = $auth_level?->name;
@endphp

@section('content')
    <div class="card content-card">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center">
                <h5 class="fw-bold">Barcode Creation List</h5>
                @if ($auth_level_code == 'Level I')
                    <a href="{{ route('barcode_create') }}"
                        class="badge rounded-pill bg-primary px-3 py-2 text-decoration-none" style="cursor:pointer;">
                        Add Barcode Creation Form
                    </a>
                @endif
            </div>

            <div class="line"> </div>

            {{-- @if ($errors->any())
                <div style="color:red">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif --}}
            {{-- <p>{{ $check }}</p> --}}

            <div class="table-responsive">
                <table id="dataTable" class="table table-hover align-middle">
                    <thead class="table-secondary">
                        <tr>
                            <th>#</th>
                            <th>Code</th>
                            <th>Brand Name</th>
                            <th>Product Name</th>
                            <th>GST</th>
                            <th>FSSAI Number</th>
                            <th>Level</th>
                            <th>Level User</th>
                            <th>Level Role</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php $sno = 1; @endphp
                        @foreach ($records as $row)
                            <tr id="row-{{ $row->id }}">
                                <td>{{ $sno }}</td>
                                <td>{{ $row->code }}</td>
                                <td>{{ $row->brand_name }}</td>
                                <td>{{ $row->product_name }}</td>
                                <td>{{ $row->gst }}</td>
                                <td>{{ $row->fssai_no }}</td>
                                <td>{{ $row->created_user?->level?->name ?? '' }}</td>
                                <td>{{ $row->created_user?->full_name ?? '' }}</td>
                                <td>{{ $row->created_user?->role?->name ?? '' }}</td>
                                <td>
                                    <span
                                        class="badge rounded-pill {{ $row->status == 'Drafted' ? 'bg-warning' : ($row->status == 'Applied' ? 'bg-primary' : ($row->status == 'Applied' ? 'bg-success' : 'bg-danger')) }} px-3 py-2 mt-2">
                                        {{ $row->status }}
                                    </span>
                                </td>
                                <td>
                                    <button type="button"
                                        class="badge rounded-pill bg-secondary px-3 py-2 mt-2 border-0 view-barcode"
                                        data-id="{{ $row->id }}" data-url="{{ route('barcode_show', $row->id) }}"
                                        style="cursor:pointer;">
                                        View
                                    </button>
                                    @if ($auth_level_name == 'Level I' && $row->status == 'Drafted')
                                        <a href="{{ route('barcode_edit', $row->id) }}"
                                            class="badge rounded-pill bg-info px-3 py-2 mt-2 text-decoration-none"
                                            style="cursor:pointer;">
                                            Edit
                                        </a>
                                        <button type="button"
                                            class="badge rounded-pill bg-danger px-3 py-2 mt-2 border-0 delete-barcode-creation"
                                            data-url="{{ route('barcode_delete', $row->id) }}"
                                            data-id="{{ $row->id }}" style="cursor:pointer;">
                                            Delete
                                        </button>
                                    @endif
                                </td>
                            </tr>
                            @php $sno++; @endphp
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
@endsection

<div class="modal fade" id="barcodeViewModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-light">
                <h5 class="modal-title fw-bold">Barcode Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="barcodeViewModalBody">
                <div class="text-center py-4">Loading...</div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
    <script>
        document.addEventListener('click', async function(e) {
            const deleteButton = e.target.closest('.delete-barcode-creation');
            if (!deleteButton) return;

            const loader = document.getElementById('page-loader');
            const url = deleteButton.dataset.url;
            const id = deleteButton.dataset.id;

            const result = await Swal.fire({
                title: '<i class="bi bi-exclamation-circle text-warning fs-1"></i>',
                text: 'Delete this Barcode Creation Form?',
                width: 330,
                showCancelButton: true,
                confirmButtonText: 'Yes',
                cancelButtonText: 'No',
                customClass: {
                    confirmButton: 'px-2 py-1',
                    cancelButton: 'px-2 py-1'
                }
            });

            if (!result.isConfirmed) {
                return;
            }

            if (loader) {
                loader.classList.remove('hidden');
            }

            try {
                const response = await fetch(`${url}?id=${encodeURIComponent(id)}`, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });

                const data = await response.json();

                if (loader) {
                    loader.classList.add('hidden');
                }

                if (response.ok && data.flag) {
                    window.location.reload();

                    Swal.fire({
                        title: '<i class="bi bi-check2-circle text-success fs-1"></i>',
                        text: data.message,
                        width: 330,
                        timer: 1500,
                        showConfirmButton: false
                    });
                } else {
                    Swal.fire({
                        title: '<i class="bi bi-x-circle text-danger fs-1"></i>',
                        text: data.message || 'Delete failed.',
                        width: 330,
                        customClass: {
                            confirmButton: 'px-2 py-1'
                        }
                    });
                }
            } catch (error) {
                if (loader) {
                    loader.classList.add('hidden');
                }

                Swal.fire({
                    title: '<i class="bi bi-x-circle text-danger fs-1"></i>',
                    text: 'Something went wrong.',
                    width: 330,
                    customClass: {
                        confirmButton: 'px-2 py-1'
                    }
                });
            }
        });


        $(document).on('click', '.view-barcode', function() {
            const url = $(this).data('url');
            const loader = $('#page-loader');
            const modalBody = $('#barcodeViewModalBody');
            const modal = new bootstrap.Modal(document.getElementById('barcodeViewModal'));

            function val(v) {
                return v !== null && v !== undefined && v !== '' ? v : '-';
            }

            function statusBadge(status) {
                const cls = status === 'Applied' ? 'success' : 'primary';
                return `<span class="badge rounded-pill bg-${cls} px-3 py-2">${val(status)}</span>`;
            }

            function field(label, value) {
                return `
                    <div class="col-md-6 col-lg-4">
                        <div class="view-field-card h-100">
                            <div class="view-field-label">${label}</div>
                            <div class="view-field-value">${val(value)}</div>
                        </div>
                    </div>
                `;
            }

            function imageCard(label, url) {
                return `
                    <div class="col-md-6">
                        <div class="view-image-card h-100">
                            <div class="view-section-mini">${label}</div>
                            ${
                                url
                                    ? `<img src="${url}" alt="${label}" class="img-fluid rounded-3 border" style="max-height:220px;">`
                                    : `<div class="text-muted text-center py-5 border rounded-3 bg-light">Image not available</div>`
                            }
                        </div>
                    </div>
                `;
            }

            modalBody.html(`
                <div class="text-center py-5">
                    <div class="spinner-border text-primary"></div>
                    <div class="mt-2">Loading details...</div>
                </div>
            `);

            modal.show();
            loader.removeClass('hidden');

            $.ajax({
                url: url,
                type: 'GET',
                dataType: 'json',
                success: function(res) {
                    if (!res.flag || !res.records) {
                        modalBody.html(
                            '<div class="text-danger text-center py-4">Record not found.</div>');
                        return;
                    }

                    const r = res.records;
                    const productImageUrl = r.product_image ? `/${r.product_image}` : '';
                    const artWorkImageUrl = r.art_work_image ? `/${r.art_work_image}` : '';

                    function val(v) {
                        return v !== null && v !== undefined && v !== '' ? v : '-';
                    }

                    function row(label, value) {
                        return `
            <div class="barcode-row">
                <div class="barcode-row-key">${label}</div>
                <div class="barcode-row-value">${val(value)}</div>
            </div>
        `;
                    }

                    function measure(label, value) {
                        return `
            <div class="barcode-measure-box">
                <div class="barcode-measure-label">${label}</div>
                <div class="barcode-measure-value">${val(value)}</div>
            </div>
        `;
                    }

                    function imageCard(label, url) {
                        return `
            <div class="barcode-gallery-card">
                <div class="barcode-gallery-title">${label}</div>
                ${
                    url
                        ? `<img src="${url}" alt="${label}" class="img-fluid">`
                        : `<div class="text-muted py-5">Image not available</div>`
                }
            </div>
        `;
                    }

                    modalBody.html(`
        <div class="barcode-sheet">
            <div class="barcode-sheet-head">
                <div class="d-flex justify-content-between align-items-start gap-3 flex-wrap">
                    <div>
                        <h4 class="barcode-sheet-title mb-0">${val(r.product_name)}</h4>
                        <div class="barcode-sheet-subtitle">${val(r.brand_name)}</div>
                    </div>
                    <div class="barcode-sheet-badge">${val(r.status)}</div>
                </div>
            </div>

            <div class="barcode-sheet-body">
                <div class="barcode-sheet-grid mb-4">
                    <div class="barcode-card">
                        <div class="barcode-card-head">Core Attributes</div>
                        <div class="barcode-card-body">
                            ${row('Brand Name', r.brand_name)}
                            ${row('Product Name', r.product_name)}
                            ${row('Category', r.category?.name)}
                            ${row('Subcategory', r.subcategory?.name)}
                            ${row('Marketing Information', r.marketing_information)}
                            ${row('Food Type', r.food_type)}
                            ${row('Location', r.location)}
                        </div>
                    </div>

                    <div class="barcode-card">
                        <div class="barcode-card-head">Pricing & Compliance</div>
                        <div class="barcode-card-body">
                            ${row('MRP Activation Date', r.mrp_activation_date)}
                            ${row('MRP', r.mrp)}
                            ${row('HSN', r.hsn)}
                            ${row('GST', r.gst)}
                            ${row('FSSAI No', r.fssai_no)}
                            ${row('Shelf Life Value', r.shelf_life_value)}
                            ${row('Shelf Life Unit', r.shelf_life_unit)}
                            ${row('Shelf Life Based On', r.shelf_life_based_on)}
                        </div>
                    </div>
                </div>

                <div class="barcode-card mb-4">
                    <div class="barcode-card-head">Product Description</div>
                    <div class="barcode-card-body">
                        <div class="barcode-note">${val(r.product_description)}</div>
                    </div>
                </div>

                <div class="barcode-card mb-4">
                    <div class="barcode-card-head">Weights & Measures</div>
                    <div class="barcode-card-body">
                        <div class="barcode-measure-strip">
                            ${measure('Net Content Unit', r.net_content_unit)}
                            ${measure('Mass Unit', r.mass_unit)}
                            ${measure('Net Weight', r.net_weight)}
                            ${measure('Net Content', r.net_content)}
                            ${measure('Cross Weight', r.cross_weight)}
                        </div>
                    </div>
                </div>

                <div class="barcode-card">
                    <div class="barcode-card-head">Images</div>
                    <div class="barcode-card-body">
                        <div class="barcode-gallery">
                            ${imageCard('Product Image', productImageUrl)}
                            ${imageCard('Art Work Image', artWorkImageUrl)}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `);
                },
                error: function() {
                    modalBody.html(
                        '<div class="text-danger text-center py-4">Failed to load details.</div>');
                },
                complete: function() {
                    loader.addClass('hidden');
                }
            });
        });
    </script>
@endpush
