@section('heading', 'Edit Service')
@extends('layouts.app')
@section('content')
<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1>Edit Service</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="{{route('home')}}">Home</a></li>
                    <li class="breadcrumb-item"><a href="{{route('services.index')}}">Service</a></li>
                    <li class="breadcrumb-item active">Edit</li>
                </ol>
            </div>
        </div>
    </div>
</section>

<section class="content">
    <div class="container-fluid">
        <form action="{{route('services.update', $service->id)}}" method="POST" id="serviceForm">
            @csrf
            @method('PUT')
            <div class="row">
                <div class="col-md-8">
                    <!-- Informasi Perangkat -->
                    <div class="card">
                        <div class="card-header bg-primary">
                            <h3 class="card-title">Informasi Perangkat</h3>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Jenis Perangkat <span class="text-danger">*</span></label>
                                        <select name="device_type" class="form-control @error('device_type') is-invalid @enderror" required>
                                            <option value="">-- Pilih Jenis --</option>
                                            <option value="Handphone" {{old('device_type', $service->device_type) == 'Handphone' ? 'selected' : ''}}>Handphone</option>
                                            <option value="Tablet" {{old('device_type', $service->device_type) == 'Tablet' ? 'selected' : ''}}>Tablet</option>
                                            <option value="Laptop" {{old('device_type', $service->device_type) == 'Laptop' ? 'selected' : ''}}>Laptop</option>
                                            <option value="Smartwatch" {{old('device_type', $service->device_type) == 'Smartwatch' ? 'selected' : ''}}>Smartwatch</option>
                                            <option value="Lainnya" {{old('device_type', $service->device_type) == 'Lainnya' ? 'selected' : ''}}>Lainnya</option>
                                        </select>
                                        @error('device_type')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Merek <span class="text-danger">*</span></label>
                                        <input type="text" name="device_brand" class="form-control @error('device_brand') is-invalid @enderror"
                                            placeholder="Contoh: Samsung, iPhone, Xiaomi" value="{{old('device_brand', $service->device_brand)}}" required>
                                        @error('device_brand')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Model <span class="text-danger">*</span></label>
                                        <input type="text" name="device_model" class="form-control @error('device_model') is-invalid @enderror"
                                            placeholder="Contoh: Galaxy S23, iPhone 14 Pro" value="{{old('device_model', $service->device_model)}}" required>
                                        @error('device_model')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>IMEI (Opsional)</label>
                                        <input type="text" name="imei" class="form-control"
                                            placeholder="Nomor IMEI perangkat" value="{{old('imei', $service->imei)}}">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Keluhan & Diagnosa -->
                    <div class="card">
                        <div class="card-header bg-info">
                            <h3 class="card-title">Keluhan & Diagnosa</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label>Keluhan Pelanggan <span class="text-danger">*</span></label>
                                <textarea name="complaint" rows="3" class="form-control @error('complaint') is-invalid @enderror"
                                    placeholder="Deskripsikan keluhan pelanggan..." required>{{old('complaint', $service->complaint)}}</textarea>
                                @error('complaint')
                                <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                            <div class="form-group">
                                <label>Diagnosa Teknisi (Opsional)</label>
                                <textarea name="diagnosis" rows="3" class="form-control"
                                    placeholder="Hasil diagnosa awal teknisi...">{{old('diagnosis', $service->diagnosis)}}</textarea>
                            </div>
                        </div>
                    </div>

                    <!-- Spare Part -->
                    <div class="card">
                        <div class="card-header bg-warning">
                            <h3 class="card-title">Spare Part Yang Digunakan</h3>
                        </div>
                        <div class="card-body">
                            <button type="button" class="btn btn-success btn-sm mb-3" id="addSparePartBtn">
                                <i class="fas fa-plus"></i> Tambah Spare Part
                            </button>
                            <div class="table-responsive">
                                <table class="table table-bordered" id="sparePartTable">
                                    <thead>
                                        <tr>
                                            <th style="width: 40%;">Spare Part</th>
                                            <th style="width: 15%;">Qty</th>
                                            <th style="width: 20%;">Harga Satuan</th>
                                            <th style="width: 20%;">Subtotal</th>
                                            <th style="width: 5%;">Aksi</th>
                                        </tr>
                                    </thead>
                                    <tbody id="sparePartBody">
                                        @if($service->serviceDetails->count() > 0)
                                            @foreach($service->serviceDetails as $index => $detail)
                                            <tr data-index="{{$index}}">
                                                <td>
                                                    <select name="products[{{$index}}][product_id]" class="form-control select2-sparePart product-select" data-index="{{$index}}" required>
                                                        <option value="">-- Pilih Spare Part --</option>
                                                        @foreach($products as $p)
                                                        <option value="{{$p->id}}" data-price="{{$p->productPrices[0]->selling_price ?? 0}}"
                                                            {{$detail->product_id == $p->id ? 'selected' : ''}}>
                                                            {{$p->name}}
                                                        </option>
                                                        @endforeach
                                                    </select>
                                                </td>
                                                <td>
                                                    <input type="number" name="products[{{$index}}][quantity]" class="form-control quantity-input"
                                                        data-index="{{$index}}" value="{{$detail->quantity}}" min="1" required>
                                                </td>
                                                <td>
                                                    <input type="number" name="products[{{$index}}][unit_price]" class="form-control unit-price-input"
                                                        data-index="{{$index}}" value="{{$detail->unit_price}}" step="0.01" required>
                                                </td>
                                                <td>
                                                    <input type="text" class="form-control subtotal-display" data-index="{{$index}}" value="Rp {{number_format($detail->subtotal, 0, ',', '.')}}" readonly>
                                                </td>
                                                <td>
                                                    <button type="button" class="btn btn-danger btn-sm remove-sparePart">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                            @endforeach
                                        @else
                                        <tr class="text-center">
                                            <td colspan="5">Tidak ada spare part</td>
                                        </tr>
                                        @endif
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-4">
                    <!-- Informasi Service -->
                    <div class="card">
                        <div class="card-header bg-success">
                            <h3 class="card-title">Informasi Service</h3>
                        </div>
                        <div class="card-body">
                            @if(session('error'))
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                {{ session('error') }}
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            @endif

                            <div class="form-group">
                                <label>No. Service</label>
                                <input type="text" class="form-control" value="{{$service->service_number}}" readonly>
                            </div>

                            <div class="form-group">
                                <label>Tanggal Service <span class="text-danger">*</span></label>
                                <input type="date" name="service_date" class="form-control @error('service_date') is-invalid @enderror"
                                    value="{{old('service_date', $service->service_date->format('Y-m-d'))}}" required>
                                @error('service_date')
                                <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="form-group">
                                <label>Customer <span class="text-danger">*</span></label>
                                <select name="customer_id" class="form-control select2 @error('customer_id') is-invalid @enderror" required>
                                    <option value="">-- Pilih Customer --</option>
                                    @foreach($customers as $customer)
                                    <option value="{{$customer->id}}" {{old('customer_id', $service->customer_id) == $customer->id ? 'selected' : ''}}>
                                        {{$customer->name}} - {{$customer->phone}}
                                    </option>
                                    @endforeach
                                </select>
                                @error('customer_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="form-group">
                                <label>Cabang <span class="text-danger">*</span></label>
                                <select name="branch_id" class="form-control @error('branch_id') is-invalid @enderror" required>
                                    <option value="">-- Pilih Cabang --</option>
                                    @foreach($branches as $branch)
                                    <option value="{{$branch->id}}" {{old('branch_id', $service->branch_id) == $branch->id ? 'selected' : ''}}>
                                        {{$branch->name}}
                                    </option>
                                    @endforeach
                                </select>
                                @error('branch_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="form-group">
                                <label>Teknisi</label>
                                <input type="text" class="form-control" value="{{$service->technician->name ?? Auth::user()->name}}" disabled>
                                <input type="hidden" name="technician_id" value="{{$service->technician_id ?? Auth::user()->id}}">
                            </div>

                            <div class="form-group">
                                <label>Status</label>
                                <select name="status" class="form-control">
                                    <option value="menunggu diagnosa" {{old('status', $service->status) == 'menunggu diagnosa' ? 'selected' : ''}}>Menunggu Diagnosa</option>
                                    <option value="sedang diagnosa" {{old('status', $service->status) == 'sedang diagnosa' ? 'selected' : ''}}>Sedang Diagnosa</option>
                                    <option value="menunggu persetujuan" {{old('status', $service->status) == 'menunggu persetujuan' ? 'selected' : ''}}>Menunggu Persetujuan</option>
                                    <option value="menunggu spare part" {{old('status', $service->status) == 'menunggu spare part' ? 'selected' : ''}}>Menunggu Spare Part</option>
                                    <option value="dalam pengerjaan" {{old('status', $service->status) == 'dalam pengerjaan' ? 'selected' : ''}}>Dalam Pengerjaan</option>
                                    <option value="quality control" {{old('status', $service->status) == 'quality control' ? 'selected' : ''}}>Quality Control</option>
                                    <option value="siap diambil" {{old('status', $service->status) == 'siap diambil' ? 'selected' : ''}}>Siap Diambil</option>
                                    <option value="selesai" {{old('status', $service->status) == 'selesai' ? 'selected' : ''}}>Selesai</option>
                                    <option value="dibatalkan" {{old('status', $service->status) == 'dibatalkan' ? 'selected' : ''}}>Dibatalkan</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <label>Prioritas</label>
                                <select name="priority" class="form-control">
                                    <option value="normal" {{old('priority', $service->priority) == 'normal' ? 'selected' : ''}}>Normal</option>
                                    <option value="urgent" {{old('priority', $service->priority) == 'urgent' ? 'selected' : ''}}>Urgent</option>
                                    <option value="very urgent" {{old('priority', $service->priority) == 'very urgent' ? 'selected' : ''}}>Very Urgent</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <label>Estimasi Selesai</label>
                                <input type="datetime-local" name="estimated_completion" class="form-control"
                                    value="{{old('estimated_completion', $service->estimated_completion ? $service->estimated_completion->format('Y-m-d\TH:i') : '')}}">
                            </div>

                            <hr>

                            <div class="form-group">
                                <label>Biaya Jasa Service</label>
                                <input type="number" name="service_fee" id="serviceFee" class="form-control"
                                    placeholder="0" value="{{old('service_fee', $service->service_fee)}}" step="0.01">
                            </div>

                            <div class="form-group">
                                <label>Total Biaya Spare Part</label>
                                <input type="text" id="partsCostDisplay" class="form-control" value="Rp {{number_format($service->parts_cost, 0, ',', '.')}}" readonly>
                            </div>

                            <div class="form-group">
                                <label>Estimasi Total Biaya</label>
                                <input type="text" id="estimatedCostDisplay" class="form-control font-weight-bold" value="Rp {{number_format($service->total_cost, 0, ',', '.')}}" readonly>
                                <input type="hidden" name="estimated_cost" id="estimatedCost" value="{{$service->total_cost}}">
                            </div>

                            <div class="form-group">
                                <label>Uang Muka (DP)</label>
                                <input type="number" name="down_payment" id="downPayment" class="form-control"
                                    placeholder="0" value="{{old('down_payment', $service->down_payment)}}" step="0.01">
                            </div>

                            <div class="form-group">
                                <label>Catatan</label>
                                <textarea name="notes" rows="3" class="form-control" placeholder="Catatan tambahan...">{{old('notes', $service->notes)}}</textarea>
                            </div>
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div class="card">
                        <div class="card-body">
                            <button type="submit" class="btn btn-success btn-block">
                                <i class="fas fa-save"></i> Update Service
                            </button>
                            <a href="{{route('services.show', $service->id)}}" class="btn btn-secondary btn-block">
                                <i class="fas fa-arrow-left"></i> Kembali
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</section>
@endsection

@push('scripts')
<script>
$(document).ready(function() {
    $('.select2').select2();

    // Initialize select2 for existing spare part rows
    $('.select2-sparePart').select2({
        placeholder: '-- Pilih Spare Part --',
        allowClear: true,
        width: '100%'
    });

    let sparePartIndex = {{$service->serviceDetails->count()}};
    let products = @json($products);

    // Add spare part row
    $('#addSparePartBtn').click(function() {
        const emptyRow = $('#sparePartBody tr.text-center');
        if (emptyRow.length) {
            emptyRow.remove();
        }

        let productOptions = '';
        if (products && products.length > 0) {
            productOptions = products.map(p => {
                const price = (p.product_prices && p.product_prices[0]) ? p.product_prices[0].selling_price : 0;
                return `<option value="${p.id}" data-price="${price}">${p.name}</option>`;
            }).join('');
        }

        let html = `
            <tr data-index="${sparePartIndex}">
                <td>
                    <select name="products[${sparePartIndex}][product_id]" class="form-control select2-sparePart product-select" data-index="${sparePartIndex}" required>
                        <option value="">-- Pilih Spare Part --</option>
                        ${productOptions}
                    </select>
                </td>
                <td>
                    <input type="number" name="products[${sparePartIndex}][quantity]" class="form-control quantity-input"
                        data-index="${sparePartIndex}" value="1" min="1" required>
                </td>
                <td>
                    <input type="number" name="products[${sparePartIndex}][unit_price]" class="form-control unit-price-input"
                        data-index="${sparePartIndex}" value="0" step="0.01" required>
                </td>
                <td>
                    <input type="text" class="form-control subtotal-display" data-index="${sparePartIndex}" value="Rp 0" readonly>
                </td>
                <td>
                    <button type="button" class="btn btn-danger btn-sm remove-sparePart">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            </tr>
        `;

        $('#sparePartBody').append(html);

        // Initialize select2 for the newly added row
        $(`select[name="products[${sparePartIndex}][product_id]"]`).select2({
            placeholder: '-- Pilih Spare Part --',
            allowClear: true,
            width: '100%'
        });

        sparePartIndex++;
        calculateTotal();
    });

    // Remove spare part row
    $(document).on('click', '.remove-sparePart', function() {
        // Destroy select2 before removing row
        $(this).closest('tr').find('.select2-sparePart').select2('destroy');
        $(this).closest('tr').remove();

        if ($('#sparePartBody tr').length === 0) {
            $('#sparePartBody').html('<tr class="text-center"><td colspan="5">Tidak ada spare part</td></tr>');
        }

        calculateTotal();
    });

    // When product selected, auto-fill price
    $(document).on('change', '.product-select', function() {
        const index = $(this).data('index');
        const price = $(this).find(':selected').data('price') || 0;
        $(`.unit-price-input[data-index="${index}"]`).val(price);
        calculateSubtotal(index);
    });

    // When quantity or price changes
    $(document).on('input', '.quantity-input, .unit-price-input', function() {
        const index = $(this).data('index');
        calculateSubtotal(index);
    });

    // When service fee or down payment changes
    $('#serviceFee, #downPayment').on('input', function() {
        calculateTotal();
    });

    function calculateSubtotal(index) {
        const qty = parseFloat($(`.quantity-input[data-index="${index}"]`).val()) || 0;
        const price = parseFloat($(`.unit-price-input[data-index="${index}"]`).val()) || 0;
        const subtotal = qty * price;

        $(`.subtotal-display[data-index="${index}"]`).val('Rp ' + formatNumber(subtotal));
        calculateTotal();
    }

    function calculateTotal() {
        let partsCost = 0;

        $('.unit-price-input').each(function() {
            const index = $(this).data('index');
            const qty = parseFloat($(`.quantity-input[data-index="${index}"]`).val()) || 0;
            const price = parseFloat($(this).val()) || 0;
            partsCost += (qty * price);
        });

        const serviceFee = parseFloat($('#serviceFee').val()) || 0;
        const totalCost = partsCost + serviceFee;

        $('#partsCostDisplay').val('Rp ' + formatNumber(partsCost));
        $('#estimatedCostDisplay').val('Rp ' + formatNumber(totalCost));
        $('#estimatedCost').val(totalCost);
    }

    function formatNumber(num) {
        return num.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    }

    // Initial calculation
    calculateTotal();
});
</script>
@endpush
