@extends('layouts/base_view')
@section('title')
{!! $variables['header_routes'] !!}
@endsection

@section('content')
<style>
    .forecast-alert-container .badge {
        font-size: 0.75em;
        cursor: help;
    }

    .forecast-alert-container .badge-danger {
        animation: pulse 2s infinite;
    }

    @keyframes pulse {
        0% {
            opacity: 1;
        }

        50% {
            opacity: 0.7;
        }

        100% {
            opacity: 1;
        }
    }

    .table th,
    .table td {
        vertical-align: middle;
        font-size: 0.9em;
    }

    #forecast-summary .alert {
        transition: all 0.3s ease;
    }

    .alert-sm {
        padding: 0.375rem 0.75rem;
        font-size: 0.875rem;
    }
</style>

<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">{!! $variables['judul'] !!}</h3>
                    </div>
                    <div class="card-body">
                        <form id="formID" method="post" action="{{ route('item_requests.store', ['prm_id' => $data->id]) }}">
                            @csrf

                             <!-- Info SPB Regular dari SO -->
                            @if($data->id && $data->request_type == 'Regular' && $data->stockOpname)
                            <div class="row mb-3">
                                <div class="col-12">
                                    <div class="alert alert-info alert-sm">
                                        <i class="fas fa-info-circle"></i>
                                        <strong>SPB Regular</strong> - Dibuat otomatis dari Stock Opname: 
                                        <a href="{{ route('stock_opnames.show', $data->stockOpname->id) }}" target="_blank" class="alert-link">
                                            <strong>{{ $data->stockOpname->so_number }}</strong>
                                        </a>
                                        ({{ $data->stockOpname->so_date->format('d M Y') }})
                                    </div>
                                </div>
                            </div>
                            @endif
                            <!-- Header Information -->
                            <div class="row mb-4">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Nomor SPB</label>
                                        <input value="{{ old('spb_number', $data->spb_number ?? 'Auto Generated') }}" type="text" class="form-control form-control-sm" readonly>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="store_id">Store <span class="text-danger">*</span></label>
                                        <select class="form-control form-control-sm select2 select2-warning" data-dropdown-css-class="select2-warning" name="store_id" id="store_id" required {{ $data->id && $data->request_type == 'Regular' ? 'disabled' : '' }}>
                                            <option value="">Pilih Store</option>
                                            @foreach($variables['stores'] as $store)
                                            <option value="{{ $store->id }}" {{ old('store_id', $data->store_id ?? '') == $store->id ? 'selected' : '' }}>
                                                {{ $store->name }}
                                            </option>
                                            @endforeach
                                        </select>
                                        @if($data->id && $data->request_type == 'Regular')
                                        <input type="hidden" name="store_id" value="{{ $data->store_id }}">
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="status">Status <span class="text-danger">*</span></label>
                                        <select class="form-control form-control-sm select2 select2-warning" data-dropdown-css-class="select2-warning" name="status" required>
                                            <option value="Draft" {{ old('status', $data->status ?? 'Draft') == 'Draft' ? 'selected' : '' }}>Draft</option>
                                            <option value="Submitted" {{ old('status', $data->status ?? '') == 'Submitted' ? 'selected' : '' }}>Submitted</option>
                                            <option value="Approved" {{ old('status', $data->status ?? '') == 'Approved' ? 'selected' : '' }}>Approved</option>
                                        </select>
                                    </div>
                                </div>
                            </div> 

                            <!-- Hidden fields -->
                            @if($data->id)
                            <!-- Untuk edit, gunakan data yang ada -->
                            <input type="hidden" name="request_type" value="{{ $data->request_type }}">
                            <input type="hidden" name="stock_opname_id" value="{{ $data->stock_opname_id }}">
                            @else
                            <!-- Untuk create baru, default Additional -->
                            <input type="hidden" name="request_type" value="Additional">
                            <input type="hidden" name="stock_opname_id" value="">
                            @endif

                            <div class="row mb-4">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="request_date">Tanggal Permintaan <span class="text-danger">*</span></label>
                                        <input value="{{ old('request_date', $data->request_date ?? date('Y-m-d')) }}" type="date" class="form-control form-control-sm" name="request_date" required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="delivery_date">Tanggal Pengiriman</label>
                                        <input value="{{ old('delivery_date', $data->delivery_date ?? '') }}" type="date" class="form-control form-control-sm" name="delivery_date">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="shipment_schedule_id">Jadwal Pengiriman</label>
                                        <select class="form-control form-control-sm select2 select2-warning" data-dropdown-css-class="select2-warning" name="shipment_schedule_id">
                                            <option value="">Pilih Jadwal Pengiriman</option>
                                            @foreach($variables['shipment_deliveries'] as $schedule)
                                            <option value="{{ $schedule->id }}" {{ old('shipment_schedule_id', $data->shipment_schedule_id ?? '') == $schedule->id ? 'selected' : '' }}>
                                                {{ $schedule->store->name }} - {{ $schedule->day_name }} ({{ $schedule->armadaType->name }})
                                            </option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <!-- Action Buttons -->
                            <div class="row mb-3">
                                <div class="col-12">
                                    <button type="button" class="btn btn-success btn-sm button-cek-permission" data-permission="item_requests.create" id="add-item">
                                        <i class="fa fa-plus"></i> Tambah Item Manual
                                    </button>

                                    <!-- Forecast Summary Alert -->
                                    <div class="float-right" id="forecast-summary" style="display: none;">
                                        <div class="alert alert-info alert-sm mb-0 py-2">
                                            <i class="fa fa-chart-line"></i>
                                            <span id="forecast-summary-text">Perbandingan forecast akan muncul di sini</span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Items Section -->
                            <div class="row">
                                <div class="col-12">
                                    <h5>Item SPB</h5>
                                    <div class="table-responsive">
                                        <table class="table table-hover table-sm" id="items-table">
                                            <thead class="bg-warning">
                                                <tr>
                                                    <th width="18%">Raw Material</th>
                                                    <th width="8%">Qty Forecast</th>
                                                    <th width="8%">Qty SO</th>
                                                    <th width="8%">Qty TSM</th>
                                                    <th width="8%">Qty Saran</th>
                                                    <th width="8%">Qty Penyesuaian</th>
                                                    <th width="8%">Qty Final</th>
                                                    <th width="12%">Alert Forecast</th>
                                                    <th width="8%">Status DOI</th>
                                                    <th width="10%">Catatan</th>
                                                    <th width="4%">Aksi</th>
                                                </tr>
                                            </thead>
                                            <tbody id="items-tbody">
                                                @if(isset($data->details) && count($data->details) > 0)
                                                @foreach($data->details as $index => $detail)
                                                <tr>
                                                    <td>
                                                        <select class="form-control form-control-sm raw-material-select" name="items[{{ $index }}][raw_material_id]" required>
                                                            <option value="">Pilih Raw Material</option>
                                                            @foreach($variables['raw_materials'] as $rm)
                                                            <option value="{{ $rm->id }}" {{ $detail->raw_material_id == $rm->id ? 'selected' : '' }}>
                                                                {{ $rm->code }} - {{ $rm->name }}
                                                            </option>
                                                            @endforeach
                                                        </select>
                                                    </td>
                                                    <td><input type="number" step="0.01" class="form-control form-control-sm" name="items[{{ $index }}][forecast_qty]" value="{{ $detail->forecast_qty }}"></td>
                                                    <td><input type="number" step="0.01" class="form-control form-control-sm" name="items[{{ $index }}][so_qty]" value="{{ $detail->so_qty }}"></td>
                                                    <td><input type="number" step="0.01" class="form-control form-control-sm" name="items[{{ $index }}][tsm_qty]" value="{{ $detail->tsm_qty }}"></td>
                                                    <td><input type="number" step="0.01" class="form-control form-control-sm suggested-qty" name="items[{{ $index }}][suggested_qty]" value="{{ $detail->suggested_qty }}" required></td>
                                                    <td><input type="number" step="0.01" class="form-control form-control-sm adjusted-qty" name="items[{{ $index }}][adjusted_qty]" value="{{ $detail->adjusted_qty }}"></td>
                                                    <td><input type="number" step="0.01" class="form-control form-control-sm final-qty" value="{{ $detail->final_qty }}" readonly></td>
                                                    <td>
                                                        <div class="forecast-alert-container">
                                                            <span class="badge badge-secondary">Memeriksa...</span>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="badge badge-{{ $detail->alert_status == 'Critical' ? 'danger' : ($detail->alert_status == 'Normal' ? 'warning' : 'success') }}">
                                                            {{ $detail->alert_status }}
                                                        </span>
                                                    </td>
                                                    <td><input type="text" class="form-control form-control-sm" name="items[{{ $index }}][notes]" value="{{ $detail->notes }}"></td>
                                                    <td><button type="button" class="btn btn-danger btn-sm remove-item"><i class="fa fa-trash"></i></button></td>
                                                </tr>
                                                @endforeach
                                                @else
                                                <tr>
                                                    <td colspan="11" class="text-center text-muted text-sm">Belum ada item yang ditambahkan. Gunakan "Tambah Item Manual" untuk menambah item</td>
                                                </tr>
                                                @endif
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>

                            <!-- Notes -->
                            <div class="row mt-3">
                                <div class="col-12">
                                    <div class="form-group">
                                        <label for="notes">Catatan</label>
                                        <textarea class="form-control form-control-sm" name="notes" placeholder="" style="height: 100px">{{ old('notes', $data->notes ?? '') }}</textarea>
                                    </div>
                                </div>
                            </div>

                            <button type="submit" class="btn btn-info btn-sm button-cek-permission" data-permission="item_requests.store"><i class="fas fa-save"></i> Simpan SPB</button>
                            <a href="{{ route('item_requests.index') }}" class="btn btn-warning btn-sm" data='back' onclick="return notificationBeforeBack(event, this);"><i class="fas fa-arrow-left"></i> Kembali</a>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
    $(document).ready(function() {
        let itemIndex = {{ isset($data->details) ? count($data->details) : 0}};

        // Add manual item row
        $('#add-item').click(function() {
            addItemRow();
        });
            addItemRow();
        });

        function addItemRow(item = null) {
            const newRow = `
            <tr>
                <td>
                    <select class="form-control form-control-sm raw-material-select" name="items[${itemIndex}][raw_material_id]" required>
                        <option value="">Select Raw Material</option>
                        @foreach($variables['raw_materials'] as $rm)
                            <option value="{{ $rm->id }}" ${item && item.raw_material_id == {{ $rm->id }} ? 'selected' : ''}>
                                {{ $rm->code }} - {{ $rm->name }}
                            </option>
                        @endforeach
                    </select>
                </td>
                <td><input type="number" step="0.01" class="form-control form-control-sm forecast-qty" name="items[${itemIndex}][forecast_qty]" value="${item ? item.forecast_qty || 0 : 0}" readonly></td>
                <td><input type="number" step="0.01" class="form-control form-control-sm" name="items[${itemIndex}][so_qty]" value="${item ? item.so_qty || 0 : 0}"></td>
                <td><input type="number" step="0.01" class="form-control form-control-sm" name="items[${itemIndex}][tsm_qty]" value="${item ? item.tsm_qty || 0 : 0}"></td>
                <td><input type="number" step="0.01" class="form-control form-control-sm suggested-qty" name="items[${itemIndex}][suggested_qty]" value="${item ? item.suggested_qty || 0 : 0}" required></td>
                <td><input type="number" step="0.01" class="form-control form-control-sm adjusted-qty" name="items[${itemIndex}][adjusted_qty]" value="0"></td>
                <td><input type="number" step="0.01" class="form-control form-control-sm final-qty" value="${item ? item.suggested_qty || 0 : 0}" readonly></td>
                <td>
                    <div class="forecast-alert-container">
                        <span class="badge badge-secondary">-</span>
                    </div>
                </td>
                <td><span class="badge badge-secondary">-</span></td>
                <td><input type="text" class="form-control form-control-sm" name="items[${itemIndex}][notes]"></td>
                <td><button type="button" class="btn btn-danger btn-sm remove-item"><i class="fa fa-trash"></i></button></td>
            </tr>
        `;

            if ($('#items-tbody tr td[colspan]').length > 0) {
                $('#items-tbody').empty();
            }

            $('#items-tbody').append(newRow);

            // Set the raw material if provided
            if (item && item.raw_material_id) {
                $(`select[name="items[${itemIndex}][raw_material_id]"]`).val(item.raw_material_id);
            }

            itemIndex++;
        }

        // Remove item row
        $(document).on('click', '.remove-item', function() {
            $(this).closest('tr').remove();
            if ($('#items-tbody tr').length === 0) {
                $('#items-tbody').html('<tr><td colspan="11" class="text-center text-muted text-sm">Belum ada item yang ditambahkan. Gunakan "Tambah Item Manual" untuk menambah item</td></tr>');
            }
        });

        // Calculate final quantity when suggested or adjusted changes
        $(document).on('input', '.suggested-qty, .adjusted-qty', function() {
            const row = $(this).closest('tr');
            const suggestedQty = parseFloat(row.find('.suggested-qty').val()) || 0;
            const adjustedQty = parseFloat(row.find('.adjusted-qty').val()) || 0;

            const finalQty = adjustedQty > 0 ? adjustedQty : suggestedQty;
            row.find('.final-qty').val(finalQty.toFixed(2));

            // Check forecast comparison when final quantity changes
            checkForecastComparison(row);
        });

        // Check forecast comparison when raw material changes
        $(document).on('change', '.raw-material-select', function() {
            const row = $(this).closest('tr');
            const rawMaterialId = $(this).val();

            if (rawMaterialId) {
                // Get forecast data and update forecast_qty field
                getForecastData(row, rawMaterialId);
            } else {
                row.find('.forecast-qty').val(0);
                row.find('.forecast-alert-container').html('<span class="badge badge-secondary">-</span>');
            }
        });

        // Function to get forecast data for selected raw material
        function getForecastData(row, rawMaterialId) {
            const storeId = $('#store_id').val();

            if (!storeId) {
                row.find('.forecast-alert-container').html('<span class="badge badge-secondary">Select store first</span>');
                return;
            }

            $.ajax({
                url: '{{ route("item_requests.forecast_comparison") }}',
                type: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    store_id: storeId,
                    raw_material_id: rawMaterialId,
                    requested_qty: 0 // Initial check
                },
                success: function(response) {
                    if (response.success) {
                        row.find('.forecast-qty').val(response.forecast_qty || 0);
                        checkForecastComparison(row);
                    }
                },
                error: function() {
                    row.find('.forecast-alert-container').html('<span class="badge badge-danger">Error loading forecast</span>');
                }
            });
        }

        // Function to check forecast comparison
        function checkForecastComparison(row) {
            const storeId = $('#store_id').val();
            const rawMaterialId = row.find('.raw-material-select').val();
            const finalQty = parseFloat(row.find('.final-qty').val()) || 0;

            if (!storeId || !rawMaterialId || finalQty <= 0) {
                row.find('.forecast-alert-container').html('<span class="badge badge-secondary">-</span>');
                return;
            }

            $.ajax({
                url: '{{ route("item_requests.forecast_comparison") }}',
                type: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    store_id: storeId,
                    raw_material_id: rawMaterialId,
                    requested_qty: finalQty
                },
                success: function(response) {
                    if (response.success) {
                        const alertHtml = `<span class="badge badge-${response.alert_class}" title="${response.message}">${response.status.replace(/_/g, ' ').toUpperCase()}</span>`;
                        row.find('.forecast-alert-container').html(alertHtml);

                        // Show detailed message on hover or click
                        row.find('.forecast-alert-container .badge').attr('data-toggle', 'tooltip');
                        row.find('.forecast-alert-container .badge').attr('data-placement', 'top');
                        row.find('.forecast-alert-container .badge').tooltip();

                        // Update summary after forecast check
                        setTimeout(updateForecastSummary, 100);
                    } else {
                        row.find('.forecast-alert-container').html('<span class="badge badge-secondary">No forecast data</span>');
                    }
                },
                error: function() {
                    row.find('.forecast-alert-container').html('<span class="badge badge-danger">Error</span>');
                }
            });
        }

        // Check forecast when store changes
        $('#store_id').change(function() {
            $('#items-tbody tr').each(function() {
                const row = $(this);
                const rawMaterialId = row.find('.raw-material-select').val();
                if (rawMaterialId) {
                    getForecastData(row, rawMaterialId);
                }
            });
        });

        // Update forecast summary
        function updateForecastSummary() {
            let totalItems = 0;
            let overForecast = 0;
            let underForecast = 0;
            let matchForecast = 0;
            let noForecast = 0;

            $('#items-tbody tr').each(function() {
                const alertBadge = $(this).find('.forecast-alert-container .badge');
                if (alertBadge.length > 0 && !alertBadge.hasClass('badge-secondary')) {
                    totalItems++;

                    if (alertBadge.hasClass('badge-danger') || alertBadge.hasClass('badge-secondary')) {
                        overForecast++;
                    } else if (alertBadge.hasClass('badge-info')) {
                        underForecast++;
                    } else if (alertBadge.hasClass('badge-success')) {
                        matchForecast++;
                    } else {
                        noForecast++;
                    }
                }
            });

            if (totalItems > 0) {
                let summaryText = `${totalItems} items: `;
                let summaryParts = [];

                if (overForecast > 0) summaryParts.push(`${overForecast} over forecast`);
                if (underForecast > 0) summaryParts.push(`${underForecast} under forecast`);
                if (matchForecast > 0) summaryParts.push(`${matchForecast} match forecast`);
                if (noForecast > 0) summaryParts.push(`${noForecast} no forecast`);

                summaryText += summaryParts.join(', ');

                $('#forecast-summary-text').text(summaryText);
                $('#forecast-summary').show();

                // Change alert color based on issues
                const alertDiv = $('#forecast-summary .alert');
                alertDiv.removeClass('alert-info alert-warning alert-danger alert-success');

                if (overForecast > totalItems * 0.3) {
                    alertDiv.addClass('alert-danger');
                } else if (overForecast > 0 || underForecast > totalItems * 0.3) {
                    alertDiv.addClass('alert-warning');
                } else {
                    alertDiv.addClass('alert-success');
                }
            } else {
                $('#forecast-summary').hide();
            }
        }

        // Call update summary when forecast alerts change
        function triggerSummaryUpdate() {
            setTimeout(updateForecastSummary, 100);
        }

        // Trigger summary update after forecast operations
        $(document).on('click', '#add-item', triggerSummaryUpdate);
        $(document).on('change', '.raw-material-select', triggerSummaryUpdate);
        $(document).on('input', '.suggested-qty, .adjusted-qty', triggerSummaryUpdate);

        // Form validation and submission
        var isSubmitting = false;

        $('#formID').validate({
            rules: {
                store_id: {
                    required: true
                },
                request_type: {
                    required: true
                },
                request_date: {
                    required: true
                },
                status: {
                    required: true
                }
            },
            submitHandler: function(form) {
                if (isSubmitting) return false;

                // Check if at least one item exists
                if ($('#items-tbody tr td[colspan]').length > 0 || $('#items-tbody tr').length === 0) {
                    alert('Please add at least one item to the SPB');
                    return false;
                }

                isSubmitting = true;
                $('#loaderkdnknz').show();

                var formData = new FormData(form);

                $.ajax({
                        type: "POST",
                        url: $(form).attr('action'),
                        data: formData,
                        processData: false,
                        contentType: false,
                        dataType: "json",
                    })
                    .done(function(data) {
                        Swal.fire({
                            icon: data[0],
                            text: data[1],
                            showCancelButton: false,
                            confirmButtonColor: '#6c757d',
                            confirmButtonText: 'OK',
                            allowOutsideClick: false
                        }).then((result) => {
                            if (result.isConfirmed && data[0] == 'success') {
                                if ("{{$data->id}}" > 0) {
                                    window.location.href = "{{ route('item_requests.show', $data->id) }}";
                                } else {
                                    window.location.href = "{{ route('item_requests.index') }}";
                                }
                            }
                        });
                    })
                    .fail(function(xhr) {
                        let errorText = "Please contact the relevant team or try again.";

                        if (xhr.status === 422 && xhr.responseJSON.errors) {
                            const errors = xhr.responseJSON.errors;
                            errorText = '';

                            for (const key in errors) {
                                if (errors.hasOwnProperty(key)) {
                                    errorText += `<strong>${key}</strong> : ${errors[key].join(', ')}<br>`;
                                }
                            }
                        } else if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorText = xhr.responseJSON.message;
                        }

                        Swal.fire({
                            icon: "error",
                            title: "Validation Failed",
                            html: errorText,
                            confirmButtonColor: '#6c757d',
                            confirmButtonText: 'OK'
                        });
                    })
                    .always(function() {
                        isSubmitting = false;
                        $('#loaderkdnknz').hide();
                    });
            }
        });

        // Initial calculation for existing items
        $('.suggested-qty').trigger('input');
    });
</script>

@endsection