<div class="modal fade" id="modalEdit" tabindex="-1" aria-labelledby="modalTambahRoleLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <form id="formEdit" enctype="multipart/form-data">
            @csrf
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Ubah TBM</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="edit-id" id="edit-id">

                    <div class="row">
                        @php
                            $isAdmin = strtolower(auth()->user()->role->role) == "admin";
                            $location_id = auth()->user()->location_id;
                        @endphp
                              <div class="col-md-6 col-12">
                            <div class="mb-3">
                                <label for="date" class="form-label">Tanggal</label>
                                <input type="datetime-local" name="date" id="edit-date" required class="form-control"
                                    placeholder="Masukkan nama">
                            </div>
                        </div>
                        <div class="col-md-6 col-12">
                            <div class="mb-3">
                                <label for="location_id" class="form-label">Lokasi</label>
                                <select name="location_id" id="edit-location_id" class="form-control lokasi">
                                    @foreach ($location as $l)
                                        <option {{!$isAdmin && $location_id == $l ? "selected" : ""  }} value="{{$l->id}}">
                                            {{$l->name}}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                    </div>

                    <div class="mb-3">
                        <label for="topic" class="form-label">Topik</label>
                        <textarea name="topic" class="form-control" rows="2" id="edit-topic" required></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="name" class="form-label">Safety Officer</label>
                        <input type="text" name="name" id="edit-name" readonly required class="form-control"
                            placeholder="Masukkan nama">
                    </div>

                    <label for="description" class="form-label w-100">Peserta</label>
                    <div class="mb-3">
                        <div class="participant row g-4  mt-1">
                            @for ($i = 0; $i < 5; $i++)
                                <div class="col-md-3 col-6 d-flex align-items-center g-2">
                                    <span>{{ $i + 1 }}.</span>
                                    <div class="">
                                        <input type="text" name="participant[{{ $i }}]" class="form-control ms-2" value=""
                                            placeholder="Masukkan nama" id="">

                                    </div>
                                </div>
                                <div class="col-md-3 col-6 d-flex align-items-center g-2">
                                    <span>{{ $i + 1 + 5 }}.</span>
                                    <div class="">
                                        <input type="text" name="participant[{{ $i + 5 }}]" class="form-control ms-2"
                                            value="" placeholder="Masukkan nama" id="">
                                    </div>
                                </div>
                                <div class="col-md-3 col-6 d-flex align-items-center g-2">
                                    <span>{{ $i + 1 + 10}}.</span>
                                    <div class="">
                                        <input type="text" name="participant[{{ $i + 10}}]" class="form-control ms-2"
                                            value="" placeholder="Masukkan nama" id="">
                                    </div>
                                </div>
                                <div class="col-md-3 col-6 d-flex align-items-center g-2">
                                    <span>{{ $i + 1 + 15 }}.</span>
                                    <div class="">
                                        <input type="text" name="participant[{{ $i + 15 }}]" class="form-control ms-2"
                                            value="" placeholder="Masukkan nama" id="">
                                    </div>
                                </div>
                            @endfor
                        </div>
                    </div>
                      <div class="mb-3">
                        <label for="description" class="form-label">Keterangan</label>
                        <textarea name="description" class="form-control editor" rows="3"
                            id="edit-description"></textarea>
                    </div>
                    <label for="description" class="form-label w-100">Dokumentasi</label>

                    <div class="mb-3">
                        <div class="images row g-4  mt-1">
                            @for ($i = 0; $i < 2; $i++)
                                <div class="col-md-6 col-12 d-flex align-items-center g-2">
                                    <span>{{ $i + 1 }}.</span>
                                    <div class="">
                                        <div class="d-flex justify-content-between">
                                            <label for="" id="label{{ $i }}"></label>
                                            <button class="btn btn-primary d-none ms-1 btn-sm viewImage" type="button" id="view{{ $i }}"><i
                                                    class="fa fa-eye"></i></button>
                                            <button class="btn btn-danger d-none ms-1 btn-sm delete-image-table" type="button" id="button{{ $i }}"><i
                                                    class="fa fa-close"></i></button>
                                        </div>
                                        <input type="file" name="images[{{ $i  }}]" class="form-control ms-2" value=""
                                            placeholder="Masukkan nama" id="" accept="image/*">

                                    </div>
                                </div>
                                <div class="col-md-6 col-12 d-flex align-items-center g-2">
                                    <span>{{ $i + 1 + 2 }}.</span>
                                    <div class="">
                                        <div class="d-flex justify-content-between">
                                            <label for="" id="label{{$i + 2}}"></label>
                                            <button class="btn btn-primary d-none ms-1 btn-sm viewImage" type="button" id="view{{ $i +2}}"><i
                                                    class="fa fa-eye"></i></button>
                                            <button class="btn btn-danger d-none ms-1 btn-sm delete-image-table" type="button" id="button{{ $i + 2 }}"><i
                                                    class="fa fa-close"></i></button>
                                        </div>
                                        <input type="file" name="images[{{ $i + 2 }}]" class="form-control ms-2" value=""
                                            placeholder="Masukkan nama" id="" accept="image/*">
                                    </div>
                                </div>

                            @endfor
                        </div>
                    </div>
                    {{-- <table class="table table-striped mt-3">
                        <thead>
                            <tr>
                                <th>Path</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table> --}}
                    <div class="old-images"></div>
                    <div class="deleted-images"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-primary">Simpan</button>
                </div>
            </div>
        </form>
    </div>
</div>


<div class="modal fade" id="viewImage" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Preview Image</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <img src="" alt="" class="w-100">
      </div>
    </div>
  </div>
</div>

@push("extraJS")
    <script>
        $(document).ready(function () {
            let editor;
            ClassicEditor
                .create(document.querySelector("#edit-description"))
                .then(ed => {
                    editor = ed
                })
                .catch(error => console.error('❌ CKEditor error:', error));

            $(document).on('click', '.edit', function () {
                clearFormErrors("form")
                let id = $(this).data('id');
                $('#edit-id').val(id);

                $('#modalEdit').modal('show');
                $(".deleted-images").empty();
                $.ajax({
                    url: `{{ route('stbm.show', ':id') }}`.replace(':id', id),
                    method: "get",
                    success: (res) => {
                        $("#edit-name").val(res.user.name)
                        $("#edit-topic").val(res.topic)
                        $("#edit-description").val(res.description)
                        editor.setData(res.description)

                        $("#edit-location_id").val(res.location_id).trigger("change")
                        $("#edit-date").val(res.date)
                        // const wrapper1 = $("#formEdit").closest("div").find(".images")
                        // wrapper1.empty();
                        $("#formEdit").find("[name*='participant']").each(function () {
                            $(this).val("");
                        });


                        // wrapper.empty();
                        res.participant.forEach((p, i) => {
                            $("#modalEdit").find(`[name='participant[${i}]']`).val(p.name)
                        });

                        const wrapper2 = $("#formEdit").find("table tbody")
                        $(wrapper2).empty()
                        for (let index = 0; index < 4; index++) {
                            $(`[name='images[${index}]']`).attr("disabled", false);
                            $(`#label${index}`).text("")
                            $(`#button${index}`).addClass("d-none")
                            $(`#view${index}`).addClass("d-none")
                        }
                        $(".old-images").empty()
                        res.images.forEach((i, index) => {
                            wrapper2.append(
                                `<tr><td>${i.image}</td><td><button type="button" class="btn btn-danger delete-image-table" data-id="${i.id}"><i class="fa fa-trash"></i></button></td></tr>`
                            )
                            $(`#label${index}`).text(i.image)
                            $(`#button${index}`).removeClass("d-none")
                            $(`#view${index}`).removeClass("d-none")
                            $(`#button${index}`).attr("data-id",i.id)
                            $(`#view${index}`).attr("data-image",i.image)

                            $(`#formEdit [name='images[${index}]']`).attr("disabled", true);
                            $(".old-images").append(`<input type='hidden' name='old_images[${i.id}]' value='${i.image}'>`)

                        })
                    }
                })
            });


            $(document).on("click",".viewImage",function () {
                $("#viewImage").modal("show")
                const src = $(this).attr("data-image")
                console.log($(this));
                $("#viewImage").find("img").attr("src",`storage/${src}`)
            })

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

                const form = $(this);
                const id = $(form).find("[name='edit-id']").val()
                const formData = new FormData(this);
                formData.append('_method', 'PUT');
                formData.append("description", editor.getData())


                $.ajax({
                    url: `{{ route('stbm.update', ':id') }}`.replace(':id', id),
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (response) {
                        $('#modalEdit').modal('hide');
                        form.trigger("reset");

                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil!',
                            text: response.message,
                            timer: 2000,
                            showConfirmButton: false
                        });
                        console.log(response);
                        $('.data-table').DataTable().ajax.reload();
                    },
                    error: function (xhr) {
                        let message = xhr.responseJSON?.message || 'Terjadi kesalahan';
                        // Swal.fire({
                        //     icon: 'error',
                        //     title: 'Gagal Menyimpan',
                        //     text: message
                        // });
                        console.log(xhr);
                        handleValidationErrors(xhr, form);

                    }
                });
            });

        })
    </script>
@endpush
