@extends('backend.layouts.master')

@section('title', 'Edit Stock In')

@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">Edit Stock In</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('stockin.list') }}">Stock In</a></li>
                    <li class="breadcrumb-item active">Edit</li>
                </ol>
            </div>
        </div>
    </div>
</div>
@endsection

@section('admin-content')
<div class="container-fluid">
    <div class="row justify-content-center">
        <div class="col-12">
            <div class="card shadow-lg border-0">
                <div class="card-header bg-primary text-white">
                    <h3 class="card-title mb-0">
                        <i class="fas fa-edit mr-2"></i>Edit Stock In Entry
                    </h3>
                </div>

                <form action="{{ route('stockin.update', $stockIn->id) }}" method="POST" id="edit-stockin-form">
                    @csrf
                    @method('PUT')
                    
                    <div class="card-body">
                        <!-- Add Item Section -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle mr-2"></i>
                                    <strong>Add New Item:</strong> Select an accessory and unit to add items to your stock in entry.
                                </div>
                            </div>
                        </div>

                        <div class="row align-items-end mb-4">
                            <div class="col-md-5">
                                <div class="form-group">
                                    <label for="accessory_name" class="font-weight-bold">
                                        <i class="fas fa-cube mr-1"></i>Accessory Name
                                    </label>
                                    <select name="accessory_name" id="accessory_name"
                                        class="form-control select2 @error('accessory_name') is-invalid @enderror">
                                        <option value="">Select Accessory</option>
                                        @foreach (App\Models\Accesories::all() as $accessory)
                                            <option value="{{ $accessory->name }}" 
                                                    data-id="{{ $accessory->id }}" 
                                                    data-unit="{{ $accessory->unit }}">
                                                {{ $accessory->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('accessory_name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="unit" class="font-weight-bold">
                                        <i class="fas fa-balance-scale mr-1"></i>Unit
                                    </label>
                                    <input type="text" name="unit" id="unit"
                                        class="form-control @error('unit') is-invalid @enderror"
                                        placeholder="Unit will be auto-filled" readonly>
                                    @error('unit')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-2">
                                <div class="form-group">
                                    <button type="button" id="append-fields" class="btn btn-success btn-block">
                                        <i class="fas fa-plus mr-1"></i>Add Item
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Items Table -->
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover" id="items-table">
                                <thead class="thead-dark">
                                    <tr>
                                        <th width="20%">Accessory Name</th>
                                        <th width="10%">Unit</th>
                                        <th width="12%">Kg</th>
                                        <th width="12%">Quantity</th>
                                        <th width="12%">Unit Price</th>
                                        <th width="12%">Total Price</th>
                                        <th width="10%">Action</th>
                                    </tr>
                                </thead>
                                <tbody id="items-tbody">
                                    @if ($stockIn && $stockIn->stock_in_details)
                                        @foreach ($stockIn->stock_in_details as $index => $details)
                                            <tr class="dynamic-row" id="row-{{ $index }}">
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <i class="fas fa-cube text-primary mr-2"></i>
                                                        <span>{{ $details->accessories->name ?? 'N/A' }}</span>
                                                    </div>
                                                    <input type="hidden" name="accessory_id[]" value="{{ $details->accessories_id }}">
                                                    <input type="hidden" name="detail_id[]" value="{{ $details->id }}">
                                                </td>
                                                <td>
                                                    <input type="text" class="form-control form-control-sm" 
                                                           value="{{ $details->accessories->unit ?? 'N/A' }}" readonly>
                                                </td>
                                                <td>
                                                    <input type="number" name="kg[]" 
                                                           class="form-control form-control-sm kg-input text-right" 
                                                           value="{{ $details->kg }}" step="0.01" min="0">
                                                </td>
                                                <td>
                                                    <input type="number" name="in_quantity[]" 
                                                           class="form-control form-control-sm quantity-input text-right" 
                                                           value="{{ $details->in_quantity }}" min="0" required>
                                                </td>
                                                <td>
                                                    <input type="number" name="price[]" 
                                                           class="form-control form-control-sm price-input text-right" 
                                                           value="{{ number_format($details->price, 2, '.', '') }}" 
                                                           step="0.01" min="0" required>
                                                </td>
                                                <td>
                                                    <input type="number" name="total_price[]" 
                                                           class="form-control form-control-sm total-price-input text-right" 
                                                           value="{{ $details->total_price }}" readonly>
                                                </td>
                                                <td class="text-center">
                                                    <button type="button" class="btn btn-danger btn-sm remove-row" 
                                                            data-row-id="row-{{ $index }}">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        @endforeach
                                    @endif
                                </tbody>
                                <tfoot class="thead-light">
                                    <tr class="font-weight-bold">
                                        <td colspan="2" class="text-right">Sub-Total:</td>
                                        <td class="text-right">
                                            <span class="totalKg">0.00</span>
                                            <input type="hidden" name="totalKg" value="0">
                                        </td>
                                        <td class="text-right">
                                            <span class="ttlqty">0</span>
                                            <input type="hidden" name="totalQty" value="0">
                                        </td>
                                        <td class="text-right">
                                            <span class="ttlunitprice">0.00</span>
                                            <input type="hidden" name="ttlunitprice" value="0">
                                        </td>
                                        <td class="text-right">
                                            <span class="grandtotal">0.00</span>
                                            <input type="hidden" name="grandtotal" value="0">
                                        </td>
                                        <td></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>

                        <!-- Summary Section -->
                        <div class="row mt-4">
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header bg-light">
                                        <h5 class="mb-0">
                                            <i class="fas fa-sticky-note mr-2"></i>Notes
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <textarea name="narration" class="form-control" rows="8" 
                                                  placeholder="Enter any additional notes here...">{{ $stockIn->narration ?? '' }}</textarea>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header bg-light">
                                        <h5 class="mb-0">
                                            <i class="fas fa-calculator mr-2"></i>Calculation Summary
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <table class="table table-sm calculation-table">
                                            <tbody>
                                                <tr>
                                                    <td class="text-right font-weight-bold">Total Amount:</td>
                                                    <td class="text-right">
                                                        <span class="grandsubTotaltotal">0.00</span>
                                                        <input type="hidden" name="grandsubTotaltotal" value="0">
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="text-right font-weight-bold">Previous Due:</td>
                                                    <td class="text-right">
                                                        <span id="previous_due">{{ $stockIn->previous_due ?? '0.00' }}</span>
                                                        <input type="hidden" name="previouse_due_amount" value="{{ $stockIn->previous_due ?? 0 }}">
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="text-right font-weight-bold">Labor Bill (+):</td>
                                                    <td>
                                                        <input type="number" id="labor_bill" name="labor_bill" 
                                                               class="form-control form-control-sm text-right" 
                                                               value="{{ $stockIn->labor_bill ?? '' }}"
                                                               placeholder="0.00" step="0.01" min="0">
                                                    </td>
                                                </tr>
                                                <tr class="table-info">
                                                    <td class="text-right font-weight-bold">Net Total:</td>
                                                    <td class="text-right font-weight-bold">
                                                        <span class="ngrandTotal">0.00</span>
                                                        <input type="hidden" name="ngrandTotal" value="0">
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="text-right font-weight-bold">Advance Account:</td>
                                                    <td>
                                                        <select name="advance_ledger_id" class="form-control form-control-sm select2">
                                                            <x-account :setAccounts="$accounts" />
                                                        </select>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="text-right font-weight-bold">Advance Amount:</td>
                                                    <td>
                                                        <input type="number" id="advance" name="advance" 
                                                               class="form-control form-control-sm text-right" 
                                                               value="{{ $stockIn->advance ?? '' }}"
                                                               placeholder="0.00" step="0.01" min="0">
                                                    </td>
                                                </tr>
                                                <tr class="table-warning">
                                                    <td class="text-right font-weight-bold">Supplier Due:</td>
                                                    <td class="text-right font-weight-bold">
                                                        <span class="finalDue">0.00</span>
                                                        <input type="hidden" name="finalDue" value="0">
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card-footer bg-light">
                        <div class="row">
                            <div class="col-md-6">
                                <button type="submit" class="btn btn-primary btn-lg">
                                    <i class="fas fa-save mr-2"></i>Update Stock In
                                </button>
                            </div>
                            <div class="col-md-6 text-right">
                                <a href="{{ route('stockin.list') }}" class="btn btn-secondary btn-lg">
                                    <i class="fas fa-arrow-left mr-2"></i>Back to List
                                </a>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<style>
    .card {
        border-radius: 10px;
    }
    
    .card-header {
        border-radius: 10px 10px 0 0 !important;
    }
    
    .table th {
        background-color: #343a40;
        color: white;
        border-color: #454d55;
    }
    
    .table-hover tbody tr:hover {
        background-color: #f8f9fa;
    }
    
    .dynamic-row {
        transition: all 0.3s ease;
    }
    
    .calculation-table td {
        padding: 8px 12px;
        border-top: 1px solid #dee2e6;
    }
    
    .btn-success {
        background-color: #28a745;
        border-color: #28a745;
    }
    
    .btn-success:hover {
        background-color: #218838;
        border-color: #1e7e34;
    }
    
    .alert-info {
        background-color: #d1ecf1;
        border-color: #bee5eb;
        color: #0c5460;
    }
    
    .form-control:focus {
        border-color: #80bdff;
        box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
    }
    
    .readonly-input {
        background-color: #f8f9fa;
    }
    
    .shadow-lg {
        box-shadow: 0 1rem 3rem rgba(0, 0, 0, 0.175) !important;
    }
</style>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    let rowCount = {{ $stockIn->stock_in_details->count() ?? 0 }};

    // Initialize Select2 if available
    if ($.fn.select2) {
        $('.select2').select2({
            theme: 'bootstrap4',
            width: '100%'
        });
    }

    // Accessory selection handler
    $('#accessory_name').on('change', function() {
        const accessoryName = $(this).val();
        const unit = $(this).find(':selected').data('unit');
        
        if (accessoryName && unit) {
            $('#unit').val(unit);
        } else {
            $('#unit').val('');
        }
    });

    // Add new row
    $('#append-fields').on('click', function() {
        const accessoryName = $('#accessory_name').val();
        const accessoryId = $('#accessory_name').find(':selected').data('id');
        const unit = $('#unit').val();

        if (!accessoryName || !unit) {
            Swal.fire({
                icon: 'warning',
                title: 'Missing Information',
                text: 'Please select an accessory and unit before adding an item.',
            });
            return;
        }

        rowCount++;
        const newRow = `
            <tr class="dynamic-row" id="row-${rowCount}">
                <td>
                    <div class="d-flex align-items-center">
                        <i class="fas fa-cube text-primary mr-2"></i>
                        <span>${accessoryName}</span>
                    </div>
                    <input type="hidden" name="accessory_id[]" value="${accessoryId}">
                </td>
                <td>
                    <input type="text" class="form-control form-control-sm readonly-input" 
                           value="${unit}" readonly>
                </td>
                <td>
                    <input type="number" name="kg[]" 
                           class="form-control form-control-sm kg-input text-right" 
                           step="0.01" min="0" placeholder="0.00">
                </td>
                <td>
                    <input type="number" name="in_quantity[]" 
                           class="form-control form-control-sm quantity-input text-right" 
                           min="0" placeholder="0" >
                </td>
                <td>
                    <input type="number" name="price[]" 
                           class="form-control form-control-sm price-input text-right" 
                           step="0.01" min="0" placeholder="0.00" >
                </td>
                <td>
                    <input type="number" name="total_price[]" 
                           class="form-control form-control-sm total-price-input text-right readonly-input" 
                           readonly>
                </td>
                <td class="text-center">
                    <button type="button" class="btn btn-danger btn-sm remove-row" 
                            data-row-id="row-${rowCount}">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            </tr>
        `;

        $('#items-tbody').append(newRow);
        
        // Clear form fields
        $('#accessory_name').val('').trigger('change');
        $('#unit').val('');
        
        // Focus on the first input of the new row
        $(`#row-${rowCount} .kg-input`).focus();
        
        calculateTotals();
    });

    // Calculate row totals on input
    $('#items-tbody').on('input', '.price-input, .quantity-input, .kg-input', function() {
        const $row = $(this).closest('tr');
        const price = parseFloat($row.find('.price-input').val()) || 0;
        const quantity = parseFloat($row.find('.quantity-input').val()) || 0;
        const kg = parseFloat($row.find('.kg-input').val()) || 0;

        let total = 0;
        if (kg > 0) {
            total = kg * price;
        } else if (quantity > 0) {
            total = quantity * price;
        }

        $row.find('.total-price-input').val(total.toFixed(2));
        calculateTotals();
    });

    // Remove row
    $('#items-tbody').on('click', '.remove-row', function() {
        const rowId = $(this).data('row-id');
        $(`#${rowId}`).fadeOut(300, function() {
            $(this).remove();
            calculateTotals();
        });
    });

    // Labor bill and advance calculations
    $('#labor_bill, #advance').on('input', function() {
        calculateTotals();
    });

    // Main calculation function
    function calculateTotals() {
        let subtotal = 0;
        let totalQuantity = 0;
        let totalKg = 0;
        let totalUnitPrice = 0;

        $('#items-tbody tr').each(function() {
            const rowTotal = parseFloat($(this).find('.total-price-input').val()) || 0;
            const quantity = parseFloat($(this).find('.quantity-input').val()) || 0;
            const kg = parseFloat($(this).find('.kg-input').val()) || 0;
            const price = parseFloat($(this).find('.price-input').val()) || 0;

            subtotal += rowTotal;
            totalQuantity += quantity;
            totalKg += kg;
            totalUnitPrice += price;
        });

        const previousDue = parseFloat($('#previous_due').text()) || 0;
        const laborBill = parseFloat($('#labor_bill').val()) || 0;
        const advance = parseFloat($('#advance').val()) || 0;

        const grandTotal = subtotal;
        const netTotal = grandTotal + previousDue + laborBill;
        const finalDue = netTotal - advance;

        // Update all display elements
        $('.grandtotal').text(grandTotal.toFixed(2));
        $('input[name="grandtotal"]').val(grandTotal.toFixed(2));
        
        $('.grandsubTotaltotal').text(grandTotal.toFixed(2));
        $('input[name="grandsubTotaltotal"]').val(grandTotal.toFixed(2));
        
        $('.ttlqty').text(totalQuantity);
        $('input[name="totalQty"]').val(totalQuantity);
        
        $('.totalKg').text(totalKg.toFixed(2));
        $('input[name="totalKg"]').val(totalKg.toFixed(2));
        
        $('.ttlunitprice').text(totalUnitPrice.toFixed(2));
        $('input[name="ttlunitprice"]').val(totalUnitPrice.toFixed(2));
        
        $('.ngrandTotal').text(netTotal.toFixed(2));
        $('input[name="ngrandTotal"]').val(netTotal.toFixed(2));
        
        $('.finalDue').text(finalDue.toFixed(2));
        $('input[name="finalDue"]').val(finalDue.toFixed(2));
    }

    // Initialize calculations on page load
    calculateTotals();

    // Form submission
    $('#edit-stockin-form').on('submit', function(e) {
        const hasItems = $('#items-tbody tr').length > 0;
        if (!hasItems) {
            e.preventDefault();
            Swal.fire({
                icon: 'error',
                title: 'No Items',
                text: 'Please add at least one item to the stock in entry.',
            });
            return false;
        }
    });
});

// Global functions
function updatePreviousDue(amount) {
    $('#previous_due').text(parseFloat(amount).toFixed(2));
    $('input[name="previouse_due_amount"]').val(amount);
    calculateTotals();
}

function clearAll() {
    $('#items-tbody').empty();
    $('#labor_bill').val('');
    $('#advance').val('');
    $('textarea[name="narration"]').val('');
    calculateTotals();
}
</script>
@endsection