@section('heading', '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>Data 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 active">Penjualan</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 Penjualan</h3>
                        @can('sales.create')
                        <div class="card-tools">
                            <button type="button" class="btn btn-primary btn-sm mr-1" data-toggle="modal" data-target="#scanQrCodeModal">
                                <i class="fas fa-qrcode"></i> Scan QR Code
                            </button>
                            <a href="{{route('sale.create')}}" class="btn btn-success btn-sm">
                                <i class="fas fa-plus"></i> Tambah Penjualan
                            </a>
                        </div>
                        @endcan
                    </div>
                    <div class="card-body">
                        @if(session('success'))
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            {{ session('success') }}
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        @endif

                        @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

                        <table id="example1" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th style="width: 5%;">No</th>
                                    <th>No. Penjualan</th>
                                    <th>Tanggal</th>
                                    <th>Customer</th>
                                    <th>Cabang</th>
                                    <th>Total</th>
                                    <th>Metode Bayar</th>
                                    <th>Status</th>
                                    <th>Kasir</th>
                                    <th style="width: 15%;">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($sales as $index => $sale)
                                <tr>
                                    <td>{{$index + 1}}</td>
                                    <td>{{$sale->sale_number}}</td>
                                    <td>{{TanggalID($sale->sale_date)}}</td>
                                    <td>{{$sale->customer ? $sale->customer->name : 'Umum'}}</td>
                                    <td>{{$sale->branch->name}}</td>
                                    <td class="text-right">Rp {{number_format($sale->total_amount, 0, ',', '.')}}</td>
                                    <td>
                                        @if($sale->payment_method == 'cash')
                                        <span class="badge badge-success">Tunai</span>
                                        @elseif($sale->payment_method == 'transfer')
                                        <span class="badge badge-info">Transfer</span>
                                        @else
                                        <span class="badge badge-warning">Kredit</span>
                                        @endif
                                    </td>
                                    <td>
                                        @if($sale->status == 'pending')
                                        <span class="badge badge-warning">Pending</span>
                                        @elseif($sale->status == 'completed')
                                        <span class="badge badge-success">Selesai</span>
                                        @else
                                        <span class="badge badge-danger">Batal</span>
                                        @endif
                                    </td>
                                    <td>{{$sale->cashier->name}}</td>
                                    <td>
                                        @can('sales.index')
                                        <a href="{{route('sale.show', $sale->id)}}" class="btn btn-info btn-sm" title="Detail">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        @endcan

                                        @can('sales.edit')
                                        {{-- @if($sale->status == 'pending') --}}
                                        <a href="{{route('sale.edit', $sale->id)}}" class="btn btn-primary btn-sm" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        {{-- @endif --}}
                                        @endcan

                                        @can('sales.delete')
                                        {{-- @if($sale->status == 'pending') --}}
                                        <form action="{{ route('sale.delete', $sale->id) }}" method="POST" style="display:inline;" class="delete-form-{{ $sale->id }}">
                                            @csrf
                                            @method('DELETE')
                                            <button type="button" class="btn btn-danger btn-sm delete" data-id="{{ $sale->id }}" data-name="Penjualan {{ $sale->sale_number }}" title="Hapus">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                        {{-- @endif --}}
                                        @endcan
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Modal Scan QR Code -->
<div class="modal fade" id="scanQrCodeModal" 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 Penjualan
                </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 Penjualan</label>
                            <input type="text" id="barcodeInputIndex" class="form-control form-control-lg"
                                placeholder="Scan QR Code atau ketik QR Code penjualan..." autofocus>
                            <small class="form-text text-muted">
                                <i class="fas fa-info-circle"></i> Gunakan QR Code scanner atau ketik QR Code penjualan, 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>

                <!-- Sale Result -->
                <div id="saleResult" class="mt-3" style="display: none;">
                    <div class="alert alert-success">
                        <h5><i class="fas fa-check-circle"></i> Penjualan Ditemukan!</h5>
                        <div id="saleInfo"></div>
                        <div class="mt-3">
                            <a href="#" id="goToDetailBtn" class="btn btn-primary">
                                <i class="fas fa-eye"></i> Lihat Detail Penjualan
                            </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> Penjualan 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>

@push('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
    $('#scanQrCodeModal').on('shown.bs.modal', function () {
        $('#barcodeInputIndex').focus();
        $('#saleResult').hide();
        $('#notFoundResult').hide();
        $('#barcodeInputIndex').val('');
    });

    // Reset camera when modal closed
    $('#scanQrCodeModal').on('hidden.bs.modal', function () {
        stopQrScannerIndex();
        $('#saleResult').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 penjualan!');
                return;
            }

            // Find sale by barcode
            findSaleByBarcodeIndex(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 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
            findSaleByBarcodeIndex(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();
    }
}

function findSaleByBarcodeIndex(barcode) {
    // Show loading
    $('#saleResult').hide();
    $('#notFoundResult').hide();

    $.ajax({
        url: '{{ route("sale.find-sale-by-barcode") }}',
        method: 'GET',
        data: { barcode: barcode },
        success: function(response) {
            if (response.success && response.sale) {
                const sale = response.sale;

                // Display sale info
                const saleHtml = `
                    <table class="table table-sm table-bordered">
                        <tr>
                            <th style="width: 30%;">No. Penjualan</th>
                            <td><strong>${sale.sale_number}</strong></td>
                        </tr>
                        <tr>
                            <th>QR Code</th>
                            <td><code>${sale.barcode}</code></td>
                        </tr>
                        <tr>
                            <th>Customer</th>
                            <td>${sale.customer_name}</td>
                        </tr>
                        <tr>
                            <th>Cabang</th>
                            <td>${sale.branch_name}</td>
                        </tr>
                        <tr>
                            <th>Kasir</th>
                            <td>${sale.cashier_name}</td>
                        </tr>
                        <tr>
                            <th>Tanggal Penjualan</th>
                            <td>${sale.sale_date}</td>
                        </tr>
                        <tr>
                            <th>Total</th>
                            <td><strong>Rp ${sale.total_amount}</strong></td>
                        </tr>
                        <tr>
                            <th>Metode Bayar</th>
                            <td><span class="badge badge-info">${sale.payment_method.toUpperCase()}</span></td>
                        </tr>
                        <tr>
                            <th>Status</th>
                            <td><span class="badge badge-${sale.status === 'completed' ? 'success' : 'warning'}">${sale.status.toUpperCase()}</span></td>
                        </tr>
                    </table>
                `;

                $('#saleInfo').html(saleHtml);
                $('#saleResult').show();

                // Set link to detail page
                $('#goToDetailBtn').attr('href', sale.url);

            } else {
                $('#notFoundResult').show();
            }
        },
        error: function(xhr) {
            $('#notFoundResult').show();
            console.error('Error finding sale:', xhr);
        }
    });
}
</script>
@endpush
@endsection
