@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 card-outline card-warning">
                    <div class="card-header">
                        <h3 class="card-title">{{ $variables['judul'] }}</h3>
                        <div class="card-tools">
                            @if($data->status != 'Approved')
                            <a href="{{ route('item_requests.edit', $data->id) }}" class="btn btn-sm btn-warning button-cek-permission" data-permission="item_requests.edit">
                                <i class="fas fa-edit"></i> Ubah
                            </a>
                            <a href="{{ route('item_requests.destroy', $data->id) }}" class="btn btn-sm btn-warning button-cek-permission" data-permission="item_requests.destroy" data='delete' onclick="notificationBeforeDelete(event, this)">
                                <i class="fas fa-trash"></i> Hapus
                            </a>
                            @endif
                            @if($data->status == 'Approved')
                            <button type="button" class="btn btn-sm btn-warning button-cek-permission" data-permission="item_requests.generate_csv" id="generate-csv">
                                <i class="fas fa-file-csv"></i> Generate CSV
                            </button>
                            <button type="button" class="btn btn-sm btn-warning button-cek-permission" data-permission="item_requests.list_csv" id="list-csv">
                                <i class="fas fa-list"></i> Daftar CSV
                            </button>
                            @endif
                            <a href="{{ route('item_requests.index') }}" class="btn btn-sm btn-warning">
                                <i class="fas fa-arrow-left"></i> Kembali
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- SPB Header Info -->
                        <div class="row">
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <td width="40%"><strong>Nomor SPB</strong></td>
                                        <td>: <span class="badge badge-info">{{ $data->spb_number }}</span></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Store</strong></td>
                                        <td>: {{ $data->store->name ?? '-' }}</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Tipe Permintaan</strong></td>
                                        <td>: <span class="badge badge-{{ $data->request_type == 'Regular' ? 'info' : 'dark' }}">{{ $data->request_type }}</span></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Status</strong></td>
                                        <td>: 
                                            @if($data->status == 'Draft')
                                            <span class="badge badge-secondary">{{ $data->status }}</span>
                                            @elseif($data->status == 'Submitted')
                                            <span class="badge badge-success">{{ $data->status }}</span>
                                            @elseif($data->status == 'Approved')
                                            <span class="badge badge-primary">{{ $data->status }}</span>
                                            @else
                                            <span class="badge badge-secondary">{{ $data->status }}</span>
                                            @endif
                                        </td>
                                    </tr>
                                    <tr>
                                        <td><strong>Tanggal Permintaan</strong></td>
                                        <td>: {{ $data->request_date->format('d/m/Y') }}</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Tanggal Pengiriman</strong></td>
                                        <td>: {{ $data->delivery_date ? $data->delivery_date->format('d/m/Y') : '-' }}</td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <td width="40%"><strong>Stock Opname</strong></td>
                                        <td>: 
                                            @if($data->stockOpname)
                                            <a href="{{ route('stock_opnames.show', $data->stockOpname->id) }}">
                                                {{ $data->stockOpname->so_number }}
                                            </a>
                                            @else
                                            -
                                            @endif
                                        </td>
                                    </tr>
                                    <tr>
                                        <td><strong>Jadwal Pengiriman</strong></td>
                                        <td>: 
                                            @if($data->ShipmentDelivery)
                                            {{ $data->ShipmentDelivery->day_name }} - {{ $data->ShipmentDelivery->armadaType->name ?? '' }}
                                            @else
                                            -
                                            @endif
                                        </td>
                                    </tr>
                                    <tr>
                                        <td><strong>Dibuat Oleh</strong></td>
                                        <td>: {{ $data->creator->fullname ?? 'System' }} ({{ $data->created_at->format('d/m/Y H:i') }})</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Diubah Oleh</strong></td>
                                        <td>: {{ $data->modificator->fullname ?? '-' }} ({{ $data->updated_at ? $data->updated_at->format('d/m/Y H:i') : '-' }})</td>
                                    </tr>
                                    @if($data->csv_generated_at)
                                    <tr>
                                        <td><strong>CSV Dibuat</strong></td>
                                        <td>: {{ $data->csvGeneratedBy->name ?? 'System' }} ({{ $data->csv_generated_at->format('d/m/Y H:i') }})</td>
                                    </tr>
                                    @endif
                                    <tr>
                                        <td><strong>Total Item</strong></td>
                                        <td>: {{ count($data->details) }} item</td>
                                    </tr>
                                </table>
                            </div>
                        </div>

                        @if($data->notes)
                        <div class="row">
                            <div class="col-12">
                                <table class="table table-borderless">
                                    <tr>
                                        <td width="20%"><strong>Catatan</strong></td>
                                        <td>: {{ $data->notes }}</td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                        @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 SPB</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-hover table-sm">
                                                <thead class="bg-warning">
                                                    <tr>
                                                        <th width="4%">No</th>
                                                        <th width="10%">Kode</th>
                                                        <th width="15%">Item</th>
                                                        <th width="6%">UOM</th>
                                                        <th width="8%">Forecast</th>
                                                        <th width="8%">Qty SO</th>
                                                        <th width="8%">Qty TSM</th>
                                                        <th width="8%">Saran</th>
                                                        <th width="8%">Penyesuaian</th>
                                                        <th width="8%">Qty Final</th>
                                                        <th width="10%">Alert Forecast</th>
                                                        <th width="8%">Status DOI</th>
                                                        <th width="9%">Catatan</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    @forelse($data->details as $index => $detail)
                                                    <tr>
                                                        <td>{{ $index + 1 }}</td>
                                                        <td>{{ $detail->rawMaterial->code ?? '' }}</td>
                                                        <td>{{ $detail->rawMaterial->name ?? '' }}</td>
                                                        <td>{{ $detail->rawMaterial->uom ?? '' }}</td>
                                                        <td class="text-right">{{ number_format($detail->forecast_qty, 2) }}</td>
                                                        <td class="text-right">{{ number_format($detail->so_qty, 2) }}</td>
                                                        <td class="text-right">{{ number_format($detail->tsm_qty, 2) }}</td>
                                                        <td class="text-right">{{ number_format($detail->suggested_qty, 2) }}</td>
                                                        <td class="text-right">{{ number_format($detail->adjusted_qty, 2) }}</td>
                                                        <td class="text-right"><strong>{{ number_format($detail->final_qty, 2) }}</strong></td>
                                                        <td>
                                                            @php
                                                            $forecastQty = $detail->forecast_qty;
                                                            $finalQty = $detail->final_qty;
                                                            $variance = $forecastQty > 0 ? (($finalQty - $forecastQty) / $forecastQty) * 100 : 0;

                                                            if ($finalQty > $forecastQty) {
                                                            if ($variance > 20) {
                                                            $alertClass = 'danger';
                                                            $alertText = 'Over +' . number_format($variance, 1) . '%';
                                                            } else {
                                                            $alertClass = 'warning';
                                                            $alertText = 'Over +' . number_format($variance, 1) . '%';
                                                            }
                                                            } elseif ($finalQty < $forecastQty) {
                                                                if (abs($variance)> 20) {
                                                                $alertClass = 'info';
                                                                $alertText = 'Under -' . number_format(abs($variance), 1) . '%';
                                                                } else {
                                                                $alertClass = 'secondary';
                                                                $alertText = 'Under -' . number_format(abs($variance), 1) . '%';
                                                                }
                                                                } else {
                                                                $alertClass = 'success';
                                                                $alertText = 'Match';
                                                                }
                                                                @endphp

                                                                @if($forecastQty > 0)
                                                                <span class="badge badge-{{ $alertClass }}" title="Forecast: {{ number_format($forecastQty, 2) }}, Diminta: {{ number_format($finalQty, 2) }}">
                                                                    {{ $alertText }}
                                                                </span>
                                                                @else
                                                                <span class="badge badge-secondary">Tidak Ada Forecast</span>
                                                                @endif
                                                        </td>
                                                        <td>
                                                            @if($detail->alert_status)
                                                            <span class="badge badge-{{ $detail->alert_status == 'Critical' ? 'danger' : ($detail->alert_status == 'Normal' ? 'warning' : 'success') }}">
                                                                {{ $detail->alert_status }}
                                                            </span>
                                                            @else
                                                            -
                                                            @endif
                                                        </td>
                                                        <td>{{ $detail->notes ?? '-' }}</td>
                                                    </tr>
                                                    @empty
                                                    <tr>
                                                        <td colspan="13" class="text-center text-muted">Tidak ada item ditemukan</td>
                                                    </tr>
                                                    @endforelse
                                                </tbody>
                                                @if(count($data->details) > 0)
                                                <tfoot class="bg-light">
                                                    <tr>
                                                        <th colspan="9" class="text-right">Total Qty Final:</th>
                                                        <th class="text-right">{{ number_format($data->details->sum('final_qty'), 2) }}</th>
                                                        <th colspan="3"></th>
                                                    </tr>
                                                </tfoot>
                                                @endif
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<form action="" id="delete-form" method="post">
    @method('delete')
    @csrf
</form>

<script>
    $(document).ready(function() {
        // Generate CSV Files
        $('#generate-csv').click(function() {
            const btn = $(this);
            btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Generating...');

            $.ajax({
                url: '{{ route("item_requests.generate_csv", $data->id) }}',
                type: 'POST',
                data: {
                    _token: '{{ csrf_token() }}'
                },
                success: function(response) {
                    btn.prop('disabled', false).html('<i class="fa fa-file-csv"></i> Generate CSV');

                    if (response.success) {
                        let filesHtml = '<ul class="text-left">';
                        response.data.files.forEach(file => {
                            filesHtml += `<li><strong>${file.type}</strong>: ${file.filename} (${file.records} records)</li>`;
                        });
                        filesHtml += '</ul>';

                        Swal.fire({
                            icon: 'success',
                            title: 'CSV Berhasil Dibuat',
                            html: `<p>${response.message}</p>${filesHtml}`,
                            confirmButtonText: 'OK'
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Pembuatan Gagal',
                            text: response.message
                        });
                    }
                },
                error: function(xhr) {
                    btn.prop('disabled', false).html('<i class="fa fa-file-csv"></i> Generate CSV');

                    const message = xhr.responseJSON?.message || 'Terjadi kesalahan saat membuat file CSV';
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: message
                    });
                }
            });
        });

        // List CSV Files
        $('#list-csv').click(function() {
            $.ajax({
                url: '{{ route("item_requests.list_csv", $data->id) }}',
                type: 'GET',
                success: function(response) {
                    if (response.success && response.data.files.length > 0) {
                        let filesHtml = '<div class="table-responsive"><table class="table table-sm table-bordered">';
                        filesHtml += '<thead><tr><th>Tipe</th><th>Nama File</th><th>Jumlah</th><th>Ukuran</th><th>Aksi</th></tr></thead><tbody>';

                        response.data.files.forEach(file => {
                            const downloadUrl = '{{ route("item_requests.download_csv", $data->id) }}?file=' + encodeURIComponent(file.path);
                            filesHtml += `<tr>
                                <td><span class="badge badge-info">${file.type}</span></td>
                                <td>${file.filename}</td>
                                <td>${file.records}</td>
                                <td>${file.size}</td>
                                <td><a href="${downloadUrl}" class="btn btn-xs btn-success" target="_blank"><i class="fa fa-download"></i> Download</a></td>
                            </tr>`;
                        });

                        filesHtml += '</tbody></table></div>';
                        filesHtml += `<div class="mt-3"><button type="button" class="btn btn-sm btn-danger" id="delete-all-csv"><i class="fa fa-trash"></i> Hapus Semua File CSV</button></div>`;

                        Swal.fire({
                            icon: 'info',
                            title: 'File CSV yang Dibuat',
                            html: filesHtml,
                            width: '800px',
                            showConfirmButton: true,
                            confirmButtonText: 'Tutup'
                        });

                        // Handle delete all CSV
                        $(document).on('click', '#delete-all-csv', function() {
                            if (confirm('Apakah Anda yakin ingin menghapus semua file CSV untuk SPB ini?')) {
                                $.ajax({
                                    url: '{{ route("item_requests.delete_csv", $data->id) }}',
                                    type: 'DELETE',
                                    data: {
                                        _token: '{{ csrf_token() }}'
                                    },
                                    success: function(response) {
                                        if (response.success) {
                                            Swal.fire({
                                                icon: 'success',
                                                title: 'Terhapus',
                                                text: response.message
                                            }).then(() => {
                                                location.reload();
                                            });
                                        }
                                    },
                                    error: function(xhr) {
                                        alert('Gagal menghapus file CSV: ' + (xhr.responseJSON?.message || 'Error tidak diketahui'));
                                    }
                                });
                            }
                        });
                    } else {
                        Swal.fire({
                            icon: 'info',
                            title: 'No CSV Files',
                            text: 'No CSV files have been generated for this SPB yet.'
                        });
                    }
                },
                error: function(xhr) {
                    const message = xhr.responseJSON?.message || 'Error occurred while listing CSV files';
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: message
                    });
                }
            });
        });
    });
</script>
@endsection