<?php $__env->startSection('title', 'Edit Stock In'); ?>
<style>
/* Updated CSS for better image preview */
.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;
    /* Show preview if image exists, hide if not */
    display: <?php echo e($stockIn->voucher && file_exists(public_path('/backend/logo/' . $stockIn->voucher)) ? 'block' : 'none'); ?>;
}

.image-preview img {
    max-width: 100%;
    max-height: 100%;
    border-radius: 4px;
    display: block;
}

.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;
}

/* Additional styles for existing file display */
.existing-file-info {
    background: #e8f5e8;
    border: 1px solid #d4edda;
    border-radius: 4px;
    padding: 10px;
    margin-top: 10px;
    font-size: 12px;
    color: #155724;
}

.existing-file-info i {
    color: #28a745;
    margin-right: 5px;
}
</style>

<style>
/* Additional CSS for image popup */
.image-clickable {
    cursor: pointer;
    transition: transform 0.2s ease;
}

.image-clickable:hover {
    transform: scale(1.05);
    opacity: 0.9;
}

#modalImage {
    max-width: 100%;
    max-height: 70vh;
    object-fit: contain;
}

.modal-lg {
    max-width: 90%;
}

@media (max-width: 768px) {
    .modal-lg {
        max-width: 95%;
        margin: 1rem;
    }
}

/* Loading spinner for modal */
.modal-loading {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
}

.spinner-border {
    width: 3rem;
    height: 3rem;
}
</style>
<?php $__env->startSection('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="<?php echo e(route('home')); ?>">Dashboard</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo e(route('stockin.list')); ?>">Stock In</a></li>
                    <li class="breadcrumb-item active">Edit</li>
                </ol>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('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="<?php echo e(route('stockin.update', $stockIn->id)); ?>" method="POST" id="edit-stockin-form">
                    <?php echo csrf_field(); ?>
                    <?php echo method_field('PUT'); ?>
                    
                    <div class="card-body">
                        <!-- Add Item Section -->
                        <div class="row mb-4">
                            <div class="col-12">
                                 <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>
                                    <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.account','data' => ['setAccounts' => $ledgers,'selectVal' => $stockIn->ledger_id]]); ?>
<?php $component->withName('account'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes(['setAccounts' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($ledgers),'selectVal' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($stockIn->ledger_id)]); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4)): ?>
<?php $component = $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4; ?>
<?php unset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4); ?>
<?php endif; ?>
                                </select>
                                <?php $__errorArgs = ['ledger_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <span class=" error text-red text-bold"><?php echo e($message); ?></span>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>
                            </div>
                        </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>
                                   <?php if(auth()->user()->role_id > 1): ?>
                                    <?php $__currentLoopData = $branchs; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($value->id); ?>" <?php echo e(auth()->user()->branch_id == $value->id ? 'selected' :''); ?>><?php echo e($value->name); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    <?php else: ?> 

                                <?php $__currentLoopData = $branchs; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($value->id); ?>"><?php echo e($value->name); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    <?php endif; ?>
                                </select>
                                <?php $__errorArgs = ['name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <span class=" error text-red text-bold"><?php echo e($message); ?></span>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </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 <?php $__errorArgs = ['accessory_name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>">
                                        <option value="">Select Accessory</option>
                                               <?php if(auth()->user()->role_id > 1): ?>
                                        <?php $__currentLoopData = App\Models\Accesories::where('branch_id', auth()->user()->branch_id)->get(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $accessory): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($accessory->name); ?>" data-id="<?php echo e($accessory->id); ?>"
                                                data-unit="<?php echo e($accessory->unit); ?>">
                                                <?php echo e($accessory->name); ?>

                                            </option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        <?php else: ?> 
                                       <?php $__currentLoopData = App\Models\Accesories::all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $accessory): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($accessory->name); ?>" data-id="<?php echo e($accessory->id); ?>"
                                                data-unit="<?php echo e($accessory->unit); ?>">
                                                <?php echo e($accessory->name); ?>

                                            </option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

                                        <?php endif; ?>
                                    </select>
                                    <?php $__errorArgs = ['accessory_name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                </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 <?php $__errorArgs = ['unit'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                        placeholder="Unit will be auto-filled" readonly>
                                    <?php $__errorArgs = ['unit'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                </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">
                                    <?php if($stockIn && $stockIn->stock_in_details): ?>
                                        <?php $__currentLoopData = $stockIn->stock_in_details; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $details): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <tr class="dynamic-row" id="row-<?php echo e($index); ?>">
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <i class="fas fa-cube text-primary mr-2"></i>
                                                        <span><?php echo e($details->accessories->name ?? 'N/A'); ?></span>
                                                    </div>
                                                    <input type="hidden" name="accessory_id[]" value="<?php echo e($details->aceesories_id); ?>">
                                                    <input type="hidden" name="detail_id[]" value="<?php echo e($details->id); ?>">
                                                      <input type="hidden" name="old_quantity[]" value="<?php echo e($details->in_quantity); ?>">
                                                </td>
                                                <td>
                                                    <input type="text" class="form-control form-control-sm" 
                                                           value="<?php echo e($details->accessories->unit ?? 'N/A'); ?>" readonly>
                                                </td>
                                                <td>
                                                    <input type="number" name="kg[]" 
                                                           class="form-control form-control-sm kg-input text-right" 
                                                           value="<?php echo e($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="<?php echo e($details->in_quantity); ?>" min="0" required>
                                                </td>
                                                <td>
                                                    <input type="number" name="price[]" 
                                                           class="form-control form-control-sm price-input text-right" 
                                                           value="<?php echo e(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="<?php echo e($details->total_price); ?>" readonly>
                                                </td>
                                                <td class="text-center">
                                                    <button type="button" class="btn btn-danger btn-sm remove-row" 
                                                            data-row-id="row-<?php echo e($index); ?>">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    <?php 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="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="<?php $__errorArgs = ['voucher'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>">
            <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>
        <?php $__errorArgs = ['voucher'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
            <div class="invalid-feedback"><?php echo e($message); ?></div>
        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
        
        <!-- Image Preview Container -->
        <div class="image-preview-container">
            <div class="image-preview" id="image-preview">
                <?php if($stockIn->voucher && file_exists(public_path('/backend/logo/' . $stockIn->voucher))): ?>
                    <img id="preview-img" src="<?php echo e(asset('/backend/logo/' . $stockIn->voucher)); ?>" alt="Preview">
                <?php else: ?>
                    <img id="preview-img" src="" alt="Preview" style="display: none;">
                <?php endif; ?>
                <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="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"><?php echo e($stockIn->previous_due ?? '0.00'); ?></span>
                                                        <input type="hidden" name="previouse_due_amount" value="<?php echo e($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="<?php echo e($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>

                                                 <?php if(auth()->user()->branch_id != 2): ?>
                                             <tr>
                                                    <td class="text-right font-weight-bold">Advance Account:</td>
                                                    <td>
                                                        <select name="advance_ledger_id" class="form-control form-control-sm select2">
                                                            <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.account','data' => ['setAccounts' => $accounts]]); ?>
<?php $component->withName('account'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes(['setAccounts' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($accounts)]); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4)): ?>
<?php $component = $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4; ?>
<?php unset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4); ?>
<?php endif; ?>
                                                        </select>
                                                    </td>
                                                </tr>
                                                                        <?php endif; ?>
                                              
                                                <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="<?php echo e($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="<?php echo e(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>

<div class="modal fade" id="imageModal" tabindex="-1" role="dialog" aria-labelledby="imageModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="imageModalLabel">Image Preview</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body text-center">
                <img id="modalImage" src="" alt="Full Size Image" class="img-fluid">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <a id="downloadImage" href="" download class="btn btn-primary">
                    <i class="fas fa-download"></i> Download
                </a>
            </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() {
    // Function to load previous due amount
    function loadPreviousDue(ledgerId) {
        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}`,
                method: 'GET',
                success: function(response) {
                    // Update previous due display
                    const dueAmount = parseFloat(response) || 0;
                    $('#previous_due').text(dueAmount.toFixed(2));
                    $('input[name="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');
                    $('input[name="previouse_due_amount"]').val(0);
                    calculateTotals();
                }
            });
        } else {
            // Reset previous due if no ledger selected
            $('#previous_due').text('0.00');
            $('input[name="previouse_due_amount"]').val(0);
            calculateTotals();
        }
    }

    // Auto-load previous due when ledger changes
    $('#ledger_id').on('change', function() {
        const ledgerId = $(this).val();
        loadPreviousDue(ledgerId);
    });

    // Auto-load previous due on page load if ledger is already selected
    const initialLedgerId = $('#ledger_id').val();
    if (initialLedgerId) {
        loadPreviousDue(initialLedgerId);
    }

    // Initialize Select2 and trigger change event to load due
    if ($.fn.select2) {
        $('.select2').select2({
            theme: 'bootstrap4',
            width: '100%'
        }).trigger('change');
    }

    // Re-initialize Select2 for ledger dropdown specifically
    $('#ledger_id').select2({
        theme: 'bootstrap4',
        width: '100%',
        placeholder: '--Select Ledger--'
    }).on('select2:select', function(e) {
        // This will also trigger when user selects from dropdown
        const ledgerId = e.params.data.id;
        loadPreviousDue(ledgerId);
    });

    // Rest of your existing code...
    
    function makeImageClickable() {
        $('.image-preview img').addClass('image-clickable').off('click').on('click', function(e) {
            e.stopPropagation();
            const imgSrc = $(this).attr('src');
            const imgAlt = $(this).attr('alt') || 'Image Preview';
            showImageModal(imgSrc, imgAlt);
        });
    }

    function showImageModal(imageSrc, imageTitle = 'Image Preview') {
        const modalBody = $('#imageModal .modal-body');
        modalBody.html(`
            <div class="modal-loading">
                <div class="spinner-border text-primary" role="status">
                    <span class="sr-only">Loading...</span>
                </div>
            </div>
        `);

        $('#imageModalLabel').text(imageTitle);
        $('#imageModal').modal('show');

        const img = new Image();
        img.onload = function() {
            modalBody.html(`<img id="modalImage" src="${imageSrc}" alt="${imageTitle}" class="img-fluid">`);
            $('#downloadImage').attr('href', imageSrc);
        };
        
        img.onerror = function() {
            modalBody.html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    Failed to load image. Please try again.
                </div>
            `);
        };
        
        img.src = imageSrc;
    }

    makeImageClickable();

    $('#voucher-input').off('change').on('change', function(e) {
        const file = e.target.files[0];
        const fileName = $('#file-name');
        const imagePreview = $('#image-preview');
        const previewImg = $('#preview-img');
        
        if (file) {
            fileName.text(file.name);
            
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImg.attr('src', e.target.result);
                    previewImg.show();
                    imagePreview.show();
                    setTimeout(makeImageClickable, 100);
                }
                reader.readAsDataURL(file);
            } else {
                imagePreview.hide();
                fileName.html(`<i class="fa fa-file"></i> ${file.name} (${(file.size / 1024).toFixed(2)} KB)`);
            }
            
            $('.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>
            `);
        }
    });

    $('#imageModal').on('keydown', function(e) {
        if (e.key === 'Escape') {
            $(this).modal('hide');
        }
    });

    $('#imageModal').on('shown.bs.modal', function() {
        const modalImage = $('#modalImage');
        let scale = 1;
        let translateX = 0, translateY = 0;

        modalImage.on('wheel', function(e) {
            e.preventDefault();
            const delta = e.originalEvent.deltaY;
            const scaleStep = 0.1;
            
            if (delta > 0) {
                scale = Math.max(0.5, scale - scaleStep);
            } else {
                scale = Math.min(3, scale + scaleStep);
            }
            
            $(this).css('transform', `scale(${scale}) translate(${translateX}px, ${translateY}px)`);
        });

        modalImage.on('dblclick', function() {
            scale = 1;
            translateX = 0;
            translateY = 0;
            $(this).css('transform', 'scale(1) translate(0px, 0px)');
        });
    });

    $('#imageModal').on('hidden.bs.modal', function() {
        $('#modalImage').off('wheel dblclick mousedown mousemove mouseup');
    });

    $('#remove-image').on('click', function() {
        $('#voucher-input').val('');
        $('#image-preview').hide();
        $('#preview-img').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>
        `);
    });

    $('.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');
        }
    });

    let rowCount = <?php echo e($stockIn->stock_in_details->count() ?? 0); ?>;

    $('#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('');
        }
    });

    $('#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" required >
                </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);
        
        $('#accessory_name').val('').trigger('change');
        $('#unit').val('');
        
        $(`#row-${rowCount} .kg-input`).focus();
        
        calculateTotals();
    });

    $('#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();
    });

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

    $('#labor_bill, #advance').on('input', function() {
        calculateTotals();
    });

    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;

        $('.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();

    $('#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>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('backend.layouts.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH E:\jubayer\resources\views/backend/pages/stockin/edit.blade.php ENDPATH**/ ?>