@extends('backend.layouts.master')

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

@section('navbar-content')
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Create Stock Out</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="{{ route('home') }}">Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('stockOut.list') }}">Stock Out</a></li>
                        <li class="breadcrumb-item active">Create</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('admin-content')
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card card-primary">
                <div class="card-header">
                    <h3 class="card-title">New Stock Out</h3>
                </div>

                <form action="{{ route('stockOut.store') }}" method="POST" id="create-stockout-form">
                    @csrf
                    <div class="card-body">
                        {{-- Accessory Selection Section --}}
                        <div class="row mb-4">
                            <div class="col-md-8">
                                <div class="form-group mb-0">
                                    <label for="accessory_name">Select Accessory</label>
                                    <select name="accessory_name" id="accessory_name"
                                        class="form-control @error('accessory_name') is-invalid @enderror">
                                        <option value="">Choose Accessory to Add</option>

                                        @if (auth()->user()->role_id > 1)
                                            @foreach (App\Models\Accesories::where('branch_id', auth()->user()->branch_id)->get() as $accessory)
                                                @php
                                                    $stock = \App\Models\stockinsummary::where(
                                                        'product_id',
                                                        $accessory->id,
                                                    )->sum('quantity');
                                                    $stockKg = \App\Models\stockinsummary::where(
                                                        'product_id',
                                                        $accessory->id,
                                                    )->sum('kg');
                                                @endphp
                                                <option value="{{ $accessory->name }}" data-id="{{ $accessory->id }}"
                                                    data-unit="{{ $accessory->unit }}" data-stock="{{ $stock }}" data-stock-kg="{{ $stockKg }}">
                                                    {{ $accessory->name }} (Available: Qty:{{ $stock }}, Kg:{{ $stockKg }}
                                                    {{ $accessory->unit }})
                                                </option>
                                            @endforeach
                                        @else
                                            @foreach (App\Models\Accesories::all() as $accessory)
                                                @php
                                                    $stock = \App\Models\stockinsummary::where(
                                                        'product_id',
                                                        $accessory->id,
                                                    )->sum('quantity');
                                                    $stockKg = \App\Models\stockinsummary::where(
                                                        'product_id',
                                                        $accessory->id,
                                                    )->sum('kg');
                                                @endphp
                                                <option value="{{ $accessory->name }}" data-id="{{ $accessory->id }}"
                                                    data-unit="{{ $accessory->unit }}" data-stock="{{ $stock }}" data-stock-kg="{{ $stockKg }}">
                                                    {{ $accessory->name }} (Available: Qty:{{ $stock }}, Kg:{{ $stockKg }}
                                                    {{ $accessory->unit }})
                                                </option>
                                            @endforeach
                                        @endif
                                    </select>
                                    @error('accessory_name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-4 d-flex align-items-end">
                                <div class="form-group mb-0 w-100">
                                    <label class="invisible d-block">Add Item</label>
                                    <button type="button" id="add-item" class="btn btn-success w-50">
                                        <i class="fa fa-plus"></i> Add Item
                                    </button>
                                </div>
                            </div>
                        </div>

                        {{-- Items Table --}}
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped" id="items-table">
                                <thead class="bg-light">
                                    <tr>
                                        <th width="20%">Accessory Name</th>
                                        <th width="8%">Unit</th>
                                  
                                        <th width="12%">Out Kg</th>
                                        <th width="12%">Out Quantity</th>
                                        <th width="23%">Description</th>
                                        <th width="10%">Action</th>
                                    </tr>
                                </thead>
                                <tbody id="items-tbody">
                                    <tr id="no-items-row">
                                        <td colspan="7" class="text-center text-muted">No items added yet. Select an
                                            accessory above to add items.</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        {{-- Hidden fields for pricing (keeping them for backend compatibility) --}}
                        <div id="hidden-fields" style="display: none;"></div>
                    </div>

                    <div class="card-footer">
                        <button type="submit" class="btn btn-primary" id="submit-btn" disabled>
                            <i class="fa fa-save"></i> Create Stock Out
                        </button>
                        <a href="{{ route('stockOut.list') }}" class="btn btn-secondary">
                            <i class="fa fa-arrow-left"></i> Back to List
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        let itemCount = 0;
        let addedItems = new Set(); // Track added items to prevent duplicates

        // Add item to table
        $('#add-item').on('click', function() {
            let selected = $('#accessory_name').find(':selected');
            let accessoryName = selected.val();
            let accessoryId = selected.data('id');
            let unit = selected.data('unit');
            let stock = selected.data('stock');
            let stockKg = selected.data('stock-kg');

            if (!accessoryName) {
                alert('Please select an accessory first.');
                return;
            }

            if (addedItems.has(accessoryId)) {
                alert('This accessory is already added to the list.');
                return;
            }

            if (stock <= 0 && stockKg <= 0) {
                alert('No stock available for this accessory.');
                return;
            }

            // Remove "no items" row if it exists
            $('#no-items-row').remove();

            itemCount++;
            addedItems.add(accessoryId);

            let newRow = `
                <tr id="item-row-${itemCount}" data-item-id="${accessoryId}">
                    <td>
                        <strong>${accessoryName}</strong>
                        <input type="hidden" name="accessory_id[]" value="${accessoryId}">
                    </td>
                    <td>
                        <span class="badge badge-secondary">${unit}</span>
                    </td>
                 
                    <td>
                        <input type="number" 
                               name="kg[]" 
                               class="form-control kg-input" 
                               placeholder="Enter kg" 
                               min="0" 
                               step="0.01"
                               max="${stockKg}" 
                               data-max-kg="${stockKg}">
                        <small class="text-muted">Max: ${stockKg} kg</small>
                    </td>
                    <td>
                        <input type="number" 
                               name="in_quantity[]" 
                               class="form-control quantity-input" 
                               placeholder="Enter quantity" 
                               min="0" 
                               max="${stock}" 
                               data-max-qty="${stock}">
                        <small class="text-muted">Max: ${stock}</small>
                    </td>
                    <td>
                        <textarea name="description[]" 
                                  class="form-control" 
                                  rows="2" 
                                  placeholder="Enter description (optional)"></textarea>
                    </td>
                    <td>
                        <button type="button" class="btn btn-danger btn-sm remove-item" data-row-id="item-row-${itemCount}" data-item-id="${accessoryId}">
                            <i class="fa fa-trash"></i>
                        </button>
                    </td>
                </tr>`;

            $('#items-tbody').append(newRow);

            // Add hidden fields for pricing (maintaining backend compatibility)
            $('#hidden-fields').append(`
                <input type="hidden" name="price[]" value="0" id="price-${itemCount}">
                <input type="hidden" name="total_price[]" value="0" id="total-price-${itemCount}">
            `);

            // Reset selection
            $('#accessory_name').val('');
            updateSubmitButton();
        });

        // Remove item from table
        $(document).on('click', '.remove-item', function() {
            const rowId = $(this).data('row-id');
            const itemId = $(this).data('item-id');

            $('#' + rowId).remove();
            addedItems.delete(itemId);

            // Show "no items" row if table is empty
            if ($('#items-tbody tr').length === 0) {
                $('#items-tbody').append(`
                    <tr id="no-items-row">
                        <td colspan="7" class="text-center text-muted">No items added yet. Select an accessory above to add items.</td>
                    </tr>
                `);
            }

            updateSubmitButton();
        });

        // Validate quantity input
        $(document).on('input', '.quantity-input', function() {
            const max = parseFloat($(this).attr('max'));
            const val = parseFloat($(this).val());

            if (val > max) {
                $(this).addClass('is-invalid');
                $(this).siblings('.invalid-feedback').remove();
                $(this).after('<div class="invalid-feedback">Quantity exceeds available stock!</div>');
            } else if (val < 0) {
                $(this).addClass('is-invalid');
                $(this).siblings('.invalid-feedback').remove();
                $(this).after('<div class="invalid-feedback">Quantity cannot be negative!</div>');
            } else {
                $(this).removeClass('is-invalid');
                $(this).siblings('.invalid-feedback').remove();
            }

            updateSubmitButton();
        });

        // Validate kg input
        $(document).on('input', '.kg-input', function() {
            const max = parseFloat($(this).attr('max'));
            const val = parseFloat($(this).val());

            if (val > max) {
                $(this).addClass('is-invalid');
                $(this).siblings('.invalid-feedback').remove();
                $(this).after('<div class="invalid-feedback">Kg exceeds available stock!</div>');
            } else if (val < 0) {
                $(this).addClass('is-invalid');
                $(this).siblings('.invalid-feedback').remove();
                $(this).after('<div class="invalid-feedback">Kg cannot be negative!</div>');
            } else {
                $(this).removeClass('is-invalid');
                $(this).siblings('.invalid-feedback').remove();
            }

            updateSubmitButton();
        });

        // Update submit button state
        function updateSubmitButton() {
            const hasItems = $('#items-tbody tr:not(#no-items-row)').length > 0;
            const hasInvalidInputs = $('.quantity-input.is-invalid, .kg-input.is-invalid').length > 0;
            
            // Check if at least one row has either quantity or kg filled
            let hasValidEntries = false;
            $('#items-tbody tr:not(#no-items-row)').each(function() {
                const qtyVal = parseFloat($(this).find('.quantity-input').val()) || 0;
                const kgVal = parseFloat($(this).find('.kg-input').val()) || 0;
                
                if (qtyVal > 0 || kgVal > 0) {
                    hasValidEntries = true;
                }
            });

            if (hasItems && !hasInvalidInputs && hasValidEntries) {
                $('#submit-btn').prop('disabled', false);
            } else {
                $('#submit-btn').prop('disabled', true);
            }
        }

        // Form validation before submit
        $('#create-stockout-form').on('submit', function(e) {
            const itemsCount = $('#items-tbody tr:not(#no-items-row)').length;

            if (itemsCount === 0) {
                e.preventDefault();
                alert('Please add at least one item before submitting.');
                return false;
            }

            // Final validation - ensure at least one row has quantity or kg
            let hasValidEntries = false;
            let hasErrors = false;

            $('#items-tbody tr:not(#no-items-row)').each(function() {
                const qtyInput = $(this).find('.quantity-input');
                const kgInput = $(this).find('.kg-input');
                
                const qtyVal = parseFloat(qtyInput.val()) || 0;
                const kgVal = parseFloat(kgInput.val()) || 0;
                const maxQty = parseFloat(qtyInput.attr('max'));
                const maxKg = parseFloat(kgInput.attr('max'));

                // Check if at least quantity or kg is filled
                if (qtyVal > 0 || kgVal > 0) {
                    hasValidEntries = true;
                }

                // Validate ranges
                if (qtyVal < 0 || qtyVal > maxQty || kgVal < 0 || kgVal > maxKg) {
                    hasErrors = true;
                }
            });

            if (!hasValidEntries) {
                e.preventDefault();
                alert('Please enter at least quantity or kg for each item.');
                return false;
            }

            if (hasErrors) {
                e.preventDefault();
                alert('Please check all quantity and kg fields for valid values.');
                return false;
            }
        });

        // Initial state
        updateSubmitButton();
    });
</script>

<style>
    .table th {
        background-color: #f8f9fa;
        font-weight: 600;
    }

    .quantity-input:invalid,
    .kg-input:invalid {
        border-color: #dc3545;
    }

    .badge {
        font-size: 0.875em;
    }

    #items-table {
        margin-top: 1rem;
    }

    .card-body {
        padding: 1.5rem;
    }

    textarea.form-control {
        resize: vertical;
        min-height: 60px;
    }

    .btn-sm {
        padding: 0.25rem 0.5rem;
    }

    .kg-input,
    .quantity-input {
        font-size: 0.9rem;
    }

    .badge.d-block {
        margin-bottom: 2px;
    }

    .text-center .badge {
        display: inline-block;
        min-width: 60px;
    }
</style>

@push('scripts')
@endpush