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

<?php $__env->startSection('content'); ?>
<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1>Data 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 active">Pembelian</li>
                </ol>
            </div>
        </div>
    </div>
</section>

<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Daftar Pembelian</h3>
                        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('purchases.create')): ?>
                        <div class="card-tools">
                            <button type="button" class="btn btn-primary btn-sm mr-1" data-toggle="modal" data-target="#scanQrModal">
                                <i class="fas fa-qrcode"></i> Scan QR Code
                            </button>
                            <a href="<?php echo e(route('purchase.create')); ?>" class="btn btn-success btn-sm">
                                <i class="fas fa-plus"></i> Tambah Pembelian
                            </a>
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="card-body">
                        <?php if(session('success')): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo e(session('success')); ?>

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

                        <?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; ?>

                        <table id="example1" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th style="width: 5%;">No</th>
                                    <th>No. Pembelian</th>
                                    <th>Tanggal</th>
                                    <th>Supplier</th>
                                    <th>Cabang</th>
                                    <th>Total</th>
                                    <th>Status</th>
                                    <th>User</th>
                                    <th style="width: 15%;">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $__currentLoopData = $purchases; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $purchase): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <tr>
                                    <td><?php echo e($index + 1); ?></td>
                                    <td><?php echo e($purchase->purchase_number); ?></td>
                                    <td><?php echo e(TanggalID($purchase->purchase_date)); ?></td>
                                    <td><?php echo e($purchase->supplier->name); ?></td>
                                    <td><?php echo e($purchase->branch->name); ?></td>
                                    <td class="text-right">Rp <?php echo e(number_format($purchase->total_amount, 0, ',', '.')); ?></td>
                                    <td>
                                        <?php if($purchase->status == 'pending'): ?>
                                        <span class="badge badge-warning">Pending</span>
                                        <?php elseif($purchase->status == 'completed'): ?>
                                        <span class="badge badge-success">Selesai</span>
                                        <?php else: ?>
                                        <span class="badge badge-danger">Batal</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo e($purchase->user->name); ?></td>
                                    <td>
                                        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('purchases.index')): ?>
                                        <a href="<?php echo e(route('purchase.show', $purchase->id)); ?>" class="btn btn-info btn-sm" title="Detail">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <?php endif; ?>

                                        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('purchases.edit')): ?>
                                        
                                        <a href="<?php echo e(route('purchase.edit', $purchase->id)); ?>" class="btn btn-primary btn-sm" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        
                                        <?php endif; ?>

                                        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('purchases.delete')): ?>
                                        
                                        <form action="<?php echo e(route('purchase.delete', $purchase->id)); ?>" method="POST" style="display:inline;" class="delete-form-<?php echo e($purchase->id); ?>">
                                            <?php echo csrf_field(); ?>
                                            <?php echo method_field('DELETE'); ?>
                                            <button type="button" class="btn btn-danger btn-sm delete" data-id="<?php echo e($purchase->id); ?>" data-name="Pembelian <?php echo e($purchase->purchase_number); ?>" title="Hapus">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                        
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Modal Scan QR Code -->
<div class="modal fade" id="scanQrModal" tabindex="-1" role="dialog" aria-labelledby="scanQrModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="scanQrModalLabel">
                    <i class="fas fa-qrcode"></i> Scan QR Code Pembelian
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- Tab Navigation -->
                <ul class="nav nav-tabs mb-3" id="scanTab" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link active" id="manual-scan-tab" data-toggle="tab" href="#manualScan" role="tab">
                            <i class="fas fa-keyboard"></i> Input Manual
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="camera-scan-tab" data-toggle="tab" href="#cameraScan" role="tab">
                            <i class="fas fa-camera"></i> Scan dengan Kamera
                        </a>
                    </li>
                </ul>

                <!-- Tab Content -->
                <div class="tab-content" id="scanTabContent">
                    <!-- Manual Input Tab -->
                    <div class="tab-pane fade show active" id="manualScan" role="tabpanel">
                        <div class="form-group">
                            <label><i class="fas fa-qrcode"></i> Scan atau Ketik QR Code Pembelian</label>
                            <input type="text" id="barcodeInputIndex" class="form-control form-control-lg"
                                placeholder="Scan QR Code atau ketik QR Code pembelian..." autofocus>
                            <small class="form-text text-muted">
                                <i class="fas fa-info-circle"></i> Gunakan QR Code scanner atau ketik QR Code pembelian, tekan Enter untuk mencari
                            </small>
                        </div>
                    </div>

                    <!-- Camera Scan Tab -->
                    <div class="tab-pane fade" id="cameraScan" role="tabpanel">
                        <div class="text-center mb-3">
                            <button type="button" id="startCameraBtnIndex" class="btn btn-success btn-lg">
                                <i class="fas fa-camera"></i> Aktifkan Kamera untuk Scan QR Code
                            </button>
                            <button type="button" id="stopCameraBtnIndex" class="btn btn-danger btn-lg" style="display: none;">
                                <i class="fas fa-stop"></i> Matikan Kamera
                            </button>
                        </div>
                        <div id="qr-reader-index" style="display: none; width: 100%; max-width: 600px; margin: 0 auto;"></div>
                        <div id="qr-reader-results-index" class="mt-2"></div>
                    </div>
                </div>

                <!-- Purchase Result -->
                <div id="purchaseResult" class="mt-3" style="display: none;">
                    <div class="alert alert-success">
                        <h5><i class="fas fa-check-circle"></i> Pembelian Ditemukan!</h5>
                        <div id="purchaseInfo"></div>
                        <div class="mt-3">
                            <a href="#" id="goToDetailBtn" class="btn btn-primary">
                                <i class="fas fa-eye"></i> Lihat Detail Pembelian
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Not Found Result -->
                <div id="notFoundResult" class="mt-3" style="display: none;">
                    <div class="alert alert-danger">
                        <h5><i class="fas fa-times-circle"></i> Pembelian Tidak Ditemukan</h5>
                        <p class="mb-0">QR Code yang di-scan tidak terdaftar di sistem.</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                    <i class="fas fa-times"></i> Tutup
                </button>
            </div>
        </div>
    </div>
</div>
<?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 html5QrCodeIndex = null;

$(function() {
    // Reset modal when opened
    $('#scanQrModal').on('shown.bs.modal', function () {
        $('#barcodeInputIndex').focus();
        $('#purchaseResult').hide();
        $('#notFoundResult').hide();
        $('#barcodeInputIndex').val('');
    });

    // Reset camera when modal closed
    $('#scanQrModal').on('hidden.bs.modal', function () {
        stopQrScannerIndex();
        $('#purchaseResult').hide();
        $('#notFoundResult').hide();
        $('#barcodeInputIndex').val('');
    });

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

            if (!barcode) {
                alert('Masukkan QR Code pembelian!');
                return;
            }

            // Find purchase by barcode
            findPurchaseByBarcodeIndex(barcode);
        }
    });

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

    // Start camera button
    $('#startCameraBtnIndex').on('click', function() {
        startQrScannerIndex();
    });

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

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

function findPurchaseByBarcodeIndex(barcode) {
    // Show loading
    $('#purchaseResult').hide();
    $('#notFoundResult').hide();

    $.ajax({
        url: '<?php echo e(route("purchase.find-purchase-by-barcode")); ?>',
        method: 'GET',
        data: { barcode: barcode },
        success: function(response) {
            if (response.success && response.purchase) {
                const purchase = response.purchase;

                // Display purchase info
                const purchaseHtml = `
                    <table class="table table-sm table-bordered">
                        <tr>
                            <th style="width: 30%;">No. Pembelian</th>
                            <td><strong>${purchase.purchase_number}</strong></td>
                        </tr>
                        <tr>
                            <th>QR Code</th>
                            <td><code>${purchase.barcode}</code></td>
                        </tr>
                        <tr>
                            <th>Supplier</th>
                            <td>${purchase.supplier_name}</td>
                        </tr>
                        <tr>
                            <th>Cabang</th>
                            <td>${purchase.branch_name}</td>
                        </tr>
                        <tr>
                            <th>Tanggal Pembelian</th>
                            <td>${purchase.purchase_date}</td>
                        </tr>
                        <tr>
                            <th>Total</th>
                            <td><strong>Rp ${formatNumber(purchase.total_amount)}</strong></td>
                        </tr>
                        <tr>
                            <th>Status</th>
                            <td><span class="badge badge-${purchase.status === 'completed' ? 'success' : 'warning'}">${purchase.status.toUpperCase()}</span></td>
                        </tr>
                        <tr>
                            <th>User</th>
                            <td>${purchase.user_name}</td>
                        </tr>
                    </table>
                `;

                $('#purchaseInfo').html(purchaseHtml);
                $('#purchaseResult').show();

                // Set link to detail page
                $('#goToDetailBtn').attr('href', '<?php echo e(url("admin/purchase")); ?>/' + purchase.id);

            } else {
                $('#notFoundResult').show();
            }
        },
        error: function(xhr) {
            $('#notFoundResult').show();
            console.error('Error finding purchase:', xhr);
        }
    });
}

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

function startQrScannerIndex() {
    // Show camera preview
    $('#qr-reader-index').show();
    $('#startCameraBtnIndex').hide();
    $('#stopCameraBtnIndex').show();

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

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

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

            // Process the scanned barcode
            findPurchaseByBarcodeIndex(decodedText);

            // Stop scanner after successful scan
            stopQrScannerIndex();
        },
        (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.');
        stopQrScannerIndex();
    });
}

function stopQrScannerIndex() {
    if (html5QrCodeIndex) {
        html5QrCodeIndex.stop().then(() => {
            html5QrCodeIndex.clear();
            html5QrCodeIndex = null;
            $('#qr-reader-index').hide();
            $('#startCameraBtnIndex').show();
            $('#stopCameraBtnIndex').hide();
        }).catch((err) => {
            console.error('Error stopping QR scanner:', err);
            $('#qr-reader-index').hide();
            $('#startCameraBtnIndex').show();
            $('#stopCameraBtnIndex').hide();
        });
    } else {
        $('#qr-reader-index').hide();
        $('#startCameraBtnIndex').show();
        $('#stopCameraBtnIndex').hide();
    }
}
</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\laravel\resources\views/transaction/purchase/index.blade.php ENDPATH**/ ?>