@extends('layouts.dashboard.adminapp')

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

@section('styles')
    <!-- Bootstrap 4 DataTables and Plugins CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap4.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    <style>
        .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;
        }

        .status-badge {
            padding: 2px 7px;
            border-radius: 10px;
            font-size: 0.85em;
            color: #fff;
        }

        .status-completed {
            background: #28a745;
        }

        .status-pending {
            background: #ffc107;
            color: #000;
        }

        .status-cancelled {
            background: #dc3545;
        }

        .modal-content {
            border-radius: 12px;
        }

        /* Modal title bold, left */
        .modal-title {
            font-weight: 700;
        }

        /* Force better alignment on form fields */
        .modal-body .row>[class^="col-"] {
            display: flex;
            flex-direction: column;
            justify-content: flex-end;
        }

        /* Responsive: Modal fits on mobile */
        @media (max-width: 767.98px) {
            .modal-lg {
                max-width: 97vw !important;
            }
        }
    </style>
@endsection

@section('content')
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <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 / SKU (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="container-fluid py-4 sku-movement">
            <div class="row mb-4 align-items-center">
                <div class="col-md-10">
                    <h2 class="mb-0"><i class="bi bi-arrow-left-right"></i> SKU Stock Movement</h2>
                </div>
                <div class="col-md-2 text-end">
                   
                </div>
            </div>

            <div class="row mb-3">
                <div class="col-md-4 mb-2">
                    <input type="text" class="form-control" placeholder="Search SKU, reference, location..."
                        id="searchInput">
                </div>
                <div class="col-md-2 mb-2">
                    <select class="form-control" id="statusFilter">
                        <option value="">All Statuses</option>
                        <option value="completed">Completed</option>
                        <option value="pending">Pending</option>
                        <option value="cancelled">Cancelled</option>
                    </select>
                </div>
                <div class="col-md-2 mb-2">
                    <select class="form-control" id="typeFilter">
                        <option value="">All Types</option>
                        <option value="inbound">Inbound</option>
                        <option value="outbound">Outbound</option>
                        <option value="transfer">Transfer</option>
                        <option value="adjustment">Adjustment</option>
                    </select>
                </div>
                <div class="col-md-2 mb-2">
                    <input type="date" class="form-control" id="dateFilter">
                </div>
            </div>

            <div class="card mb-5">
                <div class="card-header d-flex justify-content-end align-items-center" style="font-size: 1.15rem; font-weight: 500;">
                    <a class="btn btn-success mb-2" id="exportBtn" title="Export" style="margin-right:5px;">
                        <i class="bi bi-file-earmark-arrow-down"></i>
                    </a>
                    <a class="btn btn-primary mb-2" id="newMovementBtn" title="New Movement">
                        <i class="bi bi-plus-circle"></i>
                    </a>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="movementsTable" class="table table-bordered table-striped table-hover w-100">
                            <thead>
                                <tr>
                                    <th>Reference</th>
                                    <th>SKU</th>
                                    <th>Type</th>
                                    <th>Quantity</th>
                                    <th>From Location</th>
                                    <th>To Location</th>
                                    <th>Date</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- DataTables AJAX -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        {{-- Movement Modal --}}
        <div class="modal fade" id="movementModal" tabindex="-1" aria-labelledby="movementModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form id="movementForm" autocomplete="off">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">New Stock Movement</h5>
                    <button type="button" class="close btn" data-dismiss="modal" aria-label="Close" id="modalCloseBtn">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body pb-0">
                    <div id="alertMessage" class="alert d-none"></div>
                    <div class="form-row">
                        <!-- Movement Type -->
                        <div class="form-group col-md-3">
                            <label class="form-label mb-1">Movement Type</label>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="movementType" id="inbound" value="inbound" checked>
                                <label class="form-check-label" for="inbound">Inbound</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="movementType" id="outbound" value="outbound">
                                <label class="form-check-label" for="outbound">Outbound</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="movementType" id="transfer" value="transfer">
                                <label class="form-check-label" for="transfer">Transfer</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="movementType" id="adjustment" value="adjustment">
                                <label class="form-check-label" for="adjustment">Adjustment</label>
                            </div>
                        </div>
                        <!-- Reference -->
                        <div class="form-group col-md-3">
                            <label for="reference" class="form-label mb-1">Reference Number</label>
                            <input type="text" class="form-control" id="reference" name="reference" required>
                        </div>
                        <!-- Date -->
                        <div class="form-group col-md-3">
                            <label for="date" class="form-label mb-1">Movement Date</label>
                            <input type="datetime-local" class="form-control" id="date" name="date" required>
                        </div>
                        <!-- Status -->
                        <div class="form-group col-md-3">
                            <label class="form-label mb-1">Status</label>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="status" id="status-completed" value="completed">
                                <label class="form-check-label" for="status-completed">Completed</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="status" id="status-pending" value="pending" checked>
                                <label class="form-check-label" for="status-pending">Pending</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="status" id="status-cancelled" value="cancelled">
                                <label class="form-check-label" for="status-cancelled">Cancelled</label>
                            </div>
                        </div>
                    </div>
                    <div class="form-row">
                        <!-- SKU -->
                        <div class="form-group col-md-4">
                            <label for="sku" class="form-label mb-1">SKU</label>
                            <select class="form-control" id="sku" name="sku_id" required>
                                <option value="">Select SKU</option>
                                @foreach ($skus as $sku)
                                    <option value="{{ $sku->id }}">{{ $sku->item_name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <!-- Quantity -->
                        <div class="form-group col-md-2">
                            <label for="quantity" class="form-label mb-1">Quantity</label>
                            <input type="number" class="form-control" id="quantity" name="quantity" min="1" required>
                        </div>
                        <!-- From Location -->
                        <div class="form-group col-md-3" id="fromLocationGroup">
                            <label for="fromLocation" class="form-label mb-1">From Location</label>
                            <select class="form-control" id="fromLocation" name="from_location">
                                <option value="">Select Location</option>
                                @foreach ($locations as $loc)
                                    <option value="{{ $loc }}">{{ $loc }}</option>
                                @endforeach
                            </select>
                        </div>
                        <!-- To Location -->
                        <div class="form-group col-md-3" id="toLocationGroup">
                            <label for="toLocation" class="form-label mb-1">To Location</label>
                            <select class="form-control" id="toLocation" name="to_location">
                                <option value="">Select Location</option>
                                @foreach ($locations as $loc)
                                    <option value="{{ $loc }}">{{ $loc }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="notes" class="form-label mb-1">Notes</label>
                        <textarea class="form-control" id="notes" name="notes" rows="2"></textarea>
                    </div>
                    <input type="hidden" id="movementId">
                </div>
                <div class="modal-footer pt-1">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal" id="cancelBtn">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="submitBtn"><i class="bi bi-save"></i> Save Movement</button>
                </div>
            </form>
        </div>
    </div>
</div>


        {{-- Delete 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 btn" data-dismiss="modal" aria-label="Close"
                            id="closeDeleteModal">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        Are you sure you want to delete this stock movement? This action cannot be undone.
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal"
                            id="cancelDeleteBtn">Cancel</button>
                        <button type="button" class="btn btn-danger" id="confirmDeleteBtn">Delete</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <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/toastr.js/latest/toastr.min.js"></script>
    <script>
        $(document).ready(function() {
            updateLocationFields();
            // DataTable initialization (with server-side if your backend supports it)
            let table = $('#movementsTable').DataTable({
                processing: true,
                serverSide: false, // Change to true if your route supports DataTables server-side
                ajax: {
                    url: "{{ url('/admin/skumovement/list') }}",
                    data: function(d) {
                        d.search = $('#searchInput').val();
                        d.status = $('#statusFilter').val();
                        d.type = $('#typeFilter').val();
                        d.date = $('#dateFilter').val();
                    },
                    dataSrc: 'data'
                },
                columns: [
    { data: 'reference' },
    { data: 'item_name', title: 'SKU' }, // Shows item name
    { data: 'type',
      render: function(data) { return data.charAt(0).toUpperCase() + data.slice(1); }
    },
    { data: 'quantity' },
    { data: 'from_location', render: function(data) { return data || '-'; } },
    { data: 'to_location', render: function(data) { return data || '-'; } },
    { data: 'date', render: function(data) { return data ? data.substring(0, 16).replace('T', ' ') : ''; } },
    { data: 'status', render: function(data) {
        let badge = 'status-' + data;
        return `<span class="status-badge ${badge}">${data.charAt(0).toUpperCase()+data.slice(1)}</span>`;
      }
    },
    { data: null, orderable: false, searchable: false,
      render: function(data, type, row) {
        return `<div class="action-btns">
          <button class="btn btn-sm btn-warning edit-btn" data-id="${row.id}" title="Edit"><i class="bi bi-pencil"></i></button>
          <button class="btn btn-sm btn-danger delete-btn" data-id="${row.id}" title="Delete"><i class="bi bi-trash"></i></button>
        </div>`;
      }
    }
],
                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'
                    }
                ],
                pageLength: 10,
                responsive: true,
                language: {
                    emptyTable: "No stock movements found"
                }
            });

            // Filter events: redraw table
            $('#searchInput, #statusFilter, #typeFilter, #dateFilter').on('change keyup', function() {
                table.ajax.reload();
            });

            // Modal reset
            $('#newMovementBtn').on('click', function() {
    $('#movementForm')[0].reset();
    $('#movementId').val('');
    $('#modalTitle').text('New Stock Movement');
    // Set default values (optional, for clarity)
    $('input[name="movementType"][value="inbound"]').prop('checked', true);
    $('input[name="status"][value="pending"]').prop('checked', true);
    $('#sku').val('');
    $('#quantity').val('');
    $('#fromLocation').val('');
    $('#toLocation').val('');
    $('#notes').val('');
    updateLocationFields(); // Hide/show fields based on default movementType
    $('#alertMessage').addClass('d-none').removeClass('alert-danger alert-success');
    $('#movementModal').modal('show');
});

function updateLocationFields() {
    var movementType = $('input[name="movementType"]:checked').val();
    if (movementType === 'inbound') {
        $('#fromLocationGroup').hide();
        $('#toLocationGroup').show();
        $('#fromLocation').prop('required', false);
        $('#toLocation').prop('required', true);
    } else if (movementType === 'outbound') {
        $('#fromLocationGroup').show();
        $('#toLocationGroup').hide();
        $('#fromLocation').prop('required', true);
        $('#toLocation').prop('required', false);
    } else if (movementType === 'transfer') {
        $('#fromLocationGroup').show();
        $('#toLocationGroup').show();
        $('#fromLocation').prop('required', true);
        $('#toLocation').prop('required', true);
    } else if (movementType === 'adjustment') {
        $('#fromLocationGroup').show();
        $('#toLocationGroup').hide();
        $('#fromLocation').prop('required', true);
        $('#toLocation').prop('required', false);
    }
}
$('input[name="movementType"]').on('change', updateLocationFields);


            // Cancel modal
            $('#cancelBtn, #modalCloseBtn').on('click', function() {
                $('#movementModal').modal('hide');
            });

            // Add/Edit
            $('#movementForm').on('submit', function(e) {
                e.preventDefault();
                console.log('Submitting status:', $('input[name="status"]:checked').val());
                $('#product').val($('#sku option:selected').text());
                let payload = {
                    id: $('#movementId').val(),
                    reference: $('#reference').val(),
                    sku_id: $('#sku').val(),
                    product: $('#product').val(),
                    type: $('input[name="movementType"]:checked').val(),
                    quantity: $('#quantity').val(),
                    from_location: $('#fromLocation').val(),
                    to_location: $('#toLocation').val(),
                    date: $('#date').val(),
                    status: $('input[name="status"]:checked').val(),
                    notes: $('#notes').val(),
                    _token: $('meta[name="csrf-token"]').attr('content')
                };
                $.post('{{ url('/admin/skumovement/store') }}', payload, function(res) {
                    $('#movementModal').modal('hide');
                    // Clear filters so all data is shown
                    $('#searchInput').val('');
                    $('#statusFilter').val('');
                    $('#typeFilter').val('');
                    $('#dateFilter').val('');
                    table.ajax.reload(null, false);
                    toastr.success('Saved!');
                }).fail(function(xhr) {
                    toastr.error('Failed: ' + (xhr.responseJSON?.message || 'Error'));
                });
            });



            // Edit
            $('#movementsTable').on('click', '.edit-btn', function() {
                let id = $(this).data('id');
                $.get('{{ url('/admin/skumovement') }}/' + id, function(data) {
                    $('#movementId').val(data.id);
                    $('#reference').val(data.reference);
                    $('#sku').val(data.sku_id);
                    $('#quantity').val(data.quantity);
                    $('#fromLocation').val(data.from_location);
                    $('#toLocation').val(data.to_location);
                    $('#date').val(data.date ? data.date.replace(' ', 'T') : '');
                    $('input[name="movementType"][value="' + data.type + '"]').prop('checked',
                        true);
                    $('input[name="status"][value="' + data.status + '"]').prop('checked', true);
                    $('#notes').val(data.notes);
                    $('#modalTitle').text('Edit Stock Movement');
                    $('#movementModal').modal('show');
                });
            });

            // Delete
            let deleteId = null;
            $('#movementsTable').on('click', '.delete-btn', function() {
                deleteId = $(this).data('id');
                $('#deleteModal').modal('show');
            });
            $('#cancelDeleteBtn, #closeDeleteModal').on('click', function() {
                $('#deleteModal').modal('hide');
            });
            $('#confirmDeleteBtn').on('click', function() {
                $.ajax({
                    url: '{{ url('/admin/skumovement') }}/' + deleteId,
                    type: 'DELETE',
                    data: {
                        _token: $('meta[name="csrf-token"]').attr('content')
                    },
                    success: function() {
                        $('#deleteModal').modal('hide');
                        table.ajax.reload(null, false);
                        toastr.success('Deleted!');
                    }
                });
            });

            // Export button (optional, as DataTables buttons are already present)
            $('#exportBtn').on('click', function() {
                table.button('.buttons-csv').trigger();
            });
        });
    </script>
@endpush
