@extends('layouts.app')

@section('title', 'Create Stock Transfer')

@push('plugin-style')
<style>
    .item-row {
        background-color: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 15px;
    }
    .remove-item {
        color: #dc3545;
        cursor: pointer;
    }
    .remove-item:hover {
        color: #c82333;
    }
</style>
@endpush

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">Create Stock Transfer</h4>
                    <p class="card-subtitle">Transfer items between warehouse bins</p>
                </div>
                <div class="card-body">
                    <form action="{{ route('stock-transfers.store') }}" method="POST" id="stock-transfer-form">
                        @csrf

                        <div class="row g-3">
                            <!-- Transfer Details -->
                            <div class="col-12">
                                <h6 class="card-title">Transfer Details</h6>
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">From Bin <span class="text-danger">*</span></label>
                                <select name="from_bin_id" class="form-select @error('from_bin_id') is-invalid @enderror" required>
                                    <option value="">Select Source Bin</option>
                                    @foreach($bins as $bin)
                                        <option value="{{ $bin->id }}" {{ old('from_bin_id') == $bin->id ? 'selected' : '' }}>
                                            {{ $bin->code }} - {{ $bin->warehouse->name }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('from_bin_id')<div class="invalid-feedback">{{ $message }}</div>@enderror
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">To Bin <span class="text-danger">*</span></label>
                                <select name="to_bin_id" class="form-select @error('to_bin_id') is-invalid @enderror" required>
                                    <option value="">Select Destination Bin</option>
                                    @foreach($bins as $bin)
                                        <option value="{{ $bin->id }}" {{ old('to_bin_id') == $bin->id ? 'selected' : '' }}>
                                            {{ $bin->code }} - {{ $bin->warehouse->name }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('to_bin_id')<div class="invalid-feedback">{{ $message }}</div>@enderror
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Transfer Date <span class="text-danger">*</span></label>
                                <input type="date" name="transfer_date" class="form-control @error('transfer_date') is-invalid @enderror"
                                       value="{{ old('transfer_date', date('Y-m-d')) }}" required>
                                @error('transfer_date')<div class="invalid-feedback">{{ $message }}</div>@enderror
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Status <span class="text-danger">*</span></label>
                                <select name="status" class="form-select @error('status') is-invalid @enderror" required>
                                    <option value="draft" {{ old('status') == 'draft' ? 'selected' : '' }}>Draft</option>
                                    <option value="pending" {{ old('status') == 'pending' ? 'selected' : '' }}>Pending</option>
                                    <option value="approved" {{ old('status') == 'approved' ? 'selected' : '' }}>Approved</option>
                                    <option value="completed" {{ old('status') == 'completed' ? 'selected' : '' }}>Completed</option>
                                    <option value="cancelled" {{ old('status') == 'cancelled' ? 'selected' : '' }}>Cancelled</option>
                                </select>
                                @error('status')<div class="invalid-feedback">{{ $message }}</div>@enderror
                            </div>

                            <div class="col-12">
                                <label class="form-label">Notes</label>
                                <textarea name="notes" class="form-control @error('notes') is-invalid @enderror"
                                          rows="3" maxlength="500">{{ old('notes') }}</textarea>
                                @error('notes')<div class="invalid-feedback">{{ $message }}</div>@enderror
                            </div>

                            <!-- Items Section -->
                            <div class="col-12">
                                <h6 class="card-title">Transfer Items</h6>
                                <div id="items-container">
                                    <!-- Items will be added here dynamically -->
                                </div>
                                <button type="button" class="btn btn-outline-primary btn-sm" id="add-item">
                                    <i class="fas fa-plus"></i> Add Item
                                </button>
                            </div>

                            <!-- Submit Buttons -->
                            <div class="col-12">
                                <hr>
                                <div class="d-flex justify-content-end gap-2">
                                    <a href="{{ route('stock-transfers.index') }}" class="btn btn-secondary">
                                        <i class="fas fa-times"></i> Cancel
                                    </a>
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save"></i> Create Transfer
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('plugin-scripts')
@include('common.item-select-script')
<script>
$(document).ready(function() {
    let itemCount = 0;

    // Add item row
    $('#add-item').click(function() {
        addItemRow();
    });

    function addItemRow() {
        itemCount++;
        const itemRow = `
            <div class="item-row" id="item-row-${itemCount}">
                <div class="row g-2">
                    <div class="col-md-4">
                        <label class="form-label">Item <span class="text-danger">*</span></label>
                        <select name="items[${itemCount}][item_id]" class="form-select item-select" required>
                            <option value="">Select Item</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Quantity <span class="text-danger">*</span></label>
                        <input type="number" name="items[${itemCount}][qty_transferred]" class="form-control"
                               step="0.01" min="0.01" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Lot Number</label>
                        <input type="text" name="items[${itemCount}][lot_no]" class="form-control" maxlength="100">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <div>
                            <button type="button" class="btn btn-outline-danger btn-sm remove-item"
                                    onclick="removeItem(${itemCount})">
                                <i class="fas fa-trash"></i> Remove
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        $('#items-container').append(itemRow);
    }

    // Remove item row
    window.removeItem = function(itemCount) {
        $(`#item-row-${itemCount}`).remove();
    };

    // Form validation
    $('#stock-transfer-form').submit(function(e) {
        const fromBin = $('select[name="from_bin_id"]').val();
        const toBin = $('select[name="to_bin_id"]').val();

        if (fromBin === toBin) {
            e.preventDefault();
            alert('Source and destination bins cannot be the same.');
            return false;
        }

        const itemRows = $('.item-row');
        if (itemRows.length === 0) {
            e.preventDefault();
            alert('Please add at least one item to transfer.');
            return false;
        }

        // Check if all required fields are filled
        let isValid = true;
        itemRows.each(function() {
            const itemId = $(this).find('select[name*="[item_id]"]').val();
            const qty = $(this).find('input[name*="[qty_transferred]"]').val();

            if (!itemId || !qty) {
                isValid = false;
            }
        });

        if (!isValid) {
            e.preventDefault();
            alert('Please fill in all required fields for all items.');
            return false;
        }
    });

    // Add initial item row
    addItemRow();
});
</script>
@endpush
