@section('heading', 'Tambah Penjualan')
@extends('layouts.app')
@section('content')
<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1>Tambah Penjualan</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="{{route('home')}}">Home</a></li>
                    <li class="breadcrumb-item"><a href="{{route('sale')}}">Penjualan</a></li>
                    <li class="breadcrumb-item active">Tambah</li>
                </ol>
            </div>
        </div>
    </div>
</section>

<section class="content">
    <div class="container-fluid">
        <form action="{{route('sale.save')}}" method="POST" id="saleForm">
            @csrf
            <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: 10%;">Stok</th>
                                            <th style="width: 10%;">Qty</th>
                                            <th style="width: 15%;">Harga</th>
                                            <th style="width: 10%;">Diskon</th>
                                            <th style="width: 20%;">Subtotal</th>
                                            <th style="width: 5%;">Aksi</th>
                                        </tr>
                                    </thead>
                                    <tbody id="detailBody">
                                        <tr class="text-center">
                                            <td colspan="7">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 Penjualan</h3>
                        </div>
                        <div class="card-body">
                            @if(session('error'))
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                {{ session('error') }}
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            @endif

                            <div class="form-group">
                                <label>No. Penjualan</label>
                                <input type="text" class="form-control" value="{{$saleNumber}}" readonly>
                            </div>

                            <div class="form-group">
                                <label>Cabang <span class="text-danger">*</span></label>
                                <select name="branch_id" id="branchSelect" class="form-control @error('branch_id') is-invalid @enderror" required>
                                    <option value="">-- Pilih Cabang --</option>
                                    @foreach($branches as $branch)
                                    <option value="{{$branch->id}}" {{old('branch_id') == $branch->id ? 'selected' : ''}}>
                                        {{$branch->name}}
                                    </option>
                                    @endforeach
                                </select>
                                @error('branch_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="form-group">
                                <label>Customer</label>
                                <select name="customer_id" class="form-control @error('customer_id') is-invalid @enderror">
                                    <option value="">-- Umum --</option>
                                    @foreach($customers as $customer)
                                    <option value="{{$customer->id}}" {{old('customer_id') == $customer->id ? 'selected' : ''}}>
                                        {{$customer->name}}
                                    </option>
                                    @endforeach
                                </select>
                                @error('customer_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="form-group">
                                <label>Tanggal Penjualan <span class="text-danger">*</span></label>
                                <input type="date" name="sale_date" class="form-control @error('sale_date') is-invalid @enderror"
                                    value="{{old('sale_date', date('Y-m-d'))}}" required>
                                @error('sale_date')
                                <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="form-group">
                                <label>Metode Pembayaran <span class="text-danger">*</span></label>
                                <select name="payment_method" class="form-control @error('payment_method') is-invalid @enderror" required>
                                    <option value="cash" {{old('payment_method') == 'cash' ? 'selected' : ''}}>Tunai</option>
                                    <option value="transfer" {{old('payment_method') == 'transfer' ? 'selected' : ''}}>Transfer</option>
                                    <option value="credit" {{old('payment_method') == 'credit' ? 'selected' : ''}}>Kredit</option>
                                </select>
                                @error('payment_method')
                                <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="form-group">
                                <label>Catatan</label>
                                <textarea name="notes" class="form-control" rows="2">{{old('notes')}}</textarea>
                            </div>

                            <hr>

                            <div class="form-group">
                                <label>Subtotal</label>
                                <h4 id="subtotalAmount">Rp 0</h4>
                            </div>

                            <div class="form-group">
                                <label>Diskon</label>
                                <input type="number" name="discount" id="discountInput" class="form-control" value="0" min="0" step="0.01">
                            </div>

                            <div class="form-group">
                                <label>Pajak</label>
                                <input type="number" name="tax" id="taxInput" class="form-control" value="0" min="0" step="0.01">
                            </div>

                            <div class="form-group">
                                <label>Total Pembayaran</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" disabled>
                                <i class="fas fa-save"></i> Simpan Penjualan
                            </button>
                            <a href="{{route('sale')}}" class="btn btn-secondary btn-block">
                                <i class="fas fa-arrow-left"></i> Kembali
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</section>
@endsection

@push('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 Map();
const productStocks = new Map();
let html5QrCode = null;

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

    const branchSelect = $('#branchSelect');
    const productSelect = $('#productSelect');

    // Branch selection change - reload products based on branch
    branchSelect.on('change', function() {
        const branchId = $(this).val();

        // Clear product selection
        productSelect.val('').trigger('change');

        // Clear added products
        const detailBody = $('#detailBody');
        detailBody.html('<tr class="text-center"><td colspan="7">Belum ada produk yang dipilih</td></tr>');
        addedProducts.clear();
        productStocks.clear();
        detailIndex = 0;
        updateCalculation();

        // Load products based on selected branch
        if (branchId) {
            loadProductsByBranch(branchId);
        } else {
            productSelect.prop('disabled', true).html('<option value="">-- Pilih Cabang Terlebih Dahulu --</option>');
        }
    });

    // Product selection - Auto add when product is selected
    productSelect.on('change', function() {
        const productId = $(this).val();

        if (!productId) {
            return;
        }

        const branchId = branchSelect.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');

        // Fetch product data (stock and price) from server
        $.ajax({
            url: '{{ route("sale.get-product-data") }}',
            method: 'GET',
            data: {
                product_id: productId,
                branch_id: branchId
            },
            success: function(response) {
                if (response.success) {
                    const stock = response.stock;
                    const purchasePrice = response.purchase_price;
                    const sellingPrice = response.selling_price;

                    if (stock <= 0) {
                        alert('Stok produk tidak tersedia di cabang ini!');
                        productSelect.val('').trigger('change');
                        return;
                    }

                    addProductRow(productId, productName, productUnit, stock, purchasePrice, sellingPrice);
                    addedProducts.set(productId, true);
                    productStocks.set(productId, stock);
                } else {
                    alert(response.message);
                }
                productSelect.val('').trigger('change');
            },
            error: function(xhr) {
                alert('Gagal mengambil data produk. Silakan coba lagi.');
                productSelect.val('').trigger('change');
            }
        });
    });

    // Discount and tax inputs
    $('#discountInput').on('input', updateCalculation);
    $('#taxInput').on('input', updateCalculation);

    // ============================================
    // 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 = $('#branchSelect').val();
            if (!branchId) {
                alert('Pilih cabang 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 = $('#branchSelect').val();
        if (!branchId) {
            alert('Silakan pilih cabang 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, productUnit, stock, purchasePrice, sellingPrice) {
    const tbody = document.getElementById('detailBody');

    if (detailIndex === 0) {
        tbody.innerHTML = '';
    }

    const currentIndex = detailIndex;
    const initialSubtotal = 1 * sellingPrice; // Default qty = 1, discount = 0

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

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

    addCalculationListeners();
    updateCalculation();
}

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

    const tbody = document.getElementById('detailBody');
    if (tbody.children.length === 0) {
        tbody.innerHTML = '<tr class="text-center"><td colspan="7">Belum ada produk yang dipilih</td></tr>';
        detailIndex = 0;
    }

    updateCalculation();
}

function addCalculationListeners() {
    document.querySelectorAll('.qty-input, .price-input, .discount-input').forEach(input => {
        input.addEventListener('input', function() {
            const index = this.dataset.index;
            updateRowSubtotal(index);
            updateCalculation();
        });
    });
}

function updateRowSubtotal(index) {
    const row = document.getElementById(`row-${index}`);
    if (!row) return;

    const qtyInput = row.querySelector('.qty-input');
    const priceInput = row.querySelector('.price-input');
    const discountInput = row.querySelector('.discount-input');
    const subtotalCell = document.getElementById(`subtotal-${index}`);

    const qty = parseFloat(qtyInput.value) || 0;
    const price = parseFloat(priceInput.value) || 0;
    const discount = parseFloat(discountInput.value) || 0;

    const subtotal = (qty * price) - discount;
    subtotalCell.innerHTML = '<strong>Rp ' + formatNumber(subtotal) + '</strong>';
}

function updateCalculation() {
    let subtotal = 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 discountInput = row.querySelector('.discount-input');

        if (qtyInput && priceInput) {
            const qty = parseFloat(qtyInput.value) || 0;
            const price = parseFloat(priceInput.value) || 0;
            const discount = parseFloat(discountInput.value) || 0;
            subtotal += (qty * price) - discount;
        }
    });

    const globalDiscount = parseFloat(document.getElementById('discountInput').value) || 0;
    const tax = parseFloat(document.getElementById('taxInput').value) || 0;
    const total = subtotal - globalDiscount + tax;

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

    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: '{{ route("sale.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 productUnit = product.unit;
                const stock = product.stock;
                const purchasePrice = product.purchase_price;
                const sellingPrice = product.selling_price;

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

                // Add product to table
                addProductRow(productId, productName, productUnit, stock, purchasePrice, sellingPrice);
                addedProducts.set(productId, true);
                productStocks.set(productId, stock);

                // 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 = $('#branchSelect').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: '{{ route("sale.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 + stock
                    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-barcode="">
                        ${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>
@endpush
