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

                            <!-- Basic Information -->
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="code" class="font-weight-bold">Kode</label>
                                        <small class="text-muted text-xs">*({{ $data->id > 0 ? 'Kode tidak dapat diubah' : 'Otomatis dibuat jika kosong' }})</small>
                                        <input value="{{ old('code', $data->code ?? '') }}" type="text" class="form-control form-control-sm" name="code" id="code" {{ $data->id > 0 ? 'readonly' : '' }}>
                                    </div>

                                    <div class="form-group">
                                        <label for="name" class="font-weight-bold">Nama <span class="text-danger">*</span></label>
                                        <small class="text-muted text-xs">*(Nama item olahan (contoh: Kah Mie Special))</small>
                                        <input value="{{ old('name', $data->name ?? '') }}" type="text" class="form-control form-control-sm" name="name" id="name" required maxlength="255">
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="description" class="font-weight-bold">Deskripsi</label>
                                        <small class="text-muted text-xs">*(Deskripsi item olahan)</small>
                                        <textarea class="form-control form-control-sm" name="description" id="description" rows="3">{{ old('description', $data->description ?? '') }}</textarea>
                                    </div>

                                    <div class="form-group">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="is_active" id="is_active" value="1" {{ old('is_active', $data->is_active ?? true) ? 'checked' : '' }}>
                                            <label class="form-check-label font-weight-bold" for="is_active">
                                                Aktif - Aktifkan FSTR ini
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Recipe Details -->
                            <div class="row">
                                <div class="col-12">
                                    <div class="card">
                                        <div class="card-header card-outline card-warning">
                                            <h5 class="mb-0">Detail Resep</h5>
                                            <div class="card-tools">
                                                <button type="button" class="btn btn-sm btn-info" onclick="addDetail()">
                                                    <i class="fa fa-plus"></i> Tambah Bahan
                                                </button>
                                            </div>
                                        </div>
                                        <div class="card-body">
                                            <div class="table-responsive">
                                                <table class="table table-hover table-sm" id="detailsTable">
                                                    <thead class="bg-warning">
                                                        <tr>
                                                            <th width="25%">Item <span class="text-danger">*</span></th>
                                                            <th width="12%">Jumlah <span class="text-danger">*</span></th>
                                                            <th width="10%">UOM <span class="text-danger">*</span></th>
                                                            <th width="15%">Biaya UOM <span class="text-danger">*</span></th>
                                                            <th width="15%">Total Biaya</th>
                                                            <th width="18%">Catatan</th>
                                                            <th width="5%">Aksi</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody id="detailsBody">
                                                        @if($data->id > 0 && $data->fstrDetails)
                                                        @foreach($data->fstrDetails as $index => $detail)
                                                        <tr>
                                                            <td>
                                                                <select class="form-control form-control-sm select2" name="details[{{ $index }}][raw_material_id]" required>
                                                                    <option value="">Pilih Item</option>
                                                                    @foreach($variables['rawMaterials'] as $rawMaterial)
                                                                    <option value="{{ $rawMaterial->id }}" {{ $detail->raw_material_id == $rawMaterial->id ? 'selected' : '' }}>
                                                                        {{ $rawMaterial->code }} - {{ $rawMaterial->name }}
                                                                    </option>
                                                                    @endforeach
                                                                </select>
                                                            </td>
                                                            <td>
                                                                <input type="number" step="0.0001" class="form-control form-control-sm quantity-input" name="details[{{ $index }}][quantity]" value="{{ $detail->quantity }}" required min="0.0001">
                                                            </td>
                                                            <td>
                                                                <input type="text" class="form-control form-control-sm" name="details[{{ $index }}][uom]" value="{{ $detail->uom }}" required maxlength="10">
                                                            </td>
                                                            <td>
                                                                <input type="number" step="0.01" class="form-control form-control-sm unit-cost-input" name="details[{{ $index }}][unit_cost]" value="{{ $detail->unit_cost }}" required min="0">
                                                            </td>
                                                            <td>
                                                                <input type="text" class="form-control form-control-sm total-cost-display" readonly value="Rp {{ number_format($detail->total_cost, 0, ',', '.') }}">
                                                            </td>
                                                            <td>
                                                                <input type="text" class="form-control form-control-sm" name="details[{{ $index }}][notes]" value="{{ $detail->notes }}" maxlength="255">
                                                            </td>
                                                            <td>
                                                                <button type="button" class="btn btn-sm btn-danger" onclick="removeDetail(this)">
                                                                    <i class="fa fa-trash"></i>
                                                                </button>
                                                            </td>
                                                        </tr>
                                                        @endforeach
                                                        @endif
                                                    </tbody>
                                                    <tfoot class="bg-light">
                                                        <tr>
                                                            <th colspan="4" class="text-right">Total Biaya Resep:</th>
                                                            <th id="grandTotal">Rp 0</th>
                                                            <th colspan="2"></th>
                                                        </tr>
                                                    </tfoot>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

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

<script>
    let detailIndex = {{$data->id > 0 && $data->fstrDetails ? $data->fstrDetails->count() : 0}};

    $(document).ready(function() {
        // Initialize select2 for existing rows
        $('.select2').select2({
            width: '100%'
        });

        // Calculate initial totals
        calculateGrandTotal();

        // Add first row if creating new
        @if($data->id == 0)
        addDetail();
        @endif

        $('#formID').on('submit', function(e) {
            e.preventDefault();

            // Validate at least one detail
            if ($('#detailsBody tr').length === 0) {
                Swal.fire({
                    title: 'Error!',
                    text: 'Minimal satu bahan harus ditambahkan',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
                return;
            }

            const form = this;
            const formData = new FormData(form);

            // Show loading
            Swal.fire({
                title: 'Menyimpan...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            $.ajax({
                type: "POST",
                url: $(form).attr('action'),
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    Swal.fire({
                        title: 'Berhasil!',
                        text: 'FSTR berhasil disimpan',
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(() => {
                        window.location.href = "{{ route('fstrs.index') }}";
                    });
                },
                error: function(xhr) {
                    let message = 'Terjadi kesalahan';
                    if (xhr.responseJSON && xhr.responseJSON.errors) {
                        const errors = xhr.responseJSON.errors;
                        message = Object.values(errors).flat().join('\n');
                    } else if (xhr.responseJSON && xhr.responseJSON.message) {
                        message = xhr.responseJSON.message;
                    }

                    Swal.fire({
                        title: 'Error!',
                        text: message,
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            });
        });
    });

    function addDetail() {
        const rawMaterialOptions = `
        <option value="">Pilih Item</option>
        @foreach($variables['rawMaterials'] as $rawMaterial)
        <option value="{{ $rawMaterial->id }}">{{ $rawMaterial->code }} - {{ $rawMaterial->name }}</option>
        @endforeach
        `;

        const row = `
        <tr>
            <td>
                <select class="form-control form-control-sm select2" name="details[${detailIndex}][raw_material_id]" required>
                    ${rawMaterialOptions}
                </select>
            </td>
            <td>
                <input type="number" step="0.0001" class="form-control form-control-sm quantity-input" name="details[${detailIndex}][quantity]" required min="0.0001">
            </td>
            <td>
                <input type="text" class="form-control form-control-sm" name="details[${detailIndex}][uom]" required maxlength="10">
            </td>
            <td>
                <input type="number" step="0.01" class="form-control form-control-sm unit-cost-input" name="details[${detailIndex}][unit_cost]" required min="0">
            </td>
            <td>
                <input type="text" class="form-control form-control-sm total-cost-display" readonly value="Rp 0">
            </td>
            <td>
                <input type="text" class="form-control form-control-sm" name="details[${detailIndex}][notes]" maxlength="255">
            </td>
            <td>
                <button type="button" class="btn btn-sm btn-danger" onclick="removeDetail(this)">
                    <i class="fa fa-trash"></i>
                </button>
            </td>
        </tr>
        `;

        $('#detailsBody').append(row);

        // Initialize select2 for new row
        $(`select[name="details[${detailIndex}][raw_material_id]"]`).select2({
            width: '100%'
        });

        detailIndex++;
    }

    function removeDetail(button) {
        $(button).closest('tr').remove();
        calculateGrandTotal();
    }

    // Calculate total cost when quantity or unit cost changes
    $(document).on('input', '.quantity-input, .unit-cost-input', function() {
        const row = $(this).closest('tr');
        const quantity = parseFloat(row.find('.quantity-input').val()) || 0;
        const unitCost = parseFloat(row.find('.unit-cost-input').val()) || 0;
        const totalCost = quantity * unitCost;

        row.find('.total-cost-display').val('Rp ' + totalCost.toLocaleString('id-ID'));

        calculateGrandTotal();
    });

    function calculateGrandTotal() {
        let grandTotal = 0;

        $('#detailsBody tr').each(function() {
            const quantity = parseFloat($(this).find('.quantity-input').val()) || 0;
            const unitCost = parseFloat($(this).find('.unit-cost-input').val()) || 0;
            grandTotal += quantity * unitCost;
        });

        $('#grandTotal').text('Rp ' + grandTotal.toLocaleString('id-ID'));
    }
</script>
@endsection