@extends('backend.layouts.master')

@section('title', 'Create Stock In')
<style>
        .table-container {
            margin: 20px 0;
        }
        .form-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .calculation-panel {
            background: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
        }
        .readonly-input {
            background-color: #f8f9fa;
        }
        .text-right {
            text-align: right;
        }
        
        /* Image preview styles */
        .image-preview-container {
            position: relative;
            display: inline-block;
            margin: 10px 0;
        }
        .image-preview {
            max-width: 200px;
            max-height: 200px;
            border: 2px dashed #ddd;
            border-radius: 8px;
            padding: 10px;
            display: none;
        }
        .image-preview img {
            max-width: 100%;
            max-height: 100%;
            border-radius: 4px;
        }
        .image-remove-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 50%;
            width: 25px;
            height: 25px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
        }
        .image-remove-btn:hover {
            background: #c82333;
        }
        .file-input-wrapper {
            position: relative;
            overflow: hidden;
            display: inline-block;
            width: 100%;
        }
        .file-input-wrapper input[type=file] {
            position: absolute;
            left: -9999px;
        }
        .file-input-label {
            display: block;
            padding: 10px 15px;
            cursor: pointer;
            background: #f8f9fa;
            border: 2px dashed #ddd;
            border-radius: 8px;
            text-align: center;
            transition: all 0.3s ease;
        }
        .file-input-label:hover {
            background: #e9ecef;
            border-color: #007bff;
        }
        .file-input-label i {
            font-size: 24px;
            color: #6c757d;
            margin-bottom: 5px;
        }
        .file-name {
            margin-top: 5px;
            font-size: 12px;
            color: #6c757d;
        }
</style>

<style>
        .table-container {
            margin: 20px 0;
        }
        .form-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .calculation-panel {
            background: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
        }
        .readonly-input {
            background-color: #f8f9fa;
        }
        .text-right {
            text-align: right;
        }
        
        /* Image preview styles */
        .image-preview-container {
            position: relative;
            display: inline-block;
            margin: 10px 0;
        }
        .image-preview {
            max-width: 200px;
            max-height: 200px;
            border: 2px dashed #ddd;
            border-radius: 8px;
            padding: 10px;
            display: none;
        }
        .image-preview img {
            max-width: 100%;
            max-height: 100%;
            border-radius: 4px;
        }
        .image-remove-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 50%;
            width: 25px;
            height: 25px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
        }
        .image-remove-btn:hover {
            background: #c82333;
        }
        .file-input-wrapper {
            position: relative;
            overflow: hidden;
            display: inline-block;
            width: 100%;
        }
        .file-input-wrapper input[type=file] {
            position: absolute;
            left: -9999px;
        }
        .file-input-label {
            display: block;
            padding: 10px 15px;
            cursor: pointer;
            background: #f8f9fa;
            border: 2px dashed #ddd;
            border-radius: 8px;
            text-align: center;
            transition: all 0.3s ease;
        }
        .file-input-label:hover {
            background: #e9ecef;
            border-color: #007bff;
        }
        .file-input-label i {
            font-size: 24px;
            color: #6c757d;
            margin-bottom: 5px;
        }
        .file-name-supplier {
            margin-top: 5px;
            font-size: 12px;
            color: #6c757d;
        }
</style>

@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 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">Create</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('admin-content')
    <div class="row justify-content-center">
        <div class="col-md-11">
            <div class="card card-primary">
                <div class="card-header">
                    <h3 class="card-title">New Stock In</h3>
                </div>
                <form action="{{ route('stockin.store') }}" method="POST" id="create-stockin-form" enctype="multipart/form-data">
                    @csrf
                    <div class="card-body">
                        <div class="row">

                            <div class="col-md-12 mb-3">
                                <label for="ledger_id">Ledger * :
                                    <button type="button" class="btn btn-sm btn-primary ml-2" data-toggle="modal"
                                        data-target="#addSupplierModal">
                                        +
                                    </button>
                                </label>
                                <select class="form-control select2 supid" name="ledger_id" id="ledger_id">
                                    <option selected disabled value="">--Select Ledger--</option>
                                    <x-account :setAccounts="$ledgers" />
                                </select>
                                @error('ledger_id')
                                    <span class=" error text-red text-bold">{{ $message }}</span>
                                @enderror
                            </div>
                          <div class="col-md-12 mb-3">
                                <label for="validationCustom01">Branch Name * :

                                  
                                </label>
                                <select class="form-control select2" name="branch_id">
                                    <option selected disabled value="">--Select--</option>
                                   @if(auth()->user()->role_id > 1)
                                    @foreach ($branchs as $key => $value)
                                        <option value="{{ $value->id }}" {{auth()->user()->branch_id == $value->id ? 'selected' :''}}>{{ $value->name }}</option>
                                    @endforeach
                                    @else 

                                   @foreach ($branchs as $key => $value)
                                        <option value="{{ $value->id }}">{{ $value->name }}</option>
                                    @endforeach
                                    @endif
                                </select>
                                @error('name')
                                    <span class=" error text-red text-bold">{{ $message }}</span>
                                @enderror
                            </div>
                            {{-- Accessory Name Field --}}
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="accessory_name">Accessory Name</label>
                                    <select name="accessory_name" id="accessory_name"
                                        class="form-control @error('accessory_name') is-invalid @enderror" >
                                        <option value="">Select Accessory</option>
                                        @if(auth()->user()->role_id > 1)
                                        @foreach (App\Models\Accesories::where('branch_id', auth()->user()->branch_id)->get() as $accessory)
                                            <option value="{{ $accessory->name }}" data-id="{{ $accessory->id }}"
                                                data-unit="{{ $accessory->unit }}">
                                                {{ $accessory->name }}
                                            </option>
                                        @endforeach
                                        @else 
                                       @foreach (App\Models\Accesories::all() as $accessory)
                                            <option value="{{ $accessory->name }}" data-id="{{ $accessory->id }}"
                                                data-unit="{{ $accessory->unit }}">
                                                {{ $accessory->name }}
                                            </option>
                                        @endforeach

                                        @endif
                                    </select>
                                    @error('accessory_name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            {{-- Unit Field --}}
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="unit">Unit</label>
                                    <input type="text" name="unit" id="unit"
                                        class="form-control @error('unit') is-invalid @enderror" value="{{ old('unit') }}"
                                        placeholder="Unit will be auto-filled" readonly required>
                                    @error('unit')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            {{-- Append Button (with Plus Icon) --}}
                            <div class="col-md-2 d-flex align-items-end mb-3 ">
                                <button type="button" id="append-fields" class="btn btn-secondary w-100 p-2">
                                    <i class="fa fa-plus"></i>
                                </button>
                            </div>
                        </div>

                        {{-- Dynamic Fields Container --}}
                        <div  class="mt-3">
                             <table class="table table-bordered table-hover" id="additional-fields-container">
                        <thead class="table-dark">
                            <tr>
                                <th>Accessory Name</th>
                                <th>Unit</th>
                                <th>Kg</th>
                                <th>In Quantity</th>
                                <th>Price</th>
                                <th>Total Price</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Dynamic rows will be added here -->
                        </tbody>
                        <tfoot class="table-light">
                            <tr>
                                <td></td>
                                <td align="right"><strong>Sub-Total(BDT)</strong></td>
                                <td align="right">
                                    <strong class="totalKg">0.00</strong>
                                    <input type="hidden" class="totalKg" value="0" name="totalKg" />
                                </td>
                                <td align="right">
                                    <strong class="ttlqty">0</strong>
                                    <input type="hidden" class="ttlqty" value="0" name="totalQty" />
                                </td>
                                <td align="right">
                                    <strong class="ttlunitprice">0.00</strong>
                                    <input type="hidden" class="ttlunitprice" value="0" name="ttlunitprice" />
                                </td>
                                <td align="right">
                                    <strong class="grandtotal">0.00</strong>
                                    <input type="hidden" class="grandtotal" value="0" name="grandtotal" />
                                </td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <!-- Summary Section -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label>Notes</label>
                                <textarea cols="50" rows="5" class="form-control" name="narration" placeholder="Enter notes here..."></textarea>
                            </div>
                        </div>
                        
                        <div class="col-md-12">
                            <div class="form-group">
                                <label>Image/Voucher</label>
                                <div class="file-input-wrapper">
                                    <input type="file" 
                                           id="voucher-input" 
                                           name="voucher" 
                                           accept="image/*,.pdf,.doc,.docx"
                                           class="@error('voucher') is-invalid @enderror">
                                    <label for="voucher-input" class="file-input-label">
                                        <i class="fa fa-cloud-upload"></i>
                                        <div>Click to select file</div>
                                        <small>Images, PDF, DOC files supported</small>
                                    </label>
                                    <div class="file-name" id="file-name"></div>
                                </div>
                                @error('voucher')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                                
                                <!-- Image Preview Container -->
                                <div class="image-preview-container">
                                    <div class="image-preview" id="image-preview">
                                        <img id="preview-img" src="" alt="Preview">
                                        <button type="button" class="image-remove-btn" id="remove-image">
                                            <i class="fa fa-times"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="calculation-panel">
                            <table class="table table-sm">
                                <tbody>
                                    <tr>
                                        <td align="right"><strong>Total</strong></td>
                                        <td align="right" class="text-right">
                                            <strong class="grandsubTotaltotal">0.00</strong>
                                            <input type="hidden" class="grandsubTotaltotal" value="0" name="grandsubTotaltotal" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right"><strong>Previous Due</strong></td>
                                        <td align="right" class="text-right">
                                            <strong id="previous_due">0.00</strong>
                                            <input type="hidden" id="previouse_due_amount" name="previouse_due_amount" value="0">
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right"><strong>Labor Bill (+)</strong></td>
                                        <td>
                                            <input type="number" 
                                                   id="labor_bill" 
                                                   name="labor_bill" 
                                                   class="form-control text-right" 
                                                   placeholder="0.00" 
                                                   step="0.01" 
                                                   min="0" />
                                        </td>
                                    </tr>
                                    <tr class="table-info">
                                        <td align="right"><strong>Net Total</strong></td>
                                        <td align="right" class="text-right">
                                            <strong class="ngrandTotal">0.00</strong>
                                            <input type="hidden" class="ngrandTotal" value="0" name="ngrandTotal" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right"><strong>Advance</strong></td>
                                        <td>
                                            
                                             <select name="advance_ledger_id"
                                                                            class="form-control select2">
                                                                            <x-banck :setAccounts="$accounts" />
                                                                        </select>
                                                                       
                                            <input type="number" 
                                                   id="advance" 
                                                   name="advance" 
                                                   class="form-control text-right" 
                                                   placeholder="0.00" 
                                                   step="0.01" 
                                                   min="0" />
                                        </td>
                                    </tr>
                                    <tr class="table-warning">
                                        <td align="right"><strong>Supplier Due</strong></td>
                                        <td align="right" class="text-right">
                                            <strong class="finalDue">0.00</strong>
                                            <input type="hidden" class="finalDue" value="0" name="finalDue" />
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">Create</button>
                    <a href="{{ route('stockin.list') }}" class="btn btn-secondary">Back to List</a>
                </div>
            </div>
        </div>
    </div>
</form>

    <div class="modal fade" id="addSupplierModal" tabindex="-1" role="dialog" aria-labelledby="addSupplierModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addSupplierModalLabel">Add Supplier</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="POST" id="addSupplierForm"
                    action="{{ route('inventorySetup.purchase.supplierCreate') }}">
                    @csrf
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="validationCustom01">Supplier Name * :</label>
                            <input type="text" name="name" class="form-control" id="validationCustom01"
                                placeholder="Supplier Name" value="{{ old('name') }}" required>
                        </div>
                        <div class="form-group">
                            <label for="validationCustom02"> E-mail :</label>
                            <input type="text" name="email" class="form-control" id="validationCustom02"
                                placeholder="E-mail" value="{{ old('email') }}" required>
                                @error('email')
                                    <span class=" error text-red text-bold">{{ $message }}</span>
                                @enderror
                        </div>
                         <div class="col-md-6 mb-3">
                                <label for="validationCustom01">Branch Name * :

                                  
                                </label>
                                <select class="form-control select2" name="branch_id">
                                    <option selected disabled value="">--Select--</option>
                                   @if(auth()->user()->role_id > 1)
                                    @foreach ($branchs as $key => $value)
                                        <option value="{{ $value->id }}" {{auth()->user()->branch_id == $value->id ? 'selected' :''}}>{{ $value->name }}</option>
                                    @endforeach
                                    @else 

                                  @foreach ($branchs as $key => $value)
                                        <option value="{{ $value->id }}">{{ $value->name }}</option>
                                    @endforeach
                                    @endif
                                </select>
                                @error('branch_id')
                                    <span class=" error text-red text-bold">{{ $message }}</span>
                                @enderror
                            </div>
                        <div class="form-group">
                            <label for="validationCustom01">Phone * :</label>
                            <input type="text" name="phone" class="form-control" id="validationCustom01"
                                placeholder="Phone" value="{{ old('phone') }}" required>
                                <span class="error text-red text-bold"></span>
                        </div>
                         <div class="col-md-6 mb-3">

                            <div class="form-group">
                                <label>Image</label>
                                <div class="file-input-wrapper">
                                    <input type="file" 
                                           id="image-input" 
                                           name="image" 
                                           accept="image/*,.pdf,.doc,.docx"
                                           class="@error('image') is-invalid @enderror">
                                    <label for="image-input" class="file-input-label">
                                        <i class="fa fa-cloud-upload"></i>
                                        <div>Click to select file</div>
                                        <small>Images, PDF, DOC files supported</small>
                                    </label>
                                    <div class="file-name-supplier" id="file-name-supplier"></div>
                                </div>
                                @error('image')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                                
                                <!-- Image Preview Container -->
                                <div class="image-preview-container">
                                    <div class="image-preview-supplier" id="image-preview-supplier">
                                        <img id="preview-img-supplier" src="" alt="Preview" style="height: 50px">
                                        <button type="button" class="image-remove-btn" id="remove-image-supplier">
                                            <i class="fa fa-times"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            </div>
                        <div class="form-group">
                            <label for="validationCustom01">BIN :</label>
                            <input type="text" name="specialNumber" class="form-control" id="validationCustom01"
                                placeholder="BIN Number" value="{{ old('specialNumber') }}">
                        </div>
                        <div class="form-group">
                            <label for="validationCustom02">Address :</label>
                            <input name="address" class="form-control" id="validationCustom02" placeholder="Address"
                                value="{{ old('address') }}" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">Save Supplier</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
 <script>
          $(document).ready(function(){
         function showBranchDiv(type) {
        if (type != "Project") {
            $("#showBranch").show(500);
        } else {
            $("#showBranch").hide(500);
        }
    }

       $('#image-input').on('change', function(e) {
            const file = e.target.files[0];
            const fileName = $('#file-name-supplier');
            const imagePreview = $('#image-preview-supplier');
            const previewImg = $('#preview-img-supplier');
            
            if (file) {
                // Show file name
                fileName.text(file.name);
                
                // Check if file is an image
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        previewImg.attr('src', e.target.result);
                        imagePreview.show();
                    }
                    reader.readAsDataURL(file);
                } else {
                    // For non-image files, show file info
                    imagePreview.hide();
                    fileName.html(`<i class="fa fa-file"></i> ${file.name} (${(file.size / 1024).toFixed(2)} KB)`);
                }
                
                // Update label text
                $('.file-input-label').html(`
                    <i class="fa fa-check-circle" style="color: #28a745;"></i>
                    <div>File selected successfully</div>
                    <small>Click to change file</small>
                `);
            }
        });

        // Remove image functionality
        $('#remove-image').on('click', function() {
            $('#image-input').val('');
            $('#image-preview-supplier').hide();
            $('#file-name-supplier').text('');
            $('.file-input-label').html(`
                <i class="fa fa-cloud-upload"></i>
                <div>Click to select file</div>
                <small>Images, PDF, DOC files supported</small>
            `);
        });

        // Drag and drop functionality
        $('.file-input-label').on('dragover', function(e) {
            e.preventDefault();
            $(this).addClass('drag-over');
        });

        $('.file-input-label').on('dragleave', function(e) {
            e.preventDefault();
            $(this).removeClass('drag-over');
        });

        $('.file-input-label').on('drop', function(e) {
            e.preventDefault();
            $(this).removeClass('drag-over');
            
            const files = e.originalEvent.dataTransfer.files;
            if (files.length > 0) {
                $('#image-input')[0].files = files;
                $('#image-input').trigger('change');
            }
        });
    })
   

    </script>
<script>
   $(document).ready(function() {
    // Image upload and preview functionality
    $('#voucher-input').on('change', function(e) {
        const file = e.target.files[0];
        const fileName = $('#file-name');
        const imagePreview = $('#image-preview');
        const previewImg = $('#preview-img');
        
        if (file) {
            // Show file name
            fileName.text(file.name);
            
            // Check if file is an image
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImg.attr('src', e.target.result);
                    imagePreview.show();
                }
                reader.readAsDataURL(file);
            } else {
                // For non-image files, show file info
                imagePreview.hide();
                fileName.html(`<i class="fa fa-file"></i> ${file.name} (${(file.size / 1024).toFixed(2)} KB)`);
            }
            
            // Update label text
            $('.file-input-label').html(`
                <i class="fa fa-check-circle" style="color: #28a745;"></i>
                <div>File selected successfully</div>
                <small>Click to change file</small>
            `);
        }
    });

    // Remove image functionality
    $('#remove-image').on('click', function() {
        $('#voucher-input').val('');
        $('#image-preview').hide();
        $('#file-name').text('');
        $('.file-input-label').html(`
            <i class="fa fa-cloud-upload"></i>
            <div>Click to select file</div>
            <small>Images, PDF, DOC files supported</small>
        `);
    });

    // Drag and drop functionality
    $('.file-input-label').on('dragover', function(e) {
        e.preventDefault();
        $(this).addClass('drag-over');
    });

    $('.file-input-label').on('dragleave', function(e) {
        e.preventDefault();
        $(this).removeClass('drag-over');
    });

    $('.file-input-label').on('drop', function(e) {
        e.preventDefault();
        $(this).removeClass('drag-over');
        
        const files = e.originalEvent.dataTransfer.files;
        if (files.length > 0) {
            $('#voucher-input')[0].files = files;
            $('#voucher-input').trigger('change');
        }
    });

    // Supplier Create
$('#addSupplierForm').on('submit', function(e) {
    e.preventDefault();

    let formData = new FormData(this);

    $.ajax({
        url: $(this).attr('action'),
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,

        success: function(response) {
            // Clear old errors
            $('.error').text('');

            $('#addSupplierModal').modal('hide');

            // Add new supplier to dropdown
            $('select[name="ledger_id"]').append(
                `<option value="${response.accounts.id}" selected>
                    ${response.accounts.account_name} (${response.phone})
                </option>`
            ).trigger('change');

            $('#addSupplierForm')[0].reset();
        },

        error: function(xhr) {
            if (xhr.status === 422) {
                let errors = xhr.responseJSON.errors;

                // clear old errors
                $('.error').text('');

                // loop through each error
                $.each(errors, function(field, messages) {
                    // find the span.error under the same form-group
                    let errorSpan = $(`[name="${field}"]`)
                        .closest('.form-group, .col-md-6')
                        .find('.error');

                    errorSpan.text(messages[0]);
                });
            } else {
                alert("Something went wrong!");
            }
        }
    });
});



    // NEW: Handle ledger selection and fetch previous due
    $('#ledger_id').on('change', function() {
        const ledgerId = $(this).val();
        
        if (ledgerId) {
            // Show loading indicator
            $('#previous_due').html('<i class="fa fa-spinner fa-spin"></i>');
            
            // Make AJAX request to get supplier due
            $.ajax({
                url: `/admin/supplier-due-payment/${ledgerId}`, // Adjust this URL to match your route
                method: 'GET',
                success: function(response) {
                    // Update previous due display
                    const dueAmount = parseFloat(response) || 0;
                    $('#previous_due').text(dueAmount.toFixed(2));
                    $('#previouse_due_amount').val(dueAmount);
                    
                    // Recalculate totals
                    calculateTotals();
                },
                error: function(xhr, status, error) {
                    console.error('Error fetching supplier due:', error);
                    $('#previous_due').text('0.00');
                    $('#previouse_due_amount').val(0);
                    calculateTotals();
                }
            });
        } else {
            // Reset previous due if no ledger selected
            $('#previous_due').text('0.00');
            $('#previouse_due_amount').val(0);
            calculateTotals();
        }
    });

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

    let rowCount = 0;

    // 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) {
            rowCount++;

            const newRow = `
                <tr id="row-${rowCount}" class="dynamic-row">
                    <td>
                        ${accessoryName}
                        <input type="hidden" name="accessory_id[]" value="${accessoryId}">
                    </td>
                    <td>
                        <input type="text" class="form-control readonly-input" value="${unit}" readonly>
                    </td>
                    <td>
                        <input type="number" name="kg[]" class="form-control kg-input text-right" step="0.01" min="0" placeholder="0.00">
                    </td>
                    <td>
                        <input type="number" name="in_quantity[]" class="form-control quantity-input text-right" min="0" placeholder="0" required >
                    </td>
                    <td>
                        <input type="number" name="price[]" class="form-control price-input text-right" step="0.01" min="0" placeholder="0.00" >
                    </td>
                    <td>
                        <input type="number" name="total_price[]" class="form-control 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="fa fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `;

            $('#additional-fields-container tbody').append(newRow);
            
            // Clear form fields
            $('#accessory_name').val('');
            $('#unit').val('');
            
            // Focus on the first input of the new row
            $(`#row-${rowCount} .kg-input`).focus();
            
            calculateTotals();
        } else {
            alert('Please select an accessory and unit before adding an item.');
        }
    });

    // Calculate row totals on input
    $('#additional-fields-container').on('input', 'input[name="price[]"], input[name="in_quantity[]"], input[name="kg[]"]', function() {
        const $row = $(this).closest('tr');
        const price = parseFloat($row.find('input[name="price[]"]').val()) || 0;
        const quantity = parseFloat($row.find('input[name="in_quantity[]"]').val()) || 0;
        const kg = parseFloat($row.find('input[name="kg[]"]').val()) || 0;

        let total = 0;
        // If kg is provided, use kg * price, otherwise use quantity * price
        if (kg > 0) {
            total = kg * price;
        } else if (quantity > 0) {
            total = quantity * price;
        }

        $row.find('input[name="total_price[]"]').val(total.toFixed(2));
        calculateTotals();
    });

    // Remove row
    $('#additional-fields-container').on('click', '.remove-row', function() {
        const rowId = $(this).data('row-id');
        $('#' + rowId).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;

        // Calculate totals from all rows
        $('#additional-fields-container tbody tr').each(function() {
            const rowTotal = parseFloat($(this).find('input[name="total_price[]"]').val()) || 0;
            const quantity = parseFloat($(this).find('input[name="in_quantity[]"]').val()) || 0;
            const kg = parseFloat($(this).find('input[name="kg[]"]').val()) || 0;
            const price = parseFloat($(this).find('input[name="price[]"]').val()) || 0;

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

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

        // Calculate final totals
        const grandTotal = subtotal;
        const netTotal = grandTotal + previousDue + laborBill;
        const finalDue = netTotal - advance;

        // Update all display elements
        $('.grandtotal').text(grandTotal.toFixed(2));
        $('.grandtotal').val(grandTotal.toFixed(2));
        
        $('.grandsubTotaltotal').text(grandTotal.toFixed(2));
        $('.grandsubTotaltotal').val(grandTotal.toFixed(2));
        
        $('.ttlqty').text(totalQuantity);
        $('.ttlqty').val(totalQuantity);
        
        $('.totalKg').text(totalKg.toFixed(2));
        $('.totalKg').val(totalKg.toFixed(2));
        
        $('.ttlunitprice').text(totalUnitPrice.toFixed(2));
        $('.ttlunitprice').val(totalUnitPrice.toFixed(2));
        
        $('.ngrandTotal').text(netTotal.toFixed(2));
        $('.ngrandTotal').val(netTotal.toFixed(2));
        
        $('.finalDue').text(finalDue.toFixed(2));
        $('.finalDue').val(finalDue.toFixed(2));
    }

    // Initialize
    calculateTotals();
});

// Global functions for external use
function updatePreviousDue(amount) {
    $('#previous_due').text(parseFloat(amount).toFixed(2));
    $('#previouse_due_amount').val(amount);
    calculateTotals();
}

function clearAll() {
    $('#additional-fields-container tbody').empty();
    $('#labor_bill').val('');
    $('#advance').val('');
    $('textarea[name="narration"]').val('');
    // Clear image
    $('#voucher-input').val('');
    $('#image-preview').hide();
    $('#file-name').text('');
    $('.file-input-label').html(`
        <i class="fa fa-cloud-upload"></i>
        <div>Click to select file</div>
        <small>Images, PDF, DOC files supported</small>
    `);
    calculateTotals();
}
</script>

@push('scripts')
@endpush