@extends('layouts.app')

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

<style>
    #barcodeViewModal .modal-content {
        border: 0;
        border-radius: 22px;
        overflow: hidden;
        box-shadow: 0 18px 44px rgba(15, 23, 42, 0.14);
        background: #f6f9fc;
    }

    #barcodeViewModal .modal-header {
        background: linear-gradient(135deg, #ffffff 0%, #f4f8ff 100%);
        border-bottom: 1px solid #e8eef7;
        padding: 8px 18px;
    }

    #barcodeViewModal .modal-title {
        color: #1e293b;
        letter-spacing: 0.01em;
        font-size: 1rem;
    }

    #barcodeViewModal .modal-body {
        padding: 12px;
        background: radial-gradient(circle at top right, rgba(13, 110, 253, 0.06), transparent 28%), #f6f9fc;
    }

    .barcode-tabs-wrap {
        /* border: 1px solid #e4ebf5; */
        border: 1px solid #e31c8a;
        border-radius: 18px;
        overflow: hidden;
        background: #ffffff;
        box-shadow: 0 8px 20px rgba(15, 23, 42, 0.05);
    }

    .barcode-tabs-head {
        padding: 12px 12px 0;
        background: linear-gradient(180deg, #f8fbff 0%, #ffffff 100%);
        /* border-bottom: 1px solid #e8eef7; */
    }

    .barcode-tabs-title {
        font-size: 1.05rem;
        font-weight: 700;
        color: #172033;
        line-height: 1.2;
    }

    .barcode-tabs-subtitle {
        color: #64748b;
        font-size: 0.86rem;
        margin-top: 4px;
        margin-bottom: 8px;
    }

    .barcode-tabs-head .nav {
        gap: 8px;
        padding-bottom: 10px;
    }

    .barcode-tabs-head .nav-pills .nav-link {
        /* border: 1px solid #dbe5f1; */
        border-radius: 999px;
        /* color: #475569; */
        background: #f0e5e5;
        font-weight: 600;
        font-size: 0.86rem;
        padding: 4px 10px;
        transition: all 0.25s ease;
        /* box-shadow: 0 2px 6px rgba(15, 23, 42, 0.03); */
    }

    .barcode-tabs-head .nav-pills .nav-link:hover {
        color: #0d6efd;
        background: #f8fbff;
    }

    .barcode-tabs-head .nav-pills .nav-link.active {
        background-color: #e31c8a;
        /* border-color: transparent; */
        color: #fff;
    }

    .barcode-tab-pane {
        padding: 12px;
    }

    .barcode-pill-status {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        padding: 6px 10px;
        border-radius: 999px;
        color: #ffffff;
        font-weight: 700;
        font-size: 0.78rem;
        /* border: 1px solid #d7e6ff; */
        /* box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.8); */
    }

    .barcode-info-grid {
        display: grid;
        grid-template-columns: repeat(3, minmax(0, 1fr));
        gap: 10px;
    }

    .barcode-info-box {
        border: 1px solid #e8eef5;
        border-radius: 14px;
        background: linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
        padding: 10px 12px;
        box-shadow: 0 4px 12px rgba(15, 23, 42, 0.03);
    }

    .barcode-info-label {
        font-size: 0.68rem;
        color: #64748b;
        font-weight: 700;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.04em;
    }

    .barcode-info-value {
        font-size: 0.9rem;
        color: #0f172a;
        font-weight: 600;
        word-break: break-word;
        line-height: 1.35;
    }

    .barcode-description-panel {
        border: 1px solid #e8eef5;
        border-radius: 16px;
        background: linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
        padding: 12px 14px;
        color: #1f2937;
        line-height: 1.55;
        box-shadow: 0 4px 12px rgba(15, 23, 42, 0.03);
    }

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

    .barcode-image-card {
        border: 1px solid #e8eef5;
        border-radius: 16px;
        background: linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
        padding: 12px;
        text-align: center;
        box-shadow: 0 4px 12px rgba(15, 23, 42, 0.03);
    }

    .barcode-image-card-title {
        font-weight: 700;
        color: #334155;
        margin-bottom: 8px;
        font-size: 0.84rem;
        letter-spacing: 0.01em;
    }

    .barcode-image-card img {
        max-height: 180px;
        width: auto;
        border-radius: 12px;
        border: 1px solid #dbe2ea;
        background: #fff;
        padding: 4px;
        box-shadow: 0 6px 14px rgba(15, 23, 42, 0.06);
    }

    .barcode-image-card .text-muted {
        border: 1px dashed #cfd8e3;
        border-radius: 12px;
        background: #f8fafc;
        padding: 28px 10px !important;
        font-size: 0.85rem;
    }

    @media (max-width: 991px) {
        .barcode-info-grid {
            grid-template-columns: repeat(2, minmax(0, 1fr));
        }
    }

    @media (max-width: 767px) {
        #barcodeViewModal .modal-body {
            padding: 10px;
        }

        .barcode-tabs-head {
            padding: 12px 12px 0;
        }

        .barcode-tab-pane {
            padding: 10px;
        }

        .barcode-info-grid,
        .barcode-image-grid {
            grid-template-columns: 1fr;
        }

        .barcode-tabs-head .nav {
            gap: 6px;
        }

        .barcode-tabs-head .nav-pills .nav-link {
            width: 100%;
            text-align: center;
        }
    }
</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-dark 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-xl modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content border-0 shadow pb-4">
            <div class="modal-header bg-light">
                <h5 class="modal-title fw-bold">Barcode Creation 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) {
                    await Swal.fire({
                        title: '<i class="bi bi-check2-circle text-success fs-1"></i>',
                        text: data.message,
                        width: 330,
                        timer: 1500,
                        showConfirmButton: false
                    });
                    window.location.reload();
                } 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;
                    // console.log("records = ", r);

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

                    function valFull(label, value) {
                        return `
                            <div class="barcode-info-label">${label}</div>
                            <div class="barcode-info-value">${value !== null && value !== undefined && value !== '' ? value : '-'}</div>
                        `;
                    }

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

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

                    let status_color = r.status == 'Drafted' ? 'warning' : (r.status == 'Applied' ?
                        'primary' : (r.status == 'Approved' ? 'success' : (r.status == 'Rejected' ?
                            'danger' : 'secondary')));

                    modalBody.html(`
                        <div class="barcode-tabs-wrap">
                            <div class="barcode-tabs-head">
                                <div class="d-flex justify-content-between align-items-start gap-3 flex-wrap">
                                    <div>
                                        <div class="barcode-tabs-title">${val(r.product_name)}</div>
                                        <div class="barcode-tabs-subtitle">${val(r.brand_name)}</div>
                                    </div>
                                    <div class="barcode-pill-status bg-${status_color}">${val(r.status)}</div>
                                </div>
                                
                                <ul class="nav nav-pills mt-0 mb-3" id="barcodeViewTabs" role="tablist">
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link active" data-bs-toggle="pill" data-bs-target="#barcode-overview" type="button">
                                            Overview
                                        </button>
                                    </li>
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link" data-bs-toggle="pill" data-bs-target="#barcode-images" type="button">
                                            Images
                                        </button>
                                    </li>
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link" data-bs-toggle="pill" data-bs-target="#barcode-measures" type="button">
                                            Measures
                                        </button>
                                    </li>
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link" data-bs-toggle="pill" data-bs-target="#barcode-pricing" type="button">
                                            Pricing
                                        </button>
                                    </li>
                                </ul>
                            </div>

                            <div class="tab-content">
                                <div class="tab-pane fade show active barcode-tab-pane" id="barcode-overview">
                                    <div class="barcode-info-grid mb-3">
                                        ${box('Brand Name', r.brand_name)}
                                        ${box('Product Name', r.product_name)}
                                        ${box('Category', r.category?.name)}
                                        ${box('Subcategory', r.subcategory?.name)}
                                        ${box('Marketing Information', r.marketing_information)}
                                        ${box('Food Type', r.food_type)}
                                    </div>
                                    <div class="barcode-description-panel">
                                        ${valFull('Description',r.product_description)}
                                    </div>
                                </div>

                                <div class="tab-pane fade barcode-tab-pane" id="barcode-images">
                                    <div class="barcode-image-grid">
                                        ${imageCard('Product Image', r.product_image_url)}
                                        ${imageCard('Art Work Image', r.art_work_image_url)}
                                    </div>
                                </div>

                                <div class="tab-pane fade barcode-tab-pane" id="barcode-measures">
                                    <div class="barcode-info-grid">
                                        ${box('Net Content Unit', r.net_content_unit)}
                                        ${box('Mass Unit', r.mass_unit)}
                                        ${box('Net Weight', r.net_weight)}
                                        ${box('Net Content', r.net_content)}
                                        ${box('Gross Weight', r.gross_weight)}
                                        ${box('Shelf Life Value', r.shelf_life_value)}
                                        ${box('Shelf Life Unit', r.shelf_life_unit)}
                                        ${box('Shelf Life Based On', r.shelf_life_based_on)}
                                    </div>
                                </div>

                                <div class="tab-pane fade barcode-tab-pane" id="barcode-pricing">
                                    <div class="barcode-info-grid">
                                        ${box('MRP Activation Date', r.mrp_activation_date)}
                                        ${box('MRP', r.mrp)}
                                        ${box('HSN', r.hsn)}
                                        ${box('GST', r.gst)}
                                        ${box('FSSAI No', r.fssai_no)}
                                        ${box('Location', r.location)}
                                    </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
