
<?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">
                        <a href="<?php echo e(route('store_raw_materials.create')); ?>" class="btn btn-sm btn-warning button-cek-permission" data-permission="store_raw_materials.create">
                            <i class="fas fa-plus"></i> Tambah Pemetaan
                        </a>
                        <button type="button" class="btn btn-sm btn-warning button-cek-permission" data-permission="store_raw_materials.upload" data-toggle="modal" data-target="#uploadModal">
                            <i class="fas fa-upload"></i> Unggah Excel
                        </button>
                        <a href="<?php echo e(route('store_raw_materials.download_template')); ?>" target="_blank" class="btn btn-sm btn-warning button-cek-permission" data-permission="store_raw_materials.download_template">
                            <i class="fa fa-download"></i> Unduh Template
                        </a>
                    </div>
                    <div class="card-body">
                        <div class="row mb-3">
                            <div class="col-md-3">
                                <label>Filter Store:</label>
                                <select id="storeFilter" class="form-control form-control-sm">
                                    <option value="">Semua Store</option>
                                    <?php $__currentLoopData = $stores; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $store): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($store->id); ?>"><?php echo e($store->name); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label>Filter Status:</label>
                                <select id="statusFilter" class="form-control form-control-sm">
                                    <option value="">Semua Status</option>
                                    <option value="1">Aktif</option>
                                    <option value="0">Dihapus</option>
                                </select>
                            </div>
                        </div>

                        <div class="table-responsive">
                            <table id="storeRawMaterialsTable" class="table table-hover table-sm">
                                <thead class="bg-warning">
                                    <tr>
                                        <th width="5%">No</th>
                                        <th>Store</th>
                                        <th>Item</th>
                                        <th>Tipe Dokumen</th>
                                        <th>Tipe Barang</th>
                                        <th>Status</th>
                                        <th>Stok Min</th>
                                        <th>Stok Maks</th>
                                        <th>Reorder Point</th>
                                        <th>Dibuat</th>
                                        <th>Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Upload Modal -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="uploadModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-success">
                <h5 class="modal-title" id="uploadModalLabel">
                    <i class="fa fa-upload"></i> Unggah Excel - Pemetaan Item Store
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Tutup">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="uploadForm" enctype="multipart/form-data">
                <?php echo csrf_field(); ?>
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        <strong>Informasi:</strong>
                        <ul class="mb-0 mt-2">
                            <li>File harus berformat Excel (.xlsx atau .xls)</li>
                            <li>Maksimal ukuran file: 10 MB</li>
                            <li>Gunakan template yang disediakan untuk format yang benar</li>
                            <li><strong>Anda hanya bisa upload data untuk store yang Anda punya akses</strong></li>
                            <li>Kolom wajib: Store Code, Raw Material Code, Tipe Dokumen</li>
                            <li>Tipe Dokumen: DO, PO, atau PR</li>
                            <li><strong>Semua data yang di-upload akan otomatis berstatus "Active"</strong></li>
                            <li>Data yang sudah ada akan di-update, data baru akan ditambahkan</li>
                            <li>Data yang deleted akan di-activate kembali saat di-upload</li>
                        </ul>
                    </div>

                    <div class="form-group">
                        <label for="excel_file" class="font-weight-bold">
                            Pilih File Excel <span class="text-danger">*</span>
                        </label>
                        <div class="custom-file">
                            <input type="file" class="custom-file-input" id="excel_file" name="excel_file" accept=".xlsx,.xls" required>
                            <label class="custom-file-label" for="excel_file">Pilih file...</label>
                        </div>
                        <small class="form-text text-muted">
                            Format: .xlsx atau .xls (Max: 10 MB)
                        </small>
                    </div>

                    <div id="uploadProgress" class="progress" style="display: none;">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 100%">
                            Memproses...
                        </div>
                    </div>

                    <div id="uploadResult" style="display: none;">
                        <!-- Result will be shown here -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fa fa-times"></i> Tutup
                    </button>
                    <button type="submit" class="btn btn-warning" id="btnUpload">
                        <i class="fas fa-upload"></i> Unggah
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<script>
    var storeRawMaterialsTable; // Declare globally within script scope

    $(function() {
        storeRawMaterialsTable = $('#storeRawMaterialsTable').DataTable({
            processing: true,
            serverSide: true,
            ajax: {
                url: '<?php echo e(route("store_raw_materials.index")); ?>',
                data: function(d) {
                    d.store_filter = $('#storeFilter').val();
                    d.status_filter = $('#statusFilter').val();
                }
            },
            columns: [{
                    data: 0,
                    name: 'no',
                    orderable: false,
                    searchable: false
                },
                {
                    data: 1,
                    name: 'store_id'
                },
                {
                    data: 2,
                    name: 'raw_material_id'
                },
                {
                    data: 3,
                    name: 'tipe_dokumen'
                },
                {
                    data: 4,
                    name: 'tipe_barang',
                    orderable: false
                },
                {
                    data: 5,
                    name: 'is_active'
                },
                {
                    data: 6,
                    name: 'min_stock'
                },
                {
                    data: 7,
                    name: 'max_stock'
                },
                {
                    data: 8,
                    name: 'reorder_point'
                },
                {
                    data: 9,
                    name: 'created_at'
                },
                {
                    data: 10,
                    name: 'actions',
                    orderable: false,
                    searchable: false
                }
            ],
            responsive: false,
            lengthChange: true,
            autoWidth: false,
            buttons: ["copy", "csv", "excel", "pdf", "print", "colvis"],
            drawCallback: function(settings) {
                $('[data-toggle="tooltip"]').tooltip();
            }
        });

        // Append buttons
        storeRawMaterialsTable.buttons().container().appendTo('#storeRawMaterialsTable_wrapper .col-md-6:eq(0)');

        // Filter change events
        $('#storeFilter, #statusFilter').on('change', function() {
            if (storeRawMaterialsTable) {
                storeRawMaterialsTable.ajax.reload();
            }
        });

        // Custom file input label
        $('.custom-file-input').on('change', function() {
            var fileName = $(this).val().split('\\').pop();
            $(this).next('.custom-file-label').html(fileName);
        });

        // Upload form submit
        $('#uploadForm').on('submit', function(e) {
            e.preventDefault();

            var formData = new FormData(this);

            // Show progress
            $('#uploadProgress').show();
            $('#uploadResult').hide();
            $('#btnUpload').prop('disabled', true);

            $.ajax({
                url: '<?php echo e(route("store_raw_materials.upload")); ?>',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    $('#uploadProgress').hide();
                    $('#btnUpload').prop('disabled', false);

                    var resultHtml = '<div class="alert alert-' + (response.success ? 'success' : 'warning') + '">';
                    resultHtml += '<h5><i class="icon fas fa-' + (response.success ? 'check' : 'exclamation-triangle') + '"></i> ' + response.message + '</h5>';

                    if (response.inserted > 0 || response.updated > 0) {
                        resultHtml += '<ul class="mb-0">';
                        if (response.inserted > 0) {
                            resultHtml += '<li><strong>' + response.inserted + '</strong> data baru berhasil ditambahkan</li>';
                        }
                        if (response.updated > 0) {
                            resultHtml += '<li><strong>' + response.updated + '</strong> data berhasil diupdate</li>';
                        }
                        resultHtml += '</ul>';
                    }

                    if (response.errors && response.errors.length > 0) {
                        resultHtml += '<hr><strong>Error Details:</strong>';
                        resultHtml += '<div style="max-height: 200px; overflow-y: auto;">';
                        resultHtml += '<table class="table table-sm table-bordered mt-2">';
                        resultHtml += '<thead><tr><th>Baris</th><th>Error</th></tr></thead><tbody>';
                        response.errors.forEach(function(error) {
                            resultHtml += '<tr><td>' + error.row + '</td><td>' + error.error + '</td></tr>';
                        });
                        resultHtml += '</tbody></table></div>';
                    }

                    resultHtml += '</div>';

                    $('#uploadResult').html(resultHtml).show();

                    // Reload table if success
                    if (response.success && (response.inserted > 0 || response.updated > 0)) {
                        storeRawMaterialsTable.ajax.reload();
                    }

                    // Reset form if fully successful
                    if (response.success && response.errors.length === 0) {
                        setTimeout(function() {
                            $('#uploadModal').modal('hide');
                            $('#uploadForm')[0].reset();
                            $('.custom-file-label').html('Pilih file...');
                            $('#uploadResult').hide();
                        }, 2000);
                    }
                },
                error: function(xhr) {
                    $('#uploadProgress').hide();
                    $('#btnUpload').prop('disabled', false);

                    var errorMsg = 'Terjadi kesalahan saat upload';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMsg = xhr.responseJSON.message;
                    }

                    var resultHtml = '<div class="alert alert-danger">';
                    resultHtml += '<h5><i class="icon fas fa-ban"></i> Error!</h5>';
                    resultHtml += errorMsg;
                    resultHtml += '</div>';

                    $('#uploadResult').html(resultHtml).show();
                }
            });
        });

        // Reset modal on close
        $('#uploadModal').on('hidden.bs.modal', function() {
            $('#uploadForm')[0].reset();
            $('.custom-file-label').html('Pilih file...');
            $('#uploadResult').hide();
            $('#uploadProgress').hide();
            $('#btnUpload').prop('disabled', false);
        });

        // Handle activate button click
        $(document).on('click', '.btn-activate', function(e) {
            e.preventDefault();

            var url = $(this).data('url');
            var id = $(this).data('id');

            Swal.fire({
                title: 'Aktifkan Pemetaan?',
                text: 'Pemetaan ini akan diaktifkan kembali dan bisa digunakan.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#6c757d',
                confirmButtonText: '<i class="fa fa-check"></i> Ya, Aktifkan!',
                cancelButtonText: '<i class="fa fa-times"></i> Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Create form and submit
                    var form = $('<form>', {
                        'method': 'POST',
                        'action': url
                    });

                    form.append($('<input>', {
                        'type': 'hidden',
                        'name': '_token',
                        'value': '<?php echo e(csrf_token()); ?>'
                    }));

                    form.append($('<input>', {
                        'type': 'hidden',
                        'name': '_method',
                        'value': 'DELETE'
                    }));

                    form.append($('<input>', {
                        'type': 'hidden',
                        'name': 'action',
                        'value': 'activate'
                    }));

                    $('body').append(form);
                    form.submit();
                }
            });
        });
    });
</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/m-store-raw-materials/index.blade.php ENDPATH**/ ?>