
<?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">
                    <div class="card-header">
                        <div class="d-flex flex-wrap align-items-center">
                            <a href="#" id="createSOBtn" class="btn btn-sm btn-warning mb-2 mb-md-0 button-cek-permission" data-permission="stock_opnames.create">
                                <i class="fas fa-plus"></i><span class="d-none d-sm-inline ml-1">Tambah LSM</span>
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <table id="id_data_table" class="table table-hover table-sm">
                            <thead class="bg-warning">
                                <tr>
                                    <th width="5%">No</th>
                                    <th>Nomor SO</th>
                                    <th>Store</th>
                                    <th>Tanggal SO</th>
                                    <th>Status</th>
                                    <th>Sedang Diedit</th>
                                    <th>Dibuat</th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<form action="" id="delete-form" method="post">
    <?php echo method_field('delete'); ?>
    <?php echo csrf_field(); ?>
</form>
<script>
    $(function() {
        // Handle "Tambah LSM" button click
        $('#createSOBtn').on('click', function(e) {
            e.preventDefault();
            
            // Show loading
            Swal.fire({
                title: 'Memeriksa...',
                html: 'Sedang memeriksa SO hari ini. Mohon tunggu...',
                allowOutsideClick: false,
                allowEscapeKey: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Check if SO exists for today
            $.ajax({
                url: '<?php echo e(route("stock_opnames.check_today_so")); ?>',
                type: 'GET',
                data: {
                    store_id: '<?php echo e(session("store_selected")); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        if (response.exists) {
                            if (response.status === 'Submitted') {
                                // SO exists and is submitted - show error
                                Swal.fire({
                                    icon: 'error',
                                    title: 'SO Sudah Di-Submit',
                                    html: `
                                        <div class="text-left">
                                            <p><strong>SO Number:</strong> ${response.so_number}</p>
                                            <p><strong>Status:</strong> <span class="badge badge-success">Submitted</span></p>
                                            <hr>
                                            <p class="text-danger"><strong>⚠️ Tidak dapat membuat SO baru!</strong></p>
                                            <p>${response.message}</p>
                                            <p>Setiap hari hanya boleh ada 1 SO per store. SO hari ini sudah di-submit dan tidak dapat diedit lagi.</p>
                                        </div>
                                    `,
                                    confirmButtonText: 'OK',
                                    confirmButtonColor: '#dc3545',
                                    width: '600px'
                                });
                            } else {
                                // SO exists but still Draft - redirect to edit
                                Swal.fire({
                                    icon: 'info',
                                    title: 'SO Sudah Ada',
                                    html: `
                                        <div class="text-left">
                                            <p><strong>SO Number:</strong> ${response.so_number}</p>
                                            <p><strong>Status:</strong> <span class="badge badge-secondary">Draft</span></p>
                                            <hr>
                                            <p>${response.message}</p>
                                            <p>Anda akan diarahkan ke halaman edit untuk melanjutkan SO yang sudah ada.</p>
                                        </div>
                                    `,
                                    confirmButtonText: 'Lanjutkan Edit',
                                    confirmButtonColor: '#28a745',
                                    width: '600px'
                                }).then(() => {
                                    window.location.href = '<?php echo e(route("stock_opnames.create")); ?>';
                                });
                            }
                        } else {
                            // No SO exists - navigate to create
                            window.location.href = '<?php echo e(route("stock_opnames.create")); ?>';
                        }
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.message || 'Terjadi kesalahan saat memeriksa SO.',
                            confirmButtonText: 'OK',
                            confirmButtonColor: '#dc3545'
                        });
                    }
                },
                error: function(xhr) {
                    let errorMessage = 'Terjadi kesalahan saat memeriksa SO.';
                    
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMessage = xhr.responseJSON.message;
                    }
                    
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: errorMessage,
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#dc3545'
                    });
                }
            });
        });
        
        $('#id_data_table').DataTable({
            processing: true,
            serverSide: true,
            ajax: '<?php echo e(route("stock_opnames.index")); ?>',
            columns: [{
                    data: 0,
                    name: 'no',
                    orderable: false,
                    searchable: false
                },
                {
                    data: 1,
                    name: 'so_number'
                },
                {
                    data: 2,
                    name: 'store_id'
                },
                {
                    data: 3,
                    name: 'so_date'
                },
                {
                    data: 4,
                    name: 'status'
                },
                {
                    data: 5,
                    name: 'editing_by'
                },
                {
                    data: 6,
                    name: 'created_at'
                }
            ],
            "responsive": false,
            "lengthChange": true,
            "autoWidth": false,
            //"buttons": ["copy", "csv", "excel", "pdf", "print", "colvis"],
            drawCallback: function(settings) {
                $('[data-toggle="tooltip"]').tooltip();
                
                // Attach force unlock handler
                $('.force-unlock-btn').off('click').on('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    const soId = $(this).data('so-id');
                    const soNumber = $(this).data('so-number');
                    const editor = $(this).data('editor');
                    const btn = $(this);
                    
                    Swal.fire({
                        title: 'Force Unlock SO?',
                        html: `
                            <div class="text-left">
                                <p><strong>SO Number:</strong> ${soNumber}</p>
                                <p><strong>Sedang diedit oleh:</strong> ${editor}</p>
                                <hr>
                                <p class="text-danger"><strong>⚠️ Peringatan!</strong></p>
                                <p>Anda akan memaksa unlock dokumen SO ini.</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>
                            </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 DataTable
                                            $('#id_data_table').DataTable().ajax.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);
                                }
                            });
                        }
                    });
                });
            }
        }).buttons().container().appendTo('#id_data_table_wrapper .col-md-6:eq(0)');
    });
</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/index.blade.php ENDPATH**/ ?>