<?php $__env->startSection('content'); ?>
    <form novalidate action="<?php echo e(route('daily-report.update', $daily->id)); ?>" method="POST">
        <?php echo csrf_field(); ?>
        <?php echo method_field('PUT'); ?>
        <style>
            .accordion-button:not(.collapsed) {
                background-color: white;
            }

            .accordion-button::after {
                display: none !important;
            }
        </style>

        <div class="container">
            <h5><strong>History Daily Report,</strong> <?php echo e($daily->form->title ?? ''); ?> </h5>
            <hr>

            <div class="accordion" id="accordionExample">
                <?php $__currentLoopData = $daily->form->sections; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $section): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <?php if(count($section->items) == 0): ?>
                        <?php continue; ?>
                    <?php endif; ?>
                    <div class="accordion-item shadow-sm mb-2">
                        <h2 class="accordion-header border border-b">
                            <div class="d-flex justify-content-between align-items-center w-100 pe-4">
                                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse"
                                    data-bs-target="#section-<?php echo e($index); ?>" aria-expanded="false"
                                    aria-controls="section-<?php echo e($index); ?>">
                                    <h5 class="mb-0"><strong><?php echo e($section->name); ?></strong></h5>
                                </button>
                            </div>
                        </h2>

                        <div id="section-<?php echo e($index); ?>" class="accordion-collapse collapse" data-bs-parent="#accordionExample">
                            <div class="accordion-body">
                                <div class="table-responsive">
                                    <table class="table table-hover table-striped table-condensed table-bordered table-sm">
                                        <thead>
                                            <tr>
                                                <th>Inspection Item</th>
                                                <th>Catatan</th>
                                                <?php $__currentLoopData = $status; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                    <th class="text-center"><?php echo e($item->name); ?></th>
                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php $__currentLoopData = $section->items; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <?php
                                                    $currentDailyItem = $daily->detail->firstWhere(
                                                        'forms_items_id',
                                                        $item->id,
                                                    );
                                                    $statusItem = $item->status->pluck('name')->toArray();
                                                ?>
                                                <tr>
                                                    <input type="hidden" name="forms_items_id[<?php echo e($index); ?>][<?php echo e($key); ?>]"
                                                        value="<?php echo e($item->id); ?>">

                                                    <td><?php echo e($item->name); ?></td>

                                                    <td style="width: 30%">
                                                        <input type="text" name="catatan[<?php echo e($index); ?>][<?php echo e($key); ?>]"
                                                            class="form-control" value="<?php echo e($currentDailyItem->catatan ?? ''); ?>">
                                                    </td>

                                                    <?php $__currentLoopData = $status; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $statusKey => $stTd): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                        <?php
                                                            $isChecked =
                                                                optional($currentDailyItem)->status == $stTd->name;
                                                        ?>
                                                        <td class="text-center">
                                                            <input required type="radio" class="btn-check"
                                                                name="status[<?php echo e($index); ?>][<?php echo e($key); ?>]"
                                                                id="status-<?php echo e($index); ?>-<?php echo e($key); ?>-<?php echo e($statusKey); ?>"
                                                                value="<?php echo e($stTd->id); ?>" <?php echo e($isChecked ? 'checked' : ''); ?>>
                                                            <?php if($stTd->name === 'Baik' && in_array('Baik', $statusItem)): ?>
                                                                <label class="btn btn-outline-success"
                                                                    for="status-<?php echo e($index); ?>-<?php echo e($key); ?>-<?php echo e($statusKey); ?>"><?php echo e($stTd->name); ?></label>
                                                            <?php elseif($stTd->name === 'Rusak' && in_array('Rusak', $statusItem)): ?>
                                                                <label class="btn btn-outline-danger"
                                                                    for="status-<?php echo e($index); ?>-<?php echo e($key); ?>-<?php echo e($statusKey); ?>"><?php echo e($stTd->name); ?></label>
                                                            <?php elseif($stTd->name === 'Cukup' && in_array('Cukup', $statusItem)): ?>
                                                                <label class="btn btn-outline-warning"
                                                                    for="status-<?php echo e($index); ?>-<?php echo e($key); ?>-<?php echo e($statusKey); ?>"><?php echo e($stTd->name); ?></label>
                                                            <?php elseif($stTd->name === 'N/A' && in_array('N/A', $statusItem)): ?>
                                                                <label class="btn btn-outline-primary"
                                                                    for="status-<?php echo e($index); ?>-<?php echo e($key); ?>-<?php echo e($statusKey); ?>"><?php echo e($stTd->name); ?></label>
                                                            <?php endif; ?>
                                                        </td>
                                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                </tr>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </div>

            
            <div class="col-lg-12 mt-4">
                <div class="form-group mb-3">
                    <textarea name="downtime_note" id="downtime_note" class="form-control" cols="30" rows="5"
                        placeholder="Note"><?php echo e($daily->downtime_note ?? ''); ?></textarea>
                </div>
            </div>
            <div class="d-flex justify-content-between">
                <div>
                    <button type="submit" id="submit" class="btn btn-primary">Lanjutkan</button>
                </div>
            </div>
        </div>
    </form>
<?php $__env->stopSection(); ?>
<?php $__env->startPush('extraJS'); ?>
    <script>
        <?php if(session('success')): ?>
            Swal.fire({
                icon: 'success',
                title: 'Berhasil!',
                text: "<?php echo e(session('success')); ?>",
                timer: 2000,
                showConfirmButton: false
            });
        <?php endif; ?>

        <?php if(session('error')): ?>
            Swal.fire({
                icon: 'error',
                title: 'Oops...',
                text: "<?php echo e(session('error')); ?>",
            });
        <?php endif; ?>
    </script>
    <script>
        let isSubmitted = false;
        const dailyId = "<?php echo e($daily->id); ?>";

        $(document).ready(function () {
            // Jika user sudah pernah keluar dari halaman tanpa submit
            const isCanceled = localStorage.getItem(`daily_canceled_${dailyId}`);
            if (isCanceled) {
                const nextBtn = document.getElementById('nextBtn');
                if (nextBtn) {
                    nextBtn.disabled = true;
                    nextBtn.classList.add('btn-secondary');
                    nextBtn.classList.remove('btn-primary');
                    nextBtn.innerText = 'Data sudah dibatalkan';
                }
            }

            // Validasi dan submit form
            $('form').on('submit', function (e) {
                let valid = true;
                let firstInvalid = null;
                isSubmitted = true;

                // Hapus tanda * lama
                $('table tr td:first span.text-danger').remove();

                // Loop tiap input radio unik berdasarkan nama
                const radioNames = [];
                $('input[type="radio"]').each(function () {
                    const name = $(this).attr('name');
                    if (!radioNames.includes(name)) {
                        radioNames.push(name);
                    }
                });

                // Periksa setiap pertanyaan
                radioNames.forEach(function (name) {
                    const group = $(`input[name='${name}']`);
                    const hasChecked = group.is(':checked');

                    if (!hasChecked) {
                        valid = false;
                        const firstRow = group.first().closest('tr');
                        const tdLabel = firstRow.find('td:first');

                        // Tambahkan tanda * merah jika belum ada
                        if (tdLabel.find('span.text-danger').length === 0) {
                            tdLabel.append(
                                ' <span class="text-danger" style="font-size:20px;">*</span>');
                        }

                        if (!firstInvalid) firstInvalid = firstRow;

                        // Ambil nomor group utama dari name (contoh: status[4][9] → 4)
                        const mainGroup = name.match(/status\[(\d+)\]/);
                        if (mainGroup && mainGroup[1]) {
                            const groupId = mainGroup[1];
                            const collapse = $(`#collapse-${groupId}`);
                            if (collapse.length) {
                                const trigger = $(`button[data-bs-target="#collapse-${groupId}"]`);
                                trigger.removeClass('collapsed');
                                collapse.addClass('show');
                            }
                        }
                    }
                });

                if (!valid) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Validasi Gagal',
                        text: 'Masih ada pertanyaan yang belum dijawab!',
                        confirmButtonText: 'Periksa Kembali'
                    });

                    if (firstInvalid) {
                        $('html, body').animate({
                            scrollTop: firstInvalid.offset().top - 150
                        }, 600);
                    }

                    e.preventDefault();
                    return;
                }

                // Jika semua valid
                Swal.fire({
                    title: 'Sedang Proses',
                    text: 'Mohon tunggu sebentar...',
                    allowOutsideClick: false,
                    didOpen: () => Swal.showLoading()
                });

                // Hapus flag cancel jika berhasil submit
                localStorage.removeItem(`daily_canceled_${dailyId}`);

                this.submit();
            });

            // Hapus tanda * kalau user pilih salah satu radio
            $(document).on('change', 'input[type="radio"]', function () {
                const name = $(this).attr('name');
                const firstRow = $(`input[name='${name}']`).first().closest('tr');
                firstRow.find('td:first span.text-danger').remove();
            });
        });

        // Saat user keluar dari halaman (klik back / close tab / reload)
        window.addEventListener('beforeunload', function (e) {
            if (!isSubmitted) {
                const url = `<?php echo e(route('daily-report.update', ':id')); ?>`.replace(':id', dailyId);

                const csrfToken = '<?php echo e(csrf_token()); ?>';

                const formData = new FormData();
                formData.append('_method', 'DELETE');
                formData.append('_token', csrfToken);

                // Simpan info bahwa user membatalkan
                localStorage.setItem(`daily_canceled_${dailyId}`, 'true');

                navigator.sendBeacon(url, formData);
            }
        });
    </script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('template.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/pmme2286/public_html/docu/vendor1/resources/views/daily/edit.blade.php ENDPATH**/ ?>