
<?php $__env->startSection('title'); ?>
<?php echo $variables['header_routes']; ?>

<?php $__env->stopSection(); ?>
<?php $__env->startSection('content'); ?>
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card card-outline card-warning">
                    <div class="card-header">
                        <h3 class="card-title"><?php echo e($variables['judul']); ?></h3>
                        <div class="card-tools">
                            <?php if($data->status == 'Draft'): ?>
                            <a href="<?php echo e(route('stock_opnames.edit', $data->id)); ?>" class="btn btn-sm btn-warning button-cek-permission" data-permission="stock_opnames.edit">
                                <i class="fas fa-edit"></i> Ubah
                            </a>
                            <a href="<?php echo e(route('stock_opnames.destroy', $data->id)); ?>" class="btn btn-sm btn-warning button-cek-permission" data-permission="stock_opnames.destroy" data='delete' onclick="notificationBeforeDelete(event, this)">
                                <i class="fas fa-trash"></i> Hapus
                            </a>
                            <?php endif; ?>
                            <?php if($data->isBeingEdited()): ?>
                            <button type="button" id="forceUnlockBtn" class="btn btn-sm btn-danger button-cek-permission" data-permission="stock_opnames.force_unlock" data-so-id="<?php echo e($data->id); ?>">
                                <i class="fas fa-unlock"></i> Force Unlock
                            </button>
                            <?php endif; ?>
                            <?php if($data->status == 'Submitted'): ?>
                            <button type="button" id="generateSPBBtn" class="btn btn-sm btn-warning button-cek-permission" data-permission="item_requests.create" data-so-id="<?php echo e($data->id); ?>">
                                <i class="fas fa-magic"></i> Generate SPB Regular
                            </button>
                            <?php endif; ?>
                            <a href="<?php echo e(route('stock_opnames.index')); ?>" class="btn btn-sm btn-warning">
                                <i class="fas fa-arrow-left"></i> Kembali
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- Stock Opname Header Info -->
                        <div class="row">
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <td width="35%"><strong>Nomor SO</strong></td>
                                        <td>: <span class="badge badge-info"><?php echo e($data->so_number); ?></span></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Store</strong></td>
                                        <td>: <?php echo e($data->store->name ?? '-'); ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Tanggal SO</strong></td>
                                        <td>: <?php echo e($data->so_date->format('d/m/Y')); ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Status</strong></td>
                                        <td>: 
                                            <?php if($data->status == 'Draft'): ?>
                                            <span class="badge badge-secondary"><?php echo e($data->status); ?></span>
                                            <?php elseif($data->status == 'Submitted'): ?>
                                            <span class="badge badge-success"><?php echo e($data->status); ?></span>
                                            <?php else: ?>
                                            <span class="badge badge-secondary"><?php echo e($data->status); ?></span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php if($data->isBeingEdited()): ?>
                                    <?php
                                    $editingInfo = $data->getEditingInfo();
                                    ?>
                                    <tr>
                                        <td><strong>Sedang Diedit</strong></td>
                                        <td>: 
                                            <span class="badge badge-danger">
                                                <i class="fas fa-edit"></i> <?php echo e($editingInfo['user']); ?>

                                            </span>
                                            <br><small class="text-muted"><?php echo e($editingInfo['since']); ?></small>
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <td width="35%"><strong>Dibuat Oleh</strong></td>
                                        <td>: <?php echo e($data->creator->fullname ?? 'System'); ?> (<?php echo e($data->created_at->format('d/m/Y H:i')); ?>)</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Diubah Oleh</strong></td>
                                        <td>: <?php echo e($data->modificator->fullname ?? 'System'); ?> (<?php echo e($data->updated_at ? $data->updated_at->format('d/m/Y H:i') : '-'); ?>)</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Total Item</strong></td>
                                        <td>: <?php echo e(count($data->details)); ?> item</td>
                                    </tr>
                                </table>
                            </div>
                        </div>

                        <?php if($data->notes): ?>
                        <div class="row">
                            <div class="col-12">
                                <table class="table table-borderless">
                                    <tr>
                                        <td width="17.5%"><strong>Catatan</strong></td>
                                        <td>: <?php echo e($data->notes); ?></td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if($data->status == 'Submitted'): ?>
                        <!-- SPB Generation Info -->
                        <div class="row mt-3">
                            <div class="col-12">
                                <div class="alert alert-info" id="spbGenerationInfo" style="background-color: #17a2b8; border-color: #17a2b8; color: white;">
                                    <h5 style="color: white;"><i class="fas fa-info-circle"></i> Informasi Generate SPB</h5>
                                    <p class="mb-2" style="color: white;">Jika tombol <strong>"Generate SPB Regular"</strong> diklik, sistem akan membuat SPB berdasarkan pengelompokan:</p>
                                    <div id="spbGroupingPreview">
                                        <div class="text-center">
                                            <i class="fas fa-spinner fa-spin"></i> Memuat informasi pengelompokan...
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>

                        <!-- Items Details -->
                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-header card-outline card-warning">
                                        <h5 class="mb-0">Item Stock Opname</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-hover table-sm">
                                                <thead class="bg-warning">
                                                    <tr>
                                                        <th width="5%">No</th>
                                                        <th width="12%">Kode</th>
                                                        <th width="20%">Item</th>
                                                        <th width="8%">UOM</th>
                                                        <th width="10%">Qty Utuh</th>
                                                        <th width="10%">Qty Pakai</th>
                                                        <th width="8%">Konversi</th>
                                                        <th width="10%">Qty Terkonversi</th>
                                                        <th width="10%">Ending Stock</th>
                                                        <th width="17%">Catatan</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php $__empty_1 = true; $__currentLoopData = $data->details; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $detail): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                                    <tr>
                                                        <td><?php echo e($index + 1); ?></td>
                                                        <td><?php echo e($detail->rawMaterial->code ?? ''); ?></td>
                                                        <td><?php echo e($detail->rawMaterial->name ?? ''); ?></td>
                                                        <td><?php echo e($detail->rawMaterial->uom ?? ''); ?></td>
                                                        <td class="text-right"><?php echo e(number_format($detail->qty_utuh, 2)); ?></td>
                                                        <td class="text-right"><?php echo e(number_format($detail->qty_pakai, 2)); ?></td>
                                                        <td class="text-right"><?php echo e(number_format($detail->rawMaterial->conversion_factor ?? 1, 4)); ?></td>
                                                        <td class="text-right"><?php echo e(number_format($detail->qty_converted, 2)); ?></td>
                                                        <td class="text-right"><strong><?php echo e(number_format($detail->lsm_aktual, 2)); ?></strong></td>
                                                        <td><?php echo e($detail->notes ?? '-'); ?></td>
                                                    </tr>
                                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                                    <tr>
                                                        <td colspan="10" class="text-center text-muted">Tidak ada item ditemukan</td>
                                                    </tr>
                                                    <?php endif; ?>
                                                </tbody>
                                                <?php if(count($data->details) > 0): ?>
                                                <tfoot class="bg-light">
                                                    <tr>
                                                        <th colspan="8" class="text-right">Total Item:</th>
                                                        <th class="text-right"><?php echo e(count($data->details)); ?></th>
                                                        <th></th>
                                                    </tr>
                                                </tfoot>
                                                <?php endif; ?>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<form action="" id="delete-form" method="post">
    <?php echo method_field('delete'); ?>
    <?php echo csrf_field(); ?>
</form>

<script>
$(document).ready(function() {
    // Load SPB Grouping Preview (only if status is Submitted)
    <?php if($data->status == 'Submitted'): ?>
    loadSPBGroupingPreview();
    <?php endif; ?>

    function loadSPBGroupingPreview() {
        const soId = <?php echo e($data->id); ?>;
        
        $.ajax({
            url: `/stock_opnames/${soId}/preview_spb_grouping`,
            type: 'GET',
            success: function(response) {
                if (response.success) {
                    let html = '';
                    
                    if (response.groups && response.groups.length > 0) {
                        html += `<p class="mb-3" style="color: white;"><strong style="font-size: 1.1em;">📋 Total SPB yang akan terbentuk: ${response.total_groups} SPB</strong></p>`;
                        
                        // Display groups as cards
                        html += '<div class="row">';
                        response.groups.forEach((group, index) => {
                            html += '<div class="col-md-3 mb-3">';
                            html += '<div class="card" style="background-color: rgba(255,255,255,0.15); border: 2px solid rgba(255,255,255,0.3);">';
                            html += '<div class="card-body">';
                            html += `<h6 class="card-title mr-2" style="color: white;"><i class="fas fa-file-alt"></i> SPB #${index + 1}</h6>`;
                            html += '<div class="mb-2">';
                            html += `<span class="badge badge-light mr-2" style="font-size: 0.9em;"><i class="fas fa-tag"></i> ${group.tipe_dokumen}</span>`;
                            html += `<span class="badge badge-light mr-2" style="font-size: 0.9em;"><i class="fas fa-box"></i> ${group.tipe_barang}</span>`;
                            html += `<span class="badge badge-light" style="font-size: 0.9em;"><i class="fas fa-cubes"></i> ${group.item_count} Item</span>`;
                            html += '</div>'; 
                            html += '</div>';
                            html += '</div>';
                            html += '</div>';
                        });
                        html += '</div>';
                        
                        html += '<p class="mb-0 mt-2" style="color: rgba(255,255,255,0.9);"><small><i class="fas fa-lightbulb"></i> Setiap kombinasi <strong>Tipe Dokumen + Tipe Barang</strong> akan membentuk 1 SPB terpisah.</small></p>';
                    } else {
                        html = '<div class="alert alert-warning mb-0" style="background-color: rgba(255,193,7,0.2); border-color: rgba(255,193,7,0.3); color: white;">';
                        html += '<i class="fas fa-exclamation-triangle"></i> ';
                        html += 'Tidak ada item yang dapat dibuatkan SPB. Pastikan semua item memiliki mapping tipe_dokumen dan tipe_barang.';
                        html += '</div>';
                    }
                    
                    $('#spbGroupingPreview').html(html);
                } else {
                    $('#spbGroupingPreview').html(`
                        <div class="alert alert-warning mb-0" style="background-color: rgba(255,193,7,0.2); border-color: rgba(255,193,7,0.3); color: white;">
                            <i class="fas fa-exclamation-triangle"></i> ${response.message || 'Gagal memuat informasi pengelompokan'}
                        </div>
                    `);
                }
            },
            error: function(xhr) {
                console.error('Error loading SPB grouping preview:', xhr);
                $('#spbGroupingPreview').html(`
                    <div class="alert alert-danger mb-0" style="background-color: rgba(220,53,69,0.2); border-color: rgba(220,53,69,0.3); color: white;">
                        <i class="fas fa-times-circle"></i> Terjadi kesalahan saat memuat informasi pengelompokan.
                    </div>
                `);
            }
        });
    }

    // Force Unlock Button Handler
    $('#forceUnlockBtn').on('click', function() {
        const soId = $(this).data('so-id');
        const btn = $(this);
        
        Swal.fire({
            title: 'Force Unlock SO?',
            html: `
                <div class="text-left">
                    <p class="text-danger"><strong>⚠️ Peringatan!</strong></p>
                    <p>Anda akan memaksa unlock dokumen SO yang sedang diedit oleh user lain.</p>
                    <p><strong>Konsekuensi:</strong></p>
                    <ul>
                        <li>User yang sedang edit akan kehilangan akses</li>
                        <li>Perubahan yang belum disimpan mungkin hilang</li>
                        <li>Tindakan ini akan dicatat dalam log sistem</li>
                    </ul>
                    <p class="text-warning mt-2">Gunakan fitur ini hanya dalam kondisi darurat!</p>
                </div>
            `,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<i class="fas fa-unlock"></i> Ya, Force Unlock',
            cancelButtonText: 'Batal',
            width: '600px'
        }).then((result) => {
            if (result.isConfirmed) {
                // Show loading
                Swal.fire({
                    title: 'Memproses...',
                    html: 'Sedang unlock SO. Mohon tunggu...',
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                // Disable button
                btn.prop('disabled', true);
                
                // AJAX call to force unlock
                $.ajax({
                    url: '<?php echo e(route("stock_opnames.force_unlock")); ?>',
                    type: 'POST',
                    data: {
                        _token: '<?php echo e(csrf_token()); ?>',
                        so_id: soId
                    },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Berhasil!',
                                text: response.message,
                                confirmButtonText: 'OK',
                                confirmButtonColor: '#28a745'
                            }).then(() => {
                                // Reload page to update status
                                window.location.reload();
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Gagal',
                                text: response.message,
                                confirmButtonText: 'OK',
                                confirmButtonColor: '#dc3545'
                            });
                            btn.prop('disabled', false);
                        }
                    },
                    error: function(xhr) {
                        let errorMessage = 'Terjadi kesalahan saat force unlock.';
                        
                        if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorMessage = xhr.responseJSON.message;
                        }
                        
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: errorMessage,
                            confirmButtonText: 'OK',
                            confirmButtonColor: '#dc3545'
                        });
                        
                        btn.prop('disabled', false);
                    }
                });
            }
        });
    });

    // Generate SPB Button Handler
    $('#generateSPBBtn').on('click', function() {
        const soId = $(this).data('so-id');
        const btn = $(this);
        
        Swal.fire({
            title: 'Generate SPB Regular?',
            html: `
                <div class="text-left">
                    <p>Sistem akan membuat SPB Regular secara otomatis berdasarkan data SO ini.</p>
                    <p class="text-info"><strong>Proses Generate SPB:</strong></p>
                    <ul class="text-left">
                        <li>Item akan dikelompokkan berdasarkan <strong>Tipe Dokumen</strong> (DO/PO/PR) dan <strong>Tipe Barang</strong> (Basah/Kering)</li>
                        <li>Setiap kombinasi akan membentuk 1 SPB terpisah</li>
                        <li>Minimal 1 SPB, maksimal 6 SPB dapat terbentuk</li>
                        <li>Nomor SPB akan di-generate otomatis</li>
                    </ul>
                    <p class="text-warning mt-2"><i class="fas fa-exclamation-triangle"></i> <strong>Catatan:</strong> Pastikan jadwal pengiriman sudah disetup untuk store ini.</p>
                </div>
            `,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#28a745',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<i class="fas fa-magic"></i> Ya, Generate SPB',
            cancelButtonText: 'Batal',
            width: '600px'
        }).then((result) => {
            if (result.isConfirmed) {
                // Show loading
                Swal.fire({
                    title: 'Memproses...',
                    html: 'Sedang membuat SPB Regular. Mohon tunggu...',
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                // Disable button
                btn.prop('disabled', true);
                
                // AJAX call to generate SPB
                $.ajax({
                    url: `/stock_opnames/${soId}/generate_spb`,
                    type: 'POST',
                    data: {
                        _token: '<?php echo e(csrf_token()); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            // Success
                            Swal.fire({
                                icon: 'success',
                                title: 'SPB Berhasil Dibuat!',
                                html: `<div class="text-left"><pre style="text-align: left; white-space: pre-wrap;">${response.message}</pre></div>`,
                                confirmButtonText: 'OK',
                                confirmButtonColor: '#28a745',
                                width: '600px'
                            }).then(() => {
                                // Reload page to show updated status
                                window.location.reload();
                            });
                        } else {
                            // Failed
                            Swal.fire({
                                icon: 'error',
                                title: 'Gagal Membuat SPB',
                                html: `<div class="text-left"><pre style="text-align: left; white-space: pre-wrap;">${response.message}</pre></div>`,
                                confirmButtonText: 'OK',
                                confirmButtonColor: '#dc3545',
                                width: '600px'
                            });
                            btn.prop('disabled', false);
                        }
                    },
                    error: function(xhr) {
                        console.log('Full XHR Error:', xhr);
                        console.log('Status:', xhr.status);
                        console.log('Status Text:', xhr.statusText);
                        console.log('Response Text:', xhr.responseText);
                        console.log('Response JSON:', xhr.responseJSON);
                        
                        let errorMessage = 'Terjadi kesalahan saat membuat SPB.';
                        let errorDetails = '';
                        
                        try {
                            if (xhr.responseJSON) {
                                console.log('Has responseJSON');
                                errorMessage = xhr.responseJSON.message || errorMessage;
                                
                                if (xhr.responseJSON.errors) {
                                    errorDetails = '<br><br><strong>Detail Error:</strong><br>';
                                    if (Array.isArray(xhr.responseJSON.errors)) {
                                        xhr.responseJSON.errors.forEach(err => {
                                            errorDetails += `• ${JSON.stringify(err)}<br>`;
                                        });
                                    } else if (typeof xhr.responseJSON.errors === 'object') {
                                        for (let key in xhr.responseJSON.errors) {
                                            errorDetails += `• ${key}: ${xhr.responseJSON.errors[key]}<br>`;
                                        }
                                    } else {
                                        errorDetails += `• ${xhr.responseJSON.errors}<br>`;
                                    }
                                }
                                
                                if (xhr.responseJSON.error_details) {
                                    errorDetails += '<br><br><strong>Technical Details:</strong><br>';
                                    errorDetails += `<small>File: ${xhr.responseJSON.error_details.file || 'N/A'}<br>`;
                                    errorDetails += `Line: ${xhr.responseJSON.error_details.line || 'N/A'}</small>`;
                                }
                            } else if (xhr.responseText) {
                                console.log('Has responseText, trying to parse');
                                try {
                                    let response = JSON.parse(xhr.responseText);
                                    errorMessage = response.message || errorMessage;
                                } catch (e) {
                                    console.log('Failed to parse responseText:', e);
                                    errorMessage = xhr.statusText || errorMessage;
                                    errorDetails = '<br><br><small>Status: ' + xhr.status + '</small>';
                                    errorDetails += '<br><small>Response: ' + xhr.responseText.substring(0, 200) + '...</small>';
                                }
                            } else {
                                console.log('No response data');
                                errorMessage = xhr.statusText || 'Unknown error';
                                errorDetails = '<br><br><small>Status Code: ' + xhr.status + '</small>';
                            }
                        } catch (e) {
                            console.log('Error in error handler:', e);
                            errorMessage = 'Terjadi kesalahan tidak terduga: ' + e.message;
                        }
                        
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal Membuat SPB',
                            html: `<div class="text-left">${errorMessage}${errorDetails}</div>`,
                            confirmButtonText: 'OK',
                            confirmButtonColor: '#dc3545',
                            width: '600px'
                        });
                        
                        btn.prop('disabled', false);
                    }
                });
            }
        });
    });
});
</script>

<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts/base_view', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\LSM\resources\views/t-stock-opnames/show.blade.php ENDPATH**/ ?>