@extends('layouts.dashboard.superadminapp')

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

@section('styles')
<style>
    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;
    }
    /* Select2 Fixes for Modal */
    .select2-container {
        width: 100% !important;
        z-index: 9999;
    }
</style>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@x.x.x/dist/select2-bootstrap4.min.css">
@endsection

@section('content')

<!-- Page Heading -->
<x-layout.page-header title="UEPL | SKU Master" icon="barcode" iconColor="info" />

<!-- Alerts -->
@if(session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif
@if(session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

<!-- SKU Master Card -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-boxes mr-2"></i> SKU Master List
        </h6>
        <button class="btn btn-light btn-sm" data-toggle="modal" data-target="#addSkuModal" title="Add New SKU">
            <i class="fas fa-plus mr-1"></i> Add SKU
        </button>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table id="skuTable" class="table table-bordered table-striped table-sm" width="100%" cellspacing="0">
                <thead class="thead-light">
                    <tr>
                        <th width="50">Sl No</th>
                        <th>Item Name</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 width="100" class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- DataTables will populate -->
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add SKU Modal -->
<div class="modal fade" id="addSkuModal" role="dialog" aria-labelledby="addSkuModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
                <h5 class="modal-title text-white" id="addSkuModalLabel">
                    <i class="fas fa-plus-circle mr-2"></i> Add New SKU
                </h5>
                <button type="button" class="close text-white" 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 class="small font-weight-bold">Item Name <span class="text-danger">*</span></label>
                            <select class="form-control select2-tags" id="itemName" name="stock_item_id" required>
                                <option value="">Select or Type Item Name</option>
                                @foreach($items as $item)
                                    <option value="{{ $item->id }}">
                                        {{ $item->item_name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Category <span class="text-danger">*</span></label>
                            <select class="form-control select2-tags" id="category" disabled>
                                @foreach($categories as $cat)
                                    <option value=""></option>
                                    <option value="{{ $cat->id }}">{{ $cat->name }}</option>
                                @endforeach
                            </select>
                            <input type="hidden" name="category_id" id="categoryHidden">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Unit of Measure (UOM) <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="uom" name="uom" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Tax Rate (%) <span class="text-danger">*</span></label>
                            <select class="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 class="small font-weight-bold">Current Stock <span class="text-danger">*</span></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 class="small font-weight-bold">Default Price <span class="text-danger">*</span></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 class="small font-weight-bold">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 class="small font-weight-bold">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 class="small font-weight-bold">Min Order Level <span class="text-danger">*</span></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 class="small font-weight-bold">Max Order Level <span class="text-danger">*</span></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 class="small font-weight-bold">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 class="small font-weight-bold">Supplier Name</label>
                            <input type="text" class="form-control" id="supplierName" name="supplier_name">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">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 class="small font-weight-bold">Supplier Email</label>
                            <input type="email" class="form-control" id="supplierEmail" name="supplier_email">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Reason</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 btn-sm" data-dismiss="modal">
                        <i class="fa fa-times mr-1"></i> Cancel
                    </button>
                    <button type="button" class="btn btn-primary btn-sm" id="saveSkuBtn">
                        <i class="fa fa-save mr-1"></i> Save SKU
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit SKU Modal -->
<div class="modal fade" id="editSkuModal" tabindex="-1" role="dialog" aria-labelledby="editSkuModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header" style="background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%);">
                <h5 class="modal-title text-white" id="editSkuModalLabel">
                    <i class="fas fa-edit mr-2"></i> Edit SKU
                </h5>
                <button type="button" class="close text-white" 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">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Item Name <span class="text-danger">*</span></label>
                            <select class="form-control select2-tags" id="editItemName" name="stock_item_id" required>
                                @foreach($items as $item)
                                    <option value="{{ $item->id }}">
                                        {{ $item->item_name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Category <span class="text-danger">*</span></label>
                            <select class="form-control select2-tags" id="editCategory" disabled>
                                @foreach($categories as $cat)
                                    <option value="{{ $cat->id }}">{{ $cat->name }}</option>
                                @endforeach
                            </select>
                            <input type="hidden" name="category_id" id="editCategoryHidden">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Unit of Measure (UOM) <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="editUom" name="uom" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Tax Rate (%) <span class="text-danger">*</span></label>
                            <select class="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 class="small font-weight-bold">Current Stock <span class="text-danger">*</span></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 class="small font-weight-bold">Default Price <span class="text-danger">*</span></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 class="small font-weight-bold">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 class="small font-weight-bold">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 class="small font-weight-bold">Min Order Level <span class="text-danger">*</span></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 class="small font-weight-bold">Max Order Level <span class="text-danger">*</span></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 class="small font-weight-bold">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 class="small font-weight-bold">Supplier Name</label>
                            <input type="text" class="form-control" id="editSupplierName" name="supplier_name">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">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 class="small font-weight-bold">Supplier Email</label>
                            <input type="email" class="form-control" id="editSupplierEmail" name="supplier_email">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Reason</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 btn-sm" data-dismiss="modal">
                        <i class="fa fa-times mr-1"></i> Cancel
                    </button>
                    <button type="button" class="btn btn-warning btn-sm" id="updateSkuBtn">
                        <i class="fa fa-save mr-1"></i> Update SKU
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
let skuTable;

$(document).ready(function() {


    $('#itemName').on('change', function() {
        let id = $(this).val();
        if(id){
            $.get('/superadmin/sku/item/' + id, function(data){
                $('#category').val(data.category_id).trigger('change');
                // important
                $('#categoryHidden').val(data.category_id);
                $('#uom').val(data.uom);
                $('#hsnCode').val(data.hsn_code);
            });
        }
    });
    $('#editItemName').on('change', function() {
        let id = $(this).val();

        if(id){
            $.get('/superadmin/sku/item/' + id, function(data){
                $('#editCategory').val(data.category_id).trigger('change');
                // important
                $('#editCategoryHidden').val(data.category_id);
                $('#editUom').val(data.uom);
                // $('#editHsnCode').val(data.hsn_code);
            });
        }
    });
        
    // Initialize Select2
    $('.select2-tags').select2({
        // tags: true,
        dropdownParent: $('#addSkuModal'), // Fix for modal focus
        theme: 'bootstrap4',
        placeholder: "Select or Type..."
    });
    $('#editSkuModal .select2-tags').select2({
        dropdownParent: $('#editSkuModal'),
        theme: 'bootstrap4',
        width: '100%',
        placeholder: "Select or Type..."
    });

    skuTable = $('#skuTable').DataTable({
        processing: true,
        serverSide: false,
        ajax: "{{ route('superadmin.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"
        },
        createdRow: function(row, data, dataIndex) {
            if(data.DT_RowClass) {
                $(row).addClass(data.DT_RowClass);
            }
        }
    });

    // Add SKU
    $('#saveSkuBtn').on('click', function(e) {
        e.preventDefault();
        let $form = $('#skuForm');
        $.ajax({
            url: "{{ route('superadmin.sku.store') }}",
            type: "POST",
            data: $form.serialize(),
            success: function(response) {
                $('#addSkuModal').modal('hide');
                skuTable.ajax.reload(null, false); // Reload table data
                $form[0].reset();
                $('.select2-tags').val(null).trigger('change'); // Reset Select2
                Swal.fire('Success!', response.success, 'success');
            },
            error: function(xhr) {
                if (xhr.responseJSON && xhr.responseJSON.errors) {
                    let errors = Object.values(xhr.responseJSON.errors).flat().join('<br>');
                    Swal.fire('Validation Error', errors, 'error');
                } else {
                    Swal.fire('Error!', 'Something went wrong!', 'error');
                }
            }
        });
    });

    // Edit SKU - Need similar Select2 logic if Edit modal uses Select2 or Text inputs?
    // User requested dropdown on "Add" form mainly. For Edit, ideally we should match.
    // The current Edit Modal uses text inputs. Since user specified "Add stock items... upon adding new entry",
    // I will leave Edit as text inputs for now to minimize complexity unless requested, 
    // or arguably I should update Edit Modal to match. 
    // Given the constraints and specific user text "Upon adding a new entry", I'll focus on the Add Modal first.
    // However, I will enhance the Edit population to work correctly.

    $('#skuTable').on('click', '.editBtn', function() {
        let skuId = $(this).data('id');
        $.get("{{ url('superadmin/sku') }}/" + skuId + "/edit", function(response) {
            $('#editId').val(response.id);
            // $('#edititemName').val(response.item_name);
            // $('#editCategory').val(response.category);
            $('#editItemName').val(response.stock_item_id).trigger('change');
            $('#editCategory').val(response.category_id).trigger('change');
            $('#editUom').val(response.uom);
            $('#editTax').val(parseInt(response.tax_rate)).trigger('change');
            $('#editCurrentStock').val(parseInt(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('superadmin/sku') }}/" + skuId,
            type: "POST", // Method spoofing used
            data: $form.serialize(),
            success: function(response) {
                $('#editSkuModal').modal('hide');
                skuTable.ajax.reload(null, false);
                Swal.fire('Success!', response.success, 'success');
            },
            error: function(xhr) {
                if (xhr.responseJSON && xhr.responseJSON.errors) {
                    let errors = Object.values(xhr.responseJSON.errors).flat().join('<br>');
                    Swal.fire('Validation Error', errors, 'error');
                } else {
                    Swal.fire('Error!', 'Something went wrong!', 'error');
                }
            }
        });
    });

    // Delete SKU
    $('#skuTable').on('click', '.deleteBtn', function() {
        let skuId = $(this).data('id');
        Swal.fire({
            title: 'Delete SKU?',
            text: "Are you sure you want to delete this SKU? This action cannot be undone.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, Delete!',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: "{{ url('superadmin/sku') }}/" + skuId,
                    type: "DELETE",
                    data: { _token: '{{ csrf_token() }}' },
                    success: function(response) {
                        skuTable.ajax.reload(null, false);
                        Swal.fire('Deleted!', response.success, 'success');
                    },
                    error: function(xhr) {
                        Swal.fire('Error!', 'Error deleting SKU', 'error');
                    }
                });
            }
        });
    });
});
</script>
@endsection
