<?php $__env->startSection('title', 'Costos Adicionales'); ?>

<?php $__env->startSection('header', 'Gestión de Compras'); ?>

<?php $__env->startSection('content'); ?>
<div class="page-container">
    <div class="page-header">
        <h2 class="page-title">Costos Adicionales - Compra #<?php echo e($compra->numero_compra); ?></h2>
        <a href="<?php echo e(route('compras.index')); ?>" class="btn btn-secondary">
            <i class="fa-solid fa-arrow-left"></i>
            Volver
        </a>
    </div>

    <!-- Información de la Compra -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="form-row">
                <div class="form-group">
                    <label class="form-label">Proveedor</label>
                    <input type="text" class="form-control" value="<?php echo e($compra->proveedor->nombre); ?>" readonly>
                </div>
                <div class="form-group">
                    <label class="form-label">Fecha de Compra</label>
                    <input type="text" class="form-control" value="<?php echo e($compra->fecha_compra->format('d/m/Y')); ?>" readonly>
                </div>
                <div class="form-group">
                    <label class="form-label">Total Compra</label>
                    <input type="text" class="form-control" value="$<?php echo e(number_format($compra->total, 0, ',', '.')); ?>" readonly>
                </div>
            </div>
        </div>
    </div>

    <form action="<?php echo e(route('compras.guardarCostos', $compra)); ?>" method="POST">
        <?php echo csrf_field(); ?>

        <!-- Costos Adicionales -->
        <div class="card">
            <div class="card-header">
                <h3><i class="fa-solid fa-dollar-sign"></i> Costos Adicionales</h3>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table" id="costosTable">
                        <thead>
                            <tr>
                                <th style="width: 60%;">Concepto</th>
                                <th style="width: 30%;">Valor</th>
                                <th style="width: 10%;" class="text-center">Acción</th>
                            </tr>
                        </thead>
                        <tbody id="costosTableBody">
                            <?php if($compra->costos->count() > 0): ?>
                                <?php $__currentLoopData = $compra->costos; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $costo): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <tr class="costo-row">
                                    <td>
                                        <input type="text"
                                               name="costos[<?php echo e($index); ?>][concepto]"
                                               class="form-control"
                                               value="<?php echo e($costo->concepto); ?>"
                                               placeholder="Ej: Lavada, Repuestos, SOAT...">
                                    </td>
                                    <td>
                                        <div class="input-group">
                                            <span class="input-group-text">$</span>
                                            <input type="text"
                                                   name="costos[<?php echo e($index); ?>][valor]"
                                                   class="form-control number-format costo-valor"
                                                   value="<?php echo e(number_format($costo->valor, 0, ',', '.')); ?>">
                                        </div>
                                    </td>
                                    <td class="text-center">
                                        <button type="button" class="btn btn-sm btn-danger btn-eliminar-costo">
                                            <i class="fa-solid fa-trash-can"></i>
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            <?php else: ?>
                                <tr class="costo-row">
                                    <td>
                                        <input type="text"
                                               name="costos[0][concepto]"
                                               class="form-control"
                                               placeholder="Ej: Lavada, Repuestos, SOAT...">
                                    </td>
                                    <td>
                                        <div class="input-group">
                                            <span class="input-group-text">$</span>
                                            <input type="text"
                                                   name="costos[0][valor]"
                                                   class="form-control number-format costo-valor"
                                                   value="0">
                                        </div>
                                    </td>
                                    <td class="text-center">
                                        <button type="button" class="btn btn-sm btn-danger btn-eliminar-costo">
                                            <i class="fa-solid fa-trash-can"></i>
                                        </button>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <button type="button" class="btn btn-success mt-3" id="btnAgregarCosto">
                    <i class="fa-solid fa-plus"></i>
                    Agregar Costo
                </button>
            </div>
        </div>

        <!-- Observaciones -->
        <div class="card mt-4">
            <div class="card-header">
                <h3><i class="fa-solid fa-comment"></i> Observaciones</h3>
            </div>
            <div class="card-body">
                <textarea name="observaciones"
                          class="form-control"
                          rows="3"
                          placeholder="Notas adicionales sobre los costos..."><?php echo e(old('observaciones', $compra->observaciones)); ?></textarea>
            </div>
        </div>

        <!-- Resumen -->
        <div class="card mt-4">
            <div class="card-body">
                <div style="display: flex; flex-direction: column; gap: 1rem;">
                    <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 0; border-bottom: 1px solid var(--border-color);">
                        <span style="color: var(--text-secondary); font-size: 1rem;">Precio de compra</span>
                        <span style="color: var(--text-primary); font-size: 1.125rem; font-weight: 600;" id="precioCompra">
                            $<?php echo e(number_format($compra->total, 0, ',', '.')); ?>

                        </span>
                    </div>
                    <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 0; border-bottom: 1px solid var(--border-color);">
                        <span style="color: var(--text-secondary); font-size: 1rem;">Costos adicionales</span>
                        <span style="color: #dc3545; font-size: 1.125rem; font-weight: 600;" id="costosAdicionales">
                            $0
                        </span>
                    </div>
                    <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 0;">
                        <span style="color: var(--text-primary); font-size: 1.25rem; font-weight: 700;">Costo total</span>
                        <span style="color: var(--primary-color); font-size: 1.5rem; font-weight: 700;" id="costoTotal">
                            $<?php echo e(number_format($compra->total, 0, ',', '.')); ?>

                        </span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Botones de Acción -->
        <div class="form-actions-bottom">
            <button type="submit" class="btn btn-primary btn-lg">
                <i class="fa-solid fa-save"></i>
                Guardar Costos
            </button>
            <a href="<?php echo e(route('compras.index')); ?>" class="btn btn-secondary btn-lg">
                <i class="fa-solid fa-arrow-left"></i>
                Cancelar
            </a>
        </div>
    </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    let costoIndex = <?php echo e($compra->costos->count() > 0 ? $compra->costos->count() : 1); ?>;
    const precioCompra = <?php echo e($compra->total); ?>;

    // Función para formatear números con separadores de miles (Formato Colombia)
    function formatNumber(value) {
        // Remover todo excepto números
        let number = value.toString().replace(/[^\d]/g, '');

        if (number === '' || number === '0') {
            return '0';
        }

        // Formatear con puntos como separadores de miles
        return number.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
    }

    // Función para limpiar el formato y obtener el número puro
    function unformatNumber(value) {
        return parseFloat(value.toString().replace(/\./g, '')) || 0;
    }

    // Calcular totales
    function calcularTotales() {
        let totalCostos = 0;

        document.querySelectorAll('.costo-valor').forEach(input => {
            const valor = unformatNumber(input.value);
            totalCostos += valor;
        });

        document.getElementById('costosAdicionales').textContent = '$' + formatNumber(totalCostos);
        document.getElementById('costoTotal').textContent = '$' + formatNumber(precioCompra + totalCostos);
    }

    // Formatear inputs numéricos
    function setupNumberInput(input) {
        // Formatear valor inicial
        if (input.value && input.value !== '0') {
            input.value = formatNumber(input.value);
        }

        input.addEventListener('input', function(e) {
            const cursorPosition = this.selectionStart;
            const oldLength = this.value.length;

            this.value = formatNumber(this.value);

            const newLength = this.value.length;
            const lengthDiff = newLength - oldLength;
            this.setSelectionRange(cursorPosition + lengthDiff, cursorPosition + lengthDiff);

            calcularTotales();
        });

        input.addEventListener('blur', function() {
            if (this.value === '' || this.value === '0') {
                this.value = '0';
            }
            calcularTotales();
        });
    }

    // Inicializar inputs existentes
    document.querySelectorAll('.costo-valor').forEach(setupNumberInput);

    // Agregar nueva fila de costo
    document.getElementById('btnAgregarCosto').addEventListener('click', function() {
        const tbody = document.getElementById('costosTableBody');
        const newRow = document.createElement('tr');
        newRow.className = 'costo-row';
        newRow.innerHTML = `
            <td>
                <input type="text"
                       name="costos[${costoIndex}][concepto]"
                       class="form-control"
                       placeholder="Ej: Lavada, Repuestos, SOAT...">
            </td>
            <td>
                <div class="input-group">
                    <span class="input-group-text">$</span>
                    <input type="text"
                           name="costos[${costoIndex}][valor]"
                           class="form-control number-format costo-valor"
                           value="0">
                </div>
            </td>
            <td class="text-center">
                <button type="button" class="btn btn-sm btn-danger btn-eliminar-costo">
                    <i class="fa-solid fa-trash-can"></i>
                </button>
            </td>
        `;

        tbody.appendChild(newRow);

        // Configurar el nuevo input numérico
        const newInput = newRow.querySelector('.costo-valor');
        setupNumberInput(newInput);

        costoIndex++;
    });

    // Eliminar fila de costo (usando delegación de eventos)
    document.getElementById('costosTableBody').addEventListener('click', function(e) {
        if (e.target.closest('.btn-eliminar-costo')) {
            const row = e.target.closest('.costo-row');
            const tbody = document.getElementById('costosTableBody');

            // Mantener al menos una fila
            if (tbody.querySelectorAll('.costo-row').length > 1) {
                row.remove();
                calcularTotales();
            } else {
                // Limpiar la última fila en lugar de eliminarla
                row.querySelector('input[name*="[concepto]"]').value = '';
                row.querySelector('.costo-valor').value = '0';
                calcularTotales();
            }
        }
    });

    // Calcular totales iniciales
    calcularTotales();
});
</script>

<style>
.table-responsive {
    overflow-x: auto;
}

.costo-row td {
    vertical-align: middle;
    padding: 0.75rem;
}

.btn-eliminar-costo {
    padding: 0.375rem 0.75rem;
}
</style>

<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\xampp\htdocs\perfumeChimi\resources\views/compras/costos.blade.php ENDPATH**/ ?>