@extends('layouts.dashboard.superadminapp')

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

@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;
    }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<x-layout.page-header title="UEPL | SKU Stock Movement" 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

<!-- Filter Section -->
<div class="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #6c757d 0%, #495057 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-filter mr-2"></i> Filters
        </h6>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-3 mb-2">
                <label class="small font-weight-bold">Search</label>
                <input type="text" class="form-control form-control-sm" placeholder="SKU, reference, location..." id="searchInput">
            </div>
            <div class="col-md-3 mb-2">
                <label class="small font-weight-bold">Status</label>
                <select class="form-control form-control-sm" 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-3 mb-2">
                <label class="small font-weight-bold">Movement Type</label>
                <select class="form-control form-control-sm" 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-3 mb-2">
                <label class="small font-weight-bold">Date</label>
                <input type="date" class="form-control form-control-sm" id="dateFilter">
            </div>
        </div>
    </div>
</div>

<!-- SKU Movement 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-exchange-alt mr-2"></i> SKU Stock Movement List
        </h6>
        <button class="btn btn-light btn-sm" id="newMovementBtn" title="Add New Movement">
            <i class="fas fa-plus mr-1"></i> Add Movement
        </button>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table id="movementsTable" class="table table-bordered table-striped table-sm" width="100%" cellspacing="0">
                <thead class="thead-light">
                    <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 width="100" class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- DataTable fills -->
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Movement Modal -->
<div class="modal fade" id="movementModal" tabindex="-1" role="dialog" aria-labelledby="movementModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <form id="movementForm">
                @csrf
                <input type="hidden" id="movementId">
                <div class="modal-header" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
                    <h5 class="modal-title text-white" id="movementModalLabel">
                        <i class="fas fa-plus-circle mr-2"></i> New Stock Movement
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Movement Type <span class="text-danger">*</span></label>
                            <div class="mt-1">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="movementType" id="inbound" value="inbound" checked>
                                    <label class="form-check-label small" 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 small" 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 small" 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 small" for="adjustment">Adjustment</label>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Reference Number <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="reference" name="reference" required>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Movement Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="date" name="date" required>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Status <span class="text-danger">*</span></label>
                            <div class="mt-1">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="status" id="status-pending" value="pending" checked>
                                    <label class="form-check-label small" for="status-pending">Pending</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="status" id="status-completed" value="completed">
                                    <label class="form-check-label small" for="status-completed">Completed</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 small" for="status-cancelled">Cancelled</label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">SKU <span class="text-danger">*</span></label>
                            <select class="form-control" id="sku" name="sku_id" required>
                                <option value="">Select SKU</option>
                                @foreach ($skus as $sku)
                                <option value="{{ $sku->stock_item_id }}">
                                    {{ $sku->stockItem->item_name ?? 'Unknown Item' }}
                                </option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-2 mb-3">
                            <label class="small font-weight-bold">Quantity <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="quantity" name="quantity" min="1" required>
                        </div>
                        <div class="col-md-3 mb-3" id="fromLocationGroup">
                            <label class="small font-weight-bold">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>
                        <div class="col-md-3 mb-3" id="toLocationGroup">
                            <label class="small font-weight-bold">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="row">
                        <div class="col-12 mb-3">
                            <label class="small font-weight-bold">Notes</label>
                            <textarea class="form-control" id="notes" name="notes" rows="2" placeholder="Optional notes..."></textarea>
                        </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="submit" class="btn btn-primary btn-sm" id="saveMovement">
                        <i class="fa fa-save mr-1"></i> Save Movement
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
let table;

$(document).ready(function() {
    updateLocationFields();

    table = $('#movementsTable').DataTable({
        processing: true,
        serverSide: false,
        ajax: {
            url: "{{ url('/superadmin/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' },
            {
                data: 'type',
                render: function(data) {
                    if (!data) return '<span class="badge badge-secondary">-</span>';
                    let colors = {
                        'inbound': 'success',
                        'outbound': 'danger',
                        'transfer': 'info',
                        'adjustment': 'warning'
                    };
                    let color = colors[data] || 'secondary';
                    return `<span class="badge badge-${color}">${data.charAt(0).toUpperCase() + data.slice(1)}</span>`;
                }
            },
            { data: 'quantity' },
            { data: 'from_location', render: function(data) { return data || '-'; } },
            { data: 'to_location', render: function(data) { return data || '-'; } },
            {
                data: 'date',
                rrender: function(data) {
                    return data ? new Date(data).toLocaleDateString('en-GB', { day:'2-digit', month:'short', year:'numeric' }) : '-';
                }
            },
            {
                data: 'status',
                render: function(data) {
                    if (data === 'completed') {
                        return '<span class="badge badge-success">Completed</span>';
                    } else if (data === 'cancelled') {
                        return '<span class="badge badge-danger">Cancelled</span>';
                    }
                    return '<span class="badge badge-warning">Pending</span>';
                }
            },
            {
                data: null,
                orderable: false,
                searchable: false,
                render: function(data, type, row) {
                    return `
                        <div class="text-center" style="white-space: nowrap;">
                            <button class="btn btn-warning btn-sm edit-btn" data-id="${row.id}" title="Edit">
                                <i class="fa fa-edit"></i>
                            </button>
                            <button class="btn btn-danger btn-sm delete-btn" data-id="${row.id}" title="Delete">
                                <i class="fa fa-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
    $('#searchInput, #statusFilter, #typeFilter, #dateFilter').on('change keyup', function() {
        table.ajax.reload();
    });

    // New Movement button
    $('#newMovementBtn').on('click', function() {
        $('#movementForm')[0].reset();
        $('#movementId').val('');
        $('#movementModalLabel').html('<i class="fas fa-plus-circle mr-2"></i> New Stock Movement');
        $('input[name="movementType"][value="inbound"]').prop('checked', true);
        $('input[name="status"][value="pending"]').prop('checked', true);
        updateLocationFields();
        $('#movementModal').modal('show');
    });

    // Update location fields based on movement type
    function updateLocationFields() {
        var movementType = $('input[name="movementType"]:checked').val();
        if (movementType === 'inbound') {
            $('#fromLocationGroup').hide();
            $('#toLocationGroup').show();
            $('#fromLocation').prop('required', false).val('');
            $('#toLocation').prop('required', true);
        } else if (movementType === 'outbound') {
            $('#fromLocationGroup').show();
            $('#toLocationGroup').hide();
            $('#fromLocation').prop('required', true);
            $('#toLocation').prop('required', false).val('');
        } 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).val('');
        }
    }

    $('input[name="movementType"]').on('change', updateLocationFields);

    // Save Movement
    $('#movementForm').on('submit', function(e) {
        e.preventDefault();
        let payload = {
            id: $('#movementId').val(),
            reference: $('#reference').val(),
            sku_id: $('#sku').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: '{{ csrf_token() }}'
        };

        $.post('{{ url("/superadmin/skumovement/store") }}', payload, function(res) {
            $('#movementModal').modal('hide');
            $('#movementForm')[0].reset();
            $('#movementId').val('');
            // Clear filters
            $('#searchInput').val('');
            $('#statusFilter').val('');
            $('#typeFilter').val('');
            $('#dateFilter').val('');
            table.ajax.reload();
            Swal.fire('Success!', 'Movement saved successfully!', 'success');
        }).fail(function(xhr) {
            console.log(xhr.responseText);
            if (xhr.responseJSON) {
                // let errors = Object.values(xhr.responseJSON).flat().join('<br>');
                let msg = xhr.responseJSON.message ?? "Validation error";
                Swal.fire('Error', msg, 'error');
                Swal.fire('Validation Error', errors, 'error');
            } else {
                Swal.fire('Error!', 'Error saving record', 'error');
            }
        });
    });

    // Edit Movement
    $(document).on('click', '.edit-btn', function() {
        let id = $(this).data('id');

        $.get(`/superadmin/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 || ''); 
            $('input[name="movementType"][value="' + data.type + '"]').prop('checked', true);
            $('input[name="status"][value="' + data.status + '"]').prop('checked', true);
            $('#notes').val(data.notes);

            updateLocationFields(); // if you have dynamic location logic

            $('#movementModalLabel').html('<i class="fas fa-edit mr-2"></i> Edit Stock Movement');
            $('#movementModal').modal('show');

        });
    });

    // Reset modal on close
    $('#movementModal').on('hidden.bs.modal', function() {
        $('#movementForm')[0].reset();
        $('#movementId').val('');
        $('#movementModalLabel').html('<i class="fas fa-plus-circle mr-2"></i> New Stock Movement');
        $('input[name="movementType"][value="inbound"]').prop('checked', true);
        $('input[name="status"][value="pending"]').prop('checked', true);
        updateLocationFields();
    });

    // Delete Movement
    $(document).on('click', '.delete-btn', function() {
        let id = $(this).data('id');
        Swal.fire({
            title: 'Delete Movement?',
            text: "Are you sure you want to delete this stock movement?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, Delete!',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ url("/superadmin/skumovement") }}/' + id,
                    type: 'DELETE',
                    data: { _token: '{{ csrf_token() }}' },
                    success: function() {
                        table.ajax.reload();
                        Swal.fire('Deleted!', 'Movement deleted successfully.', 'success');
                    },
                    error: function(xhr) {
                        Swal.fire('Error!', 'Delete failed!', 'error');
                    }
                });
            }
        });
    });
});
</script>
@endsection
