@extends('layouts/base_view')
@section('title')
{!! $variables['header_routes'] !!}
@endsection
@section('content')
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <div class="row">
                            <div class="col-md-auto">
                                <button type="button" class="btn btn-warning btn-sm mr-2" id="upload-excel-btn">
                                    <i class="fas fa-file-upload"></i> Unggah Excel
                                </button>
                                <button type="button" class="btn btn-warning btn-sm mr-2" id="download-template-btn">
                                    <i class="fas fa-file-download"></i> Unduh Template
                                </button>
                                <a href="{{ route('target_sisa_malam.create') }}" class="btn btn-warning btn-sm button-cek-permission" data-permission="target_sisa_malam.create">
                                    <i class="fas fa-plus"></i> Tambah
                                </a>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="id_data_table" class="table table-hover table-sm">
                                <thead class="bg-warning">
                                    <tr>
                                    <th width="5%">No</th>
                                    <th>Store</th>
                                    <th>Item</th>
                                    <th>Target Qty</th>
                                    <th>Status</th>
                                    <th>Dibuat</th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Excel Upload Modal -->
<div class="modal fade" id="uploadExcelModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Unggah Excel - Target Sisa Malam</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form id="uploadExcelForm" enctype="multipart/form-data">
                @csrf
                <div class="modal-body">
                    <div class="form-group">
                        <label>Pilih File Excel</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: 10MB)<br>
                            Kolom yang diperlukan: Store Code, Raw Material Code, Target Qty, Status
                        </small>
                    </div>
                    <div id="upload-progress" class="progress" style="display: none;">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 100%"></div>
                    </div>
                    <div id="upload-result" style="display: none;">
                        <div class="alert" role="alert"></div>
                        <div id="error-details"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-warning" data-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-warning" id="upload-submit-btn">
                        <i class="fas fa-upload"></i> Unggah
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<form action="" id="delete-form" method="post">
    @method('delete')
    @csrf
</form>
<script>
    $(function() {
        $('#id_data_table').DataTable({
            processing: true,
            serverSide: true,
            ajax: '{{ route("target_sisa_malam.index") }}',
            columns: [{
                    data: 0,
                    name: 'no',
                    orderable: false,
                    searchable: false
                },
                {
                    data: 1,
                    name: 'store_id'
                },
                {
                    data: 2,
                    name: 'raw_material_id'
                },
                {
                    data: 3,
                    name: 'target_qty'
                },
                {
                    data: 4,
                    name: 'status'
                },
                {
                    data: 5,
                    name: 'created_at'
                }
            ],
            "responsive": false,
            "lengthChange": true,
            "autoWidth": false,
            //"buttons": ["copy", "csv", "excel", "pdf", "print", "colvis"],
            drawCallback: function(settings) {
                $('[data-toggle="tooltip"]').tooltip();
            }
        }).buttons().container().appendTo('#id_data_table_wrapper .col-md-6:eq(0)');

        // Upload Excel Button
        $('#upload-excel-btn').click(function() {
            $('#uploadExcelModal').modal('show');
            $('#uploadExcelForm')[0].reset();
            $('#upload-result').hide();
            $('.custom-file-label').text('Pilih file...');
        });

        // Download Template Button
        $('#download-template-btn').click(function() {
            window.location.href = '{{ route("target_sisa_malam.download_template") }}';
        });

        // File input change
        $('#excel_file').change(function() {
            var fileName = $(this).val().split('\\').pop();
            $(this).next('.custom-file-label').text(fileName);
        });

        // Upload Form Submit
        $('#uploadExcelForm').submit(function(e) {
            e.preventDefault();

            var formData = new FormData(this);

            $('#upload-progress').show();
            $('#upload-result').hide();
            $('#upload-submit-btn').prop('disabled', true);

            $.ajax({
                url: '{{ route("target_sisa_malam.upload_excel") }}',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    $('#upload-progress').hide();
                    $('#upload-submit-btn').prop('disabled', false);

                    var alertClass = response.success ? 'alert-success' : 'alert-warning';
                    var alertHtml = '<div class="alert ' + alertClass + '">' + response.message + '</div>';

                    if (response.errors && response.errors.length > 0) {
                        var errorHtml = '<div class="alert alert-danger"><strong>Error Details:</strong><ul>';
                        response.errors.forEach(function(error) {
                            errorHtml += '<li>Baris ' + error.row + ': ' + error.error + '</li>';
                        });
                        errorHtml += '</ul></div>';
                        $('#error-details').html(errorHtml);
                    } else {
                        $('#error-details').html('');
                    }

                    $('#upload-result .alert').html(response.message);
                    $('#upload-result .alert').removeClass('alert-success alert-warning alert-danger').addClass(alertClass);
                    $('#upload-result').show();

                    if (response.success) {
                        $('#id_data_table').DataTable().ajax.reload();
                        setTimeout(function() {
                            $('#uploadExcelModal').modal('hide');
                        }, 2000);
                    }
                },
                error: function(xhr) {
                    $('#upload-progress').hide();
                    $('#upload-submit-btn').prop('disabled', false);

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

                    $('#upload-result .alert').html(errorMsg);
                    $('#upload-result .alert').removeClass('alert-success alert-warning').addClass('alert-danger');
                    $('#upload-result').show();
                }
            });
        });
    });
</script>
@endsection