<?php $__env->startSection('heading', 'Tambah Pembelian'); ?>


<?php $__env->startSection('content'); ?>
<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1>Tambah Pembelian</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo e(route('home')); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo e(route('purchase')); ?>">Pembelian</a></li>
                    <li class="breadcrumb-item active">Tambah</li>
                </ol>
            </div>
        </div>
    </div>
</section>

<section class="content">
    <div class="container-fluid">
        <form action="<?php echo e(route('purchase.save')); ?>" method="POST">
            <?php echo csrf_field(); ?>
            <div class="row">
                <div class="col-md-8">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Detail Produk</h3>
                        </div>
                        <div class="card-body">
                            <!-- Tab Navigation -->
                            <ul class="nav nav-tabs mb-3" id="productInputTab" role="tablist">
                                <li class="nav-item">
                                    <a class="nav-link active" id="select-tab" data-toggle="tab" href="#selectProduct" role="tab">
                                        <i class="fas fa-list"></i> Pilih Produk
                                    </a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link" id="scan-tab" data-toggle="tab" href="#scanProduct" role="tab">
                                        <i class="fas fa-qrcode"></i> Scan QR Code
                                    </a>
                                </li>
                            </ul>

                            <!-- Tab Content -->
                            <div class="tab-content" id="productInputTabContent">
                                <!-- Tab: Select Product -->
                                <div class="tab-pane fade show active" id="selectProduct" role="tabpanel">
                                    <div class="row">
                                        <div class="col-md-12">
                                            <div class="form-group">
                                                <label>Pilih Produk</label>
                                                <select id="productSelect" class="form-control select2" disabled>
                                                    <option value="">-- Pilih Cabang Terlebih Dahulu --</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Tab: Scan QR Code -->
                                <div class="tab-pane fade" id="scanProduct" role="tabpanel">
                                    <div class="row">
                                        <div class="col-md-12">
                                            <div class="form-group">
                                                <label><i class="fas fa-qrcode"></i> Scan atau Ketik Barcode</label>
                                                <input type="text" id="barcodeInput" class="form-control form-control-lg"
                                                    placeholder="Scan QR Code atau ketik barcode produk..." autofocus>
                                                <small class="form-text text-muted">
                                                    <i class="fas fa-info-circle"></i> Gunakan barcode scanner atau ketik barcode secara manual
                                                </small>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row mt-3">
                                        <div class="col-md-12">
                                            <div class="text-center mb-2">
                                                <button type="button" id="startCameraBtn" class="btn btn-success btn-lg">
                                                    <i class="fas fa-camera"></i> Aktifkan Kamera untuk Scan QR Code
                                                </button>
                                                <button type="button" id="stopCameraBtn" class="btn btn-danger btn-lg" style="display: none;">
                                                    <i class="fas fa-stop"></i> Matikan Kamera
                                                </button>
                                            </div>
                                            <div id="qr-reader" style="display: none; width: 100%; max-width: 600px; margin: 0 auto;"></div>
                                            <div id="qr-reader-results" class="mt-2"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="table-responsive">
                                <table class="table table-bordered" id="detailTable">
                                    <thead>
                                        <tr>
                                            <th style="width: 30%;">Produk</th>
                                            <th style="width: 12%;">Stok</th>
                                            <th style="width: 13%;">Qty</th>
                                            <th style="width: 18%;">Harga</th>
                                            <th style="width: 20%;">Sub Total</th>
                                            <th style="width: 7%;">Aksi</th>
                                        </tr>
                                    </thead>
                                    <tbody id="detailBody">
                                        <tr class="text-center">
                                            <td colspan="6">Belum ada produk yang dipilih</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Informasi Pembelian</h3>
                        </div>
                        <div class="card-body">
                            <?php if(session('error')): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <?php echo e(session('error')); ?>

                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <?php endif; ?>

                            <div class="form-group">
                                <label>No. Pembelian</label>
                                <input type="text" class="form-control" value="<?php echo e($purchaseNumber); ?>" readonly>
                            </div>

                            <div class="form-group">
                                <label>Supplier <span class="text-danger">*</span></label>
                                <select name="supplier_id" class="form-control <?php $__errorArgs = ['supplier_id'];
$__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); ?>" required>
                                    <option value="">-- Pilih Supplier --</option>
                                    <?php $__currentLoopData = $suppliers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $supplier): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($supplier->id); ?>" <?php echo e(old('supplier_id') == $supplier->id ? 'selected' : ''); ?>>
                                        <?php echo e($supplier->name); ?>

                                    </option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                                <?php $__errorArgs = ['supplier_id'];
$__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 class="form-group">
                                <label>Cabang <span class="text-danger">*</span></label>
                                <select name="branch_id" class="form-control <?php $__errorArgs = ['branch_id'];
$__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); ?>" required>
                                    <option value="">-- Pilih Cabang --</option>
                                    <?php $__currentLoopData = $branches; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $branch): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($branch->id); ?>" <?php echo e(old('branch_id') == $branch->id ? 'selected' : ''); ?>>
                                        <?php echo e($branch->name); ?>

                                    </option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                                <?php $__errorArgs = ['branch_id'];
$__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 class="form-group">
                                <label>Tanggal Pembelian <span class="text-danger">*</span></label>
                                <input type="date" name="purchase_date" class="form-control <?php $__errorArgs = ['purchase_date'];
$__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); ?>"
                                    value="<?php echo e(old('purchase_date', date('Y-m-d'))); ?>" required>
                                <?php $__errorArgs = ['purchase_date'];
$__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 class="form-group">
                                <label>Catatan</label>
                                <textarea name="notes" class="form-control" rows="3"><?php echo e(old('notes')); ?></textarea>
                            </div>

                            <hr>

                            <div class="form-group">
                                <label>Total Pembelian</label>
                                <h3 class="text-success" id="totalAmount">Rp 0</h3>
                            </div>
                        </div>
                        <div class="card-footer">
                            <button type="submit" class="btn btn-success btn-block" id="submitBtn">
                                <i class="fas fa-save"></i> Simpan Pembelian
                            </button>
                            <a href="<?php echo e(route('purchase')); ?>" class="btn btn-secondary btn-block">
                                <i class="fas fa-arrow-left"></i> Kembali
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</section>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<!-- HTML5 QR Code Scanner Library -->
<script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>

<script>
let detailIndex = 0;
const addedProducts = new Set();
let html5QrCode = null;

$(function() {
    // Initialize Select2
    $('#productSelect').select2({
        placeholder: '-- Pilih Produk --',
        allowClear: true,
        width: '100%'
    });

    // Branch change event - reload products based on branch
    $('select[name="branch_id"]').on('change', function() {
        const branchId = $(this).val();

        // Clear product table when branch changes
        const tbody = document.getElementById('detailBody');
        if (tbody && detailIndex > 0) {
            tbody.innerHTML = '<tr class="text-center"><td colspan="6">Belum ada produk yang dipilih</td></tr>';
            addedProducts.clear();
            detailIndex = 0;
            updateCalculation(); // Reset total to 0
        }

        if (branchId) {
            loadProductsByBranch(branchId);
        } else {
            $('#productSelect').prop('disabled', true).html('<option value="">-- Pilih Cabang Terlebih Dahulu --</option>');
        }
    });

    // Product selection
    $('#productSelect').on('change', function() {
        const productId = $(this).val();
        if (!productId) return;

        // Check if supplier is selected first
        const supplierId = $('select[name="supplier_id"]').val();
        if (!supplierId) {
            alert('Silakan pilih supplier terlebih dahulu!');
            $(this).val('').trigger('change');
            return;
        }

        // Get selected branch
        const branchId = $('select[name="branch_id"]').val();
        if (!branchId) {
            alert('Silakan pilih cabang terlebih dahulu!');
            $(this).val('').trigger('change');
            return;
        }

        if (addedProducts.has(productId)) {
            alert('Produk sudah ditambahkan!');
            $(this).val('').trigger('change');
            return;
        }

        const option = $(this).find('option:selected');
        const productName = option.data('name');
        const productUnit = option.data('unit');
        const productStock = option.data('stock') || 0;

        // Fetch product price from server
        $.ajax({
            url: '<?php echo e(route("purchase.get-product-price")); ?>',
            method: 'GET',
            data: {
                product_id: productId,
                branch_id: branchId
            },
            success: function(response) {
                if (response.success) {
                    addProductRow(productId, productName, productStock, response.purchase_price);
                } else {
                    // If no price found, add with 0 and show warning
                    alert(response.message + '\nSilakan isi harga secara manual.');
                    addProductRow(productId, productName, productStock, 0);
                }
                addedProducts.add(productId);
            },
            error: function(xhr) {
                alert('Gagal mengambil harga produk. Silakan isi harga secara manual.');
                addProductRow(productId, productName, productStock, 0);
                addedProducts.add(productId);
            }
        });

        $(this).val('').trigger('change');
    });

    // ============================================
    // BARCODE SCAN FUNCTIONALITY
    // ============================================

    // Barcode input handler
    $('#barcodeInput').on('keypress', function(e) {
        if (e.which === 13) { // Enter key pressed
            e.preventDefault();
            const barcode = $(this).val().trim();

            if (!barcode) {
                alert('Masukkan barcode produk!');
                return;
            }

            const branchId = $('select[name="branch_id"]').val();
            if (!branchId) {
                alert('Pilih cabang terlebih dahulu!');
                return;
            }

            const supplierId = $('select[name="supplier_id"]').val();
            if (!supplierId) {
                alert('Pilih supplier terlebih dahulu!');
                return;
            }

            // Find product by barcode
            findProductByBarcode(barcode, branchId);

            // Clear input
            $(this).val('');
        }
    });

    // Auto focus to barcode input when scan tab is active
    $('#scan-tab').on('click', function() {
        setTimeout(function() {
            $('#barcodeInput').focus();
        }, 100);
    });

    // ============================================
    // CAMERA QR CODE SCANNER
    // ============================================

    // Start camera button
    $('#startCameraBtn').on('click', function() {
        const branchId = $('select[name="branch_id"]').val();
        if (!branchId) {
            alert('Silakan pilih cabang terlebih dahulu!');
            return;
        }

        const supplierId = $('select[name="supplier_id"]').val();
        if (!supplierId) {
            alert('Silakan pilih supplier terlebih dahulu!');
            return;
        }

        startQrScanner();
    });

    // Stop camera button
    $('#stopCameraBtn').on('click', function() {
        stopQrScanner();
    });

    // When leaving scan tab, stop camera
    $('#select-tab').on('click', function() {
        stopQrScanner();
    });
});

function addProductRow(productId, productName, stock, purchasePrice = 0) {
    const tbody = document.getElementById('detailBody');

    // Remove empty row
    if (detailIndex === 0) {
        tbody.innerHTML = '';
    }

    const subtotal = 1 * purchasePrice; // Default qty is 1

    const row = `
        <tr id="row-${detailIndex}">
            <td>
                ${productName}
                <input type="hidden" name="details[${detailIndex}][product_id]" value="${productId}">
            </td>
            <td class="text-center"><span class="badge badge-info">${stock}</span></td>
            <td>
                <input type="number" name="details[${detailIndex}][quantity]" class="form-control form-control-sm qty-input"
                    value="1" min="1" step="1" required data-index="${detailIndex}">
            </td>
            <td>
                <input type="number" name="details[${detailIndex}][purchase_price]" class="form-control form-control-sm price-input"
                    value="${purchasePrice}" min="0" step="0.01" required data-index="${detailIndex}">
            </td>
            <td class="text-right subtotal-cell" id="subtotal-${detailIndex}">
                <strong>Rp ${formatNumber(subtotal)}</strong>
            </td>
            <td class="text-center">
                <button type="button" class="btn btn-danger btn-sm" onclick="removeRow(${detailIndex}, '${productId}')">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `;

    tbody.insertAdjacentHTML('beforeend', row);
    detailIndex++;

    // Add event listeners for calculation
    updateCalculation();
    addCalculationListeners();
}

function removeRow(index, productId) {
    document.getElementById(`row-${index}`).remove();
    addedProducts.delete(productId);

    // If no rows, show empty message
    const tbody = document.getElementById('detailBody');
    if (tbody.children.length === 0) {
        tbody.innerHTML = '<tr class="text-center"><td colspan="6">Belum ada produk yang dipilih</td></tr>';
        detailIndex = 0;
    }

    updateCalculation();
}

function addCalculationListeners() {
    document.querySelectorAll('.qty-input, .price-input').forEach(input => {
        input.addEventListener('input', updateCalculation);
    });
}

function updateCalculation() {
    let total = 0;
    const tbody = document.getElementById('detailBody');
    const rows = tbody.querySelectorAll('tr');

    rows.forEach(row => {
        const qtyInput = row.querySelector('.qty-input');
        const priceInput = row.querySelector('.price-input');
        const subtotalCell = row.querySelector('.subtotal-cell');

        if (qtyInput && priceInput && subtotalCell) {
            const qty = parseFloat(qtyInput.value) || 0;
            const price = parseFloat(priceInput.value) || 0;
            const subtotal = qty * price;

            // Update subtotal cell
            subtotalCell.innerHTML = '<strong>Rp ' + formatNumber(subtotal) + '</strong>';

            total += subtotal;
        }
    });

    document.getElementById('totalAmount').textContent = 'Rp ' + formatNumber(total);

    // Enable/disable submit button
    const submitBtn = document.getElementById('submitBtn');
    submitBtn.disabled = total === 0;
}

function formatNumber(num) {
    return num.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}

function findProductByBarcode(barcode, branchId) {
    // Search product by barcode from database via API
    $.ajax({
        url: '<?php echo e(route("purchase.find-product-by-barcode")); ?>',
        method: 'GET',
        data: {
            barcode: barcode,
            branch_id: branchId
        },
        success: function(response) {
            if (response.success) {
                const product = response.product;
                const productId = product.id;
                const productName = product.name;
                const productStock = product.stock || 0;
                const purchasePrice = product.purchase_price;

                // Check if product already added
                if (addedProducts.has(productId)) {
                    alert('Produk "' + productName + '" sudah ditambahkan!');
                    return;
                }

                // Add product to table
                addProductRow(productId, productName, productStock, purchasePrice);
                addedProducts.add(productId);

                // Show success notification
                showNotification('success', 'Produk "' + productName + '" berhasil ditambahkan!');
            } else {
                alert(response.message);
            }
        },
        error: function(xhr) {
            if (xhr.status === 404) {
                const response = JSON.parse(xhr.responseText);
                alert(response.message);
            } else {
                alert('Gagal mengambil data produk. Silakan coba lagi.');
            }
        }
    });
}

function showNotification(type, message) {
    // Simple notification (you can replace with better notification library)
    const bgColor = type === 'success' ? '#28a745' : '#dc3545';
    const notification = $('<div>')
        .css({
            position: 'fixed',
            top: '20px',
            right: '20px',
            backgroundColor: bgColor,
            color: 'white',
            padding: '15px 20px',
            borderRadius: '5px',
            zIndex: 9999,
            boxShadow: '0 4px 6px rgba(0,0,0,0.1)'
        })
        .text(message)
        .appendTo('body');

    setTimeout(function() {
        notification.fadeOut(300, function() {
            $(this).remove();
        });
    }, 3000);
}

function startQrScanner() {
    const branchId = $('select[name="branch_id"]').val();

    if (!branchId) {
        alert('Silakan pilih cabang terlebih dahulu!');
        return;
    }

    // Show camera preview
    $('#qr-reader').show();
    $('#startCameraBtn').hide();
    $('#stopCameraBtn').show();

    // Initialize QR Code scanner
    html5QrCode = new Html5Qrcode("qr-reader");

    const config = {
        fps: 10,
        qrbox: { width: 250, height: 250 }
    };

    html5QrCode.start(
        { facingMode: "environment" }, // Use back camera
        config,
        (decodedText, decodedResult) => {
            // QR Code successfully scanned
            console.log(`QR Code detected: ${decodedText}`);

            // Process the scanned barcode
            findProductByBarcode(decodedText, branchId);

            // Stop scanner after successful scan
            stopQrScanner();
        },
        (errorMessage) => {
            // Scan error (can be ignored, happens during scanning)
        }
    ).catch((err) => {
        console.error('Error starting QR scanner:', err);
        alert('Gagal mengaktifkan kamera. Pastikan Anda memberikan izin akses kamera.');
        stopQrScanner();
    });
}

function stopQrScanner() {
    if (html5QrCode) {
        html5QrCode.stop().then(() => {
            html5QrCode.clear();
            html5QrCode = null;
            $('#qr-reader').hide();
            $('#startCameraBtn').show();
            $('#stopCameraBtn').hide();
        }).catch((err) => {
            console.error('Error stopping QR scanner:', err);
            $('#qr-reader').hide();
            $('#startCameraBtn').show();
            $('#stopCameraBtn').hide();
        });
    } else {
        $('#qr-reader').hide();
        $('#startCameraBtn').show();
        $('#stopCameraBtn').hide();
    }
}

function loadProductsByBranch(branchId) {
    $.ajax({
        url: '<?php echo e(route("purchase.get-products-by-branch")); ?>',
        method: 'GET',
        data: { branch_id: branchId },
        beforeSend: function() {
            $('#productSelect').prop('disabled', true).html('<option value="">Loading...</option>');
        },
        success: function(response) {
            if (response.success) {
                let options = '<option value="">-- Pilih Produk --</option>';
                response.products.forEach(function(product) {
                    // Format: 4 digit code + name + brand + unit
                    const code = String(product.id).padStart(4, '0');
                    const stock = product.stock || 0;
                    options += `<option value="${product.id}" data-name="${product.name}" data-unit="${product.unit}" data-stock="${stock}">
                        ${code} - ${product.name} - ${product.brand_name} (Stok: ${stock})
                    </option>`;
                });
                $('#productSelect').html(options).prop('disabled', false).trigger('change');
            } else {
                alert('Gagal memuat produk');
                $('#productSelect').html('<option value="">-- Pilih Produk --</option>').prop('disabled', false);
            }
        },
        error: function() {
            alert('Terjadi kesalahan saat memuat produk');
            $('#productSelect').html('<option value="">-- Pilih Produk --</option>').prop('disabled', false);
        }
    });
}
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp82\htdocs\umi-cell\resources\views/transaction/purchase/create.blade.php ENDPATH**/ ?>