<?php $__env->startSection('heading', 'Tambah Service'); ?>

<?php $__env->startSection('content'); ?>
<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1>Tambah Service</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo e(route('home')); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo e(route('services.index')); ?>">Service </a></li>
                    <li class="breadcrumb-item active">Tambah</li>
                </ol>
            </div>
        </div>
    </div>
</section>

<section class="content">
    <div class="container-fluid">
        <form action="<?php echo e(route('services.store')); ?>" method="POST" id="serviceForm">
            <?php echo csrf_field(); ?>
            <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 <?php $__errorArgs = ['device_type'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" required>
                                            <option value="">-- Pilih Jenis --</option>
                                            <option value="Handphone" <?php echo e(old('device_type') == 'Handphone' ? 'selected' : ''); ?>>Handphone</option>
                                            <option value="Tablet" <?php echo e(old('device_type') == 'Tablet' ? 'selected' : ''); ?>>Tablet</option>
                                            <option value="Laptop" <?php echo e(old('device_type') == 'Laptop' ? 'selected' : ''); ?>>Laptop</option>
                                            <option value="Smartwatch" <?php echo e(old('device_type') == 'Smartwatch' ? 'selected' : ''); ?>>Smartwatch</option>
                                            <option value="Lainnya" <?php echo e(old('device_type') == 'Lainnya' ? 'selected' : ''); ?>>Lainnya</option>
                                        </select>
                                        <?php $__errorArgs = ['device_type'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                    </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 <?php $__errorArgs = ['device_brand'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                            placeholder="Contoh: Samsung, iPhone, Xiaomi" value="<?php echo e(old('device_brand')); ?>" required>
                                        <?php $__errorArgs = ['device_brand'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                    </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 <?php $__errorArgs = ['device_model'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                            placeholder="Contoh: Galaxy S23, iPhone 14 Pro" value="<?php echo e(old('device_model')); ?>" required>
                                        <?php $__errorArgs = ['device_model'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                    </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="<?php echo e(old('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 <?php $__errorArgs = ['complaint'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                    placeholder="Deskripsikan keluhan pelanggan..." required><?php echo e(old('complaint')); ?></textarea>
                                <?php $__errorArgs = ['complaint'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <div class="invalid-feedback"><?php echo e($message); ?></div>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>
                            <div class="form-group">
                                <label>Diagnosa Teknisi (Opsional)</label>
                                <textarea name="diagnosis" rows="3" class="form-control"
                                    placeholder="Hasil diagnosa awal teknisi..."><?php echo e(old('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">
                                        <tr class="text-center">
                                            <td colspan="5">Tidak ada spare part</td>
                                        </tr>
                                    </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">
                            <?php if(session('error')): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <?php echo e(session('error')); ?>

                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <?php endif; ?>

                            <div class="form-group">
                                <label>Tanggal Service <span class="text-danger">*</span></label>
                                <input type="date" name="service_date" class="form-control <?php $__errorArgs = ['service_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                    value="<?php echo e(old('service_date', date('Y-m-d'))); ?>" required>
                                <?php $__errorArgs = ['service_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <div class="invalid-feedback"><?php echo e($message); ?></div>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>

                            <div class="form-group">
                                <label>Customer <span class="text-danger">*</span></label>
                                <select name="customer_id" class="form-control select2 <?php $__errorArgs = ['customer_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" required>
                                    <option value="">-- Pilih Customer --</option>
                                    <?php $__currentLoopData = $customers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $customer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($customer->id); ?>" <?php echo e(old('customer_id') == $customer->id ? 'selected' : ''); ?>>
                                        <?php echo e($customer->name); ?> - <?php echo e($customer->phone); ?>

                                    </option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                                <?php $__errorArgs = ['customer_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <div class="invalid-feedback"><?php echo e($message); ?></div>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>

                            <div class="form-group">
                                <label>Cabang <span class="text-danger">*</span></label>
                                <select name="branch_id" class="form-control <?php $__errorArgs = ['branch_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" required>
                                    <option value="">-- Pilih Cabang --</option>
                                    <?php $__currentLoopData = $branches; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $branch): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($branch->id); ?>" <?php echo e(old('branch_id') == $branch->id ? 'selected' : ''); ?>>
                                        <?php echo e($branch->name); ?>

                                    </option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                                <?php $__errorArgs = ['branch_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <div class="invalid-feedback"><?php echo e($message); ?></div>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>

                            <div class="form-group">
                                <label>Teknisi</label>
                                <input type="text" class="form-control" value="<?php echo e(Auth::user()->name); ?>" disabled>
                                <input type="hidden" name="technician_id" value="<?php echo e(Auth::user()->id); ?>">
                            </div>

                            <div class="form-group">
                                <label>Prioritas</label>
                                <select name="priority" class="form-control">
                                    <option value="normal" <?php echo e(old('priority') == 'normal' ? 'selected' : ''); ?>>Normal</option>
                                    <option value="urgent" <?php echo e(old('priority') == 'urgent' ? 'selected' : ''); ?>>Urgent</option>
                                    <option value="very urgent" <?php echo e(old('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="<?php echo e(old('estimated_completion')); ?>">
                            </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="<?php echo e(old('service_fee', 0)); ?>" step="0.01">
                            </div>

                            <div class="form-group">
                                <label>Total Biaya Spare Part</label>
                                <input type="text" id="partsCostDisplay" class="form-control" value="Rp 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 0" readonly>
                                <input type="hidden" name="estimated_cost" id="estimatedCost" value="0">
                            </div>

                            <div class="form-group">
                                <label>Uang Muka (DP)</label>
                                <input type="number" name="down_payment" id="downPayment" class="form-control"
                                    placeholder="0" value="<?php echo e(old('down_payment', 0)); ?>" step="0.01">
                            </div>

                            <div class="form-group">
                                <label>Catatan</label>
                                <textarea name="notes" rows="3" class="form-control" placeholder="Catatan tambahan..."><?php echo e(old('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> Simpan Service
                            </button>
                            <a href="<?php echo e(route('services.index')); ?>" class="btn btn-secondary btn-block">
                                <i class="fas fa-arrow-left"></i> Kembali
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</section>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
$(document).ready(function() {
    $('.select2').select2();

    let sparePartIndex = 0;
    let products = <?php echo json_encode($products, 15, 512) ?>;

    console.log('Products loaded:', products);
    console.log('Add button exists:', $('#addSparePartBtn').length);

    // Add spare part row
    $('#addSparePartBtn').on('click', function(e) {
        e.preventDefault();
        console.log('Button clicked!');

        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>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp82\htdocs\umi-cell\resources\views/transaction/service/create.blade.php ENDPATH**/ ?>