@extends('layouts.dashboard.adminapp')

@section('title', 'SKU Master')

@section('styles')
    <!-- DataTables Bootstrap 4 & Plugins CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap4.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
    <style>
    #toast-container > .toast-success {
    background-color: #198754 !important; /* Bootstrap success green */
    color: #fff !important;
}
#toast-container > .toast-error {
    background-color: #dc3545 !important; /* Bootstrap danger red */
    color: #fff !important;
}
#toast-container > .toast-info {
    background-color: #0dcaf0 !important; /* Bootstrap info blue */
    color: #222 !important;
}
#toast-container > .toast-warning {
    background-color: #ffc107 !important;
    color: #222 !important;
}
        div.dt-buttons {
            float: left;
            display: flex !important;
        }

        .dataTable {
            overflow-x: auto !important;
            display: table !important;
        }

        .dt-buttons .btn {
            margin-right: 0.5rem !important;
            padding: 0.25rem 0.75rem !important;
            font-size: 0.95rem !important;
        }

        .modal .form-label {
            font-weight: 500;
        }

        .modal-footer .btn {
            min-width: 100px;
        }

        .action-btns .btn {
            margin-right: 0.25rem;
            margin-bottom: 0.1rem;
        }

        .btn {
            width: auto;
        }
    </style>
@endsection

@section('content')
    <div class="container-fluid bg-white">
        <div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4 border-bottom">
            <h1 class="h5 mb-0 text-gray-800">UEPL / Stock Keeping Unit</h1>
            <div class="display-date">
                <span id="day">day</span>,
                <span id="daynum">00</span>
                <span id="month">month</span>
                <span id="year">0000</span>
            </div>
            <div class="display-time"></div>
        </div>

        <div class="row">
            <div class="col-lg-12">
                <div class="container-fluid py-4 sku-master">
                    <div class="row mb-4 align-items-center">
                        <div class="col-md-10">
                            <h2 class="mb-0"><i class="bi bi-box-seam"></i> SKU Master</h2>
                        </div>
                        <div class="col-md-2 text-end">
                            
                        </div>
                    </div>

                    <div class="card shadow mb-4">
                        <div class="card-header d-flex justify-content-between align-items-center" style="float: left;flex-direction: row-reverse;">
                            <span><button class="btn btn-primary" data-toggle="modal" data-target="#addSkuModal" title=" Add New SKU">
                                <i class="fa fa-plus-square"></i>
                            </button></span>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table id="skuTable" class="table table-bordered table-striped table-hover"
                                    style="width:100%">
                                    <thead>
                                        <tr>
                                            <th>SL No.</th>
                                            <th>Item</th>
                                            <th>Category</th>
                                            <th>UOM</th>
                                            <th>Current Stock</th>
                                            <th>Default Price</th>
                                            <th>Stock Status</th>
                                            <th>Min Order</th>
                                            <th>Max Order</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- DataTables will populate -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Add SKU Modal -->
                <div class="modal fade" id="addSkuModal" tabindex="-1" aria-labelledby="addSkuModalLabel"
                    aria-hidden="true">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="addSkuModalLabel">Add New SKU</h5>
                                <button type="button" class="close btn" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <form id="skuForm" method="POST">
                                @csrf
                                <div class="modal-body">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="itemName" class="form-label">Item Name *</label>
                                            <input type="text" class="form-control" id="itemName" name="item_name"
                                                required>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="category" class="form-label">Category *</label>
                                            <input type="text" class="form-control" id="category" name="category"
                                                required>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-4 mb-3">
                                            <label for="uom" class="form-label">Unit of Measure (UOM) *</label>
                                            <input type="text" class="form-control" id="uom" name="uom"
                                                required>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="tax" class="form-label">Tax Rate (%) *</label>
                                            <select class="form-select form-control" id="tax" name="tax_rate"
                                                required>
                                                <option value="">Select Tax</option>
                                                <option value="0">0%</option>
                                                <option value="3">3%</option>
                                                <option value="6">6%</option>
                                                <option value="9">9%</option>
                                                <option value="14">14%</option>
                                                <option value="18">18%</option>
                                            </select>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="currentStock" class="form-label">Current Stock *</label>
                                            <input type="number" class="form-control" id="currentStock"
                                                name="current_stock" min="0" required>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-4 mb-3">
                                            <label for="defaultPrice" class="form-label">Default Price *</label>
                                            <input type="number" class="form-control" id="defaultPrice"
                                                name="default_price" min="0" step="0.01" required>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="discountPrice" class="form-label">Discount Price</label>
                                            <input type="number" class="form-control" id="discountPrice"
                                                name="discount_price" min="0" step="0.01">
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="tcs" class="form-label">TCS (%)</label>
                                            <input type="number" class="form-control" id="tcs" name="tcs"
                                                min="0" max="100" step="0.01">
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-4 mb-3">
                                            <label for="minOrderLevel" class="form-label">Minimum Order Level *</label>
                                            <input type="number" class="form-control" id="minOrderLevel"
                                                name="min_order_level" min="0" required>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="maxOrderLevel" class="form-label">Maximum Order Level *</label>
                                            <input type="number" class="form-control" id="maxOrderLevel"
                                                name="max_order_level" min="0" required>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="hsnCode" class="form-label">HSN Code</label>
                                            <input type="text" class="form-control" id="hsnCode" name="hsn_code">
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="supplierName" class="form-label">Supplier Name</label>
                                            <input type="text" class="form-control" id="supplierName"
                                                name="supplier_name">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="supplierPhone" class="form-label">Supplier Phone</label>
                                            <input type="tel" class="form-control" id="supplierPhone"
                                                name="supplier_phone">
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="supplierEmail" class="form-label">Supplier Email</label>
                                            <input type="email" class="form-control" id="supplierEmail"
                                                name="supplier_email">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="reason" class="form-label">Reason (if any)</label>
                                            <input type="text" class="form-control" id="reason" name="reason">
                                        </div>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    <button type="button" class="btn btn-primary" id="saveSkuBtn">Save SKU</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Edit SKU Modal -->
                <div class="modal fade" id="editSkuModal" tabindex="-1" aria-labelledby="editSkuModalLabel"
                    aria-hidden="true">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="editSkuModalLabel">Edit SKU</h5>
                                <button type="button" class="close btn" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <form id="editSkuForm" method="POST">
                                @csrf
                                @method('PUT')
                                <input type="hidden" id="editId" name="id">
                                <div class="modal-body">
                                    <!-- same fields as add -->
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="edititemName" class="form-label">Item Name *</label>
                                            <input type="text" class="form-control" id="edititemName"
                                                name="item_name" required>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="editCategory" class="form-label">Category *</label>
                                            <input type="text" class="form-control" id="editCategory" name="category"
                                                required>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-4 mb-3">
                                            <label for="editUom" class="form-label">Unit of Measure (UOM) *</label>
                                            <input type="text" class="form-control" id="editUom" name="uom"
                                                required>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="editTax" class="form-label">Tax Rate (%) *</label>
                                            <select class="form-select form-control" id="editTax" name="tax_rate"
                                                required>
                                                <option value="">Select Tax</option>
                                                <option value="0">0%</option>
                                                <option value="3">3%</option>
                                                <option value="6">6%</option>
                                                <option value="9">9%</option>
                                                <option value="14">14%</option>
                                                <option value="18">18%</option>
                                            </select>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="editCurrentStock" class="form-label">Current Stock *</label>
                                            <input type="number" class="form-control" id="editCurrentStock"
                                                name="current_stock" min="0" required>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-4 mb-3">
                                            <label for="editDefaultPrice" class="form-label">Default Price *</label>
                                            <input type="number" class="form-control" id="editDefaultPrice"
                                                name="default_price" min="0" step="0.01" required>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="editDiscountPrice" class="form-label">Discount Price</label>
                                            <input type="number" class="form-control" id="editDiscountPrice"
                                                name="discount_price" min="0" step="0.01">
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="editTcs" class="form-label">TCS (%)</label>
                                            <input type="number" class="form-control" id="editTcs" name="tcs"
                                                min="0" max="100" step="0.01">
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-4 mb-3">
                                            <label for="editMinOrderLevel" class="form-label">Minimum Order Level
                                                *</label>
                                            <input type="number" class="form-control" id="editMinOrderLevel"
                                                name="min_order_level" min="0" required>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="editMaxOrderLevel" class="form-label">Maximum Order Level
                                                *</label>
                                            <input type="number" class="form-control" id="editMaxOrderLevel"
                                                name="max_order_level" min="0" required>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="editHsnCode" class="form-label">HSN Code</label>
                                            <input type="text" class="form-control" id="editHsnCode" name="hsn_code">
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="editSupplierName" class="form-label">Supplier Name</label>
                                            <input type="text" class="form-control" id="editSupplierName"
                                                name="supplier_name">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="editSupplierPhone" class="form-label">Supplier Phone</label>
                                            <input type="tel" class="form-control" id="editSupplierPhone"
                                                name="supplier_phone">
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="editSupplierEmail" class="form-label">Supplier Email</label>
                                            <input type="email" class="form-control" id="editSupplierEmail"
                                                name="supplier_email">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="editReason" class="form-label">Reason (if any)</label>
                                            <input type="text" class="form-control" id="editReason" name="reason">
                                        </div>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    <button type="button" class="btn btn-primary" id="updateSkuBtn">Update SKU</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Delete Confirmation Modal -->
                <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel"
                    aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header bg-danger text-white">
                                <h5 class="modal-title" id="deleteModalLabel">Confirm Delete</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                Are you sure you want to delete this SKU? This action cannot be undone.
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">Delete</button>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- End Delete Confirmation Modal -->
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <!-- DataTables Bootstrap 4 & Plugins JS -->
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap4.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.colVis.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap4.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <script>
        let skuTable;
        $(document).ready(function() {
            skuTable = $('#skuTable').DataTable({
                processing: true,
                serverSide: false,
                ajax: "{{ route('admin.sku.data') }}",
                dom: 'Bfrtip',
                buttons: [{
                        extend: 'copy',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'csv',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'excel',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'pdf',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'print',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'colvis',
                        className: 'btn btn-secondary btn-sm'
                    }
                ],
                columns: [{
                        data: 'slno',
                        name: 'slno',
                        orderable: false,
                        searchable: false
                    },
                    {
                        data: 'item_name',
                        name: 'item_name'
                    },
                    {
                        data: 'category',
                        name: 'category'
                    },
                    {
                        data: 'uom',
                        name: 'uom'
                    },
                    {
                        data: 'current_stock',
                        name: 'current_stock'
                    },
                    {
                        data: 'default_price',
                        name: 'default_price'
                    },
                    {
                        data: 'stock_status',
                        name: 'stock_status'
                    },
                    {
                        data: 'min_order_level',
                        name: 'min_order_level'
                    },
                    {
                        data: 'max_order_level',
                        name: 'max_order_level'
                    },
                    {
                        data: 'actions',
                        name: 'actions',
                        orderable: false,
                        searchable: false
                    }
                ],
                pageLength: 10,
                responsive: true,
                language: {
                    "emptyTable": "No SKUs found"
                }
            });

            // Add SKU
            $('#saveSkuBtn').on('click', function(e) {
                e.preventDefault();
                let $form = $('#skuForm');
                $.ajax({
                    url: "{{ route('admin.sku.store') }}",
                    type: "POST",
                    data: $form.serialize(),
                    success: function(response) {
                        $('#addSkuModal').modal('hide');
                        skuTable.ajax.reload(null, false);
                        $form[0].reset();
                        toastr.success(response.success);
                    },
                    error: function(xhr) {
                        if (xhr.responseJSON && xhr.responseJSON.errors) {
                            $.each(xhr.responseJSON.errors, function(key, value) {
                                toastr.error(value[0]);
                            });
                        } else {
                            toastr.error('Something went wrong!');
                        }
                    }
                });
            });

            // Edit SKU
            $('#skuTable').on('click', '.editBtn', function() {
                let skuId = $(this).data('id');
                $.get("{{ url('admin/sku') }}/" + skuId + "/edit", function(response) {
                    $('#editId').val(response.id);
                    $('#edititemName').val(response.item_name);
                    $('#editCategory').val(response.category);
                    $('#editUom').val(response.uom);
                    $('#editTax').val(parseInt(response.tax_rate)).trigger('change');
                    $('#editCurrentStock').val(response.current_stock);
                    $('#editDefaultPrice').val(response.default_price);
                    $('#editDiscountPrice').val(response.discount_price);
                    $('#editTcs').val(response.tcs);
                    $('#editMinOrderLevel').val(response.min_order_level);
                    $('#editMaxOrderLevel').val(response.max_order_level);
                    $('#editHsnCode').val(response.hsn_code);
                    $('#editSupplierName').val(response.supplier_name);
                    $('#editSupplierPhone').val(response.supplier_phone);
                    $('#editSupplierEmail').val(response.supplier_email);
                    $('#editReason').val(response.reason);
                    $('#editSkuModal').modal('show');
                });
            });

            // Update SKU
            $('#updateSkuBtn').on('click', function(e) {
                e.preventDefault();
                let skuId = $('#editId').val();
                let $form = $('#editSkuForm');
                $.ajax({
                    url: "{{ url('admin/sku') }}/" + skuId,
                    type: "POST",
                    data: $form.serialize(),
                    success: function(response) {
                        $('#editSkuModal').modal('hide');
                        skuTable.ajax.reload(null, false);
                        toastr.success(response.success);
                    },
                    error: function(xhr) {
                        if (xhr.responseJSON && xhr.responseJSON.errors) {
                            $.each(xhr.responseJSON.errors, function(key, value) {
                                toastr.error(value[0]);
                            });
                        } else {
                            toastr.error('Something went wrong!');
                        }
                    }
                });
            });

            // Delete SKU
            $('#skuTable').on('click', '.deleteBtn', function() {
                let skuId = $(this).data('id');
                $('#deleteModal').modal('show');
                $('#confirmDeleteBtn').data('id', skuId);
            });

            $('#confirmDeleteBtn').on('click', function() {
                let skuId = $(this).data('id');
                $.ajax({
                    url: "{{ url('admin/sku') }}/" + skuId,
                    type: "DELETE",
                    data: {
                        _token: '{{ csrf_token() }}'
                    },
                    success: function(response) {
                        $('#deleteModal').modal('hide');
                        skuTable.ajax.reload(null, false);
                        toastr.success(response.success);
                    },
                    error: function(xhr) {
                        toastr.error('Error deleting SKU');
                    }
                });
            });
        });
    </script>
@endpush
