@extends('template.master')

@section('content')
    @if ($canCreate)
        <x-primary-button class="mb-4" id="btn-tambah-unit">Tambah Unit</x-primary-button>
    @endif
    <div class="card">
        <div class="card-body">
            <table class="table table-striped data-table">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Kode Unit</th>
                        <th>Jenis Unit</th>
                        <th>Pabrikan</th>
                        <th>Lokasi</th>
                        <th>Type Unit</th>
                        <th>Tahun Pembuatan</th>
                        <th>Serial Nomor Unit</th>
                        <th>Serial Nomor Chasis</th>
                        <th width="105px">Action</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>

    <div class="modal fade" id="modalTambahunit" tabindex="-1" aria-labelledby="modalTambahUnitLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form action="{{ route('units.store') }}" id="form-tambah-unit" method="POST">
                    @csrf
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalTambahUnitLabel">Tambah Unit</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="add-unit-type-id" class="form-label">Jenis Unit</label>
                            <select class="form-select @error('unit_type_id') is-invalid @enderror" id="add-unit-type-id"
                                name="unit_type_id" required>
                                <option value="">-- Pilih Jenis Unit --</option>
                                @foreach ($unittype as $data)
                                    <option value="{{ $data->id }}" {{ old('unit_type_id') == $data->id ? 'selected' : '' }}>
                                        {{ $data->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('unit_type_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="add-unit-code" class="form-label">Kode Unit</label>
                            <input type="text" class="form-control @error('unit_code') is-invalid @enderror"
                                id="add-unit-code" name="unit_code" value="{{ old('name') }}" required>
                            @error('unit_code')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="add-manufacture-id" class="form-label">Pabrikan</label>
                            <select class="form-select @error('manufacture_id') is-invalid @enderror"
                                id="add-manufacture-id" name="manufacture_id" required>
                                <option value="">-- Pilih Pabrikan --</option>
                                @foreach ($manufacture as $data)
                                    <option value="{{ $data->id }}" {{ old('manufacture_id') == $data->id ? 'selected' : '' }}>
                                        {{ $data->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('manufacture_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="add-location-id" class="form-label">Lokasi</label>
                            <select class="form-select @error('location_id') is-invalid @enderror" id="add-location-id"
                                name="location_id" required>
                                <option value="">-- Pilih Lokasi --</option>
                                @foreach ($locations as $data)
                                    <option value="{{ $data->id }}" {{ old('location_id') == $data->id ? 'selected' : '' }}>
                                        {{ $data->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('location_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="add-type-unit" class="form-label">Type Unit</label>
                            <input type="text" class="form-control @error('type_unit') is-invalid @enderror"
                                id="add-type-unit" name="type_unit" value="{{ old('type_unit') }}" required>
                            @error('type_unit')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="add-production-year" class="form-label">Tahun Produksi</label>
                            <input type="text" class="form-control @error('production_year') is-invalid @enderror"
                                id="add-production-year" name="production_year" value="{{ old('production_year') }}"
                                required>
                            @error('production_year')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="add-serial-number-unit" class="form-label">Serial Number Unit</label>
                            <input type="text" class="form-control @error('serial_number_unit') is-invalid @enderror"
                                id="add-serial-number-unit" name="serial_number_unit"
                                value="{{ old('serial_number_unit') }}" required>
                            @error('serial_number_unit')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="add-serial-number-chassis" class="form-label">Serial Number Chasis</label>
                            <input type="text" class="form-control @error('serial_number_chassis') is-invalid @enderror"
                                id="add-serial-number-chassis" name="serial_number_chassis"
                                value="{{ old('serial_number_chassis') }}" required>
                            @error('serial_number_chassis')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="add-hours-meter" class="form-label">Hours Metes</label>
                            <input type="text" class="form-control @error('hours_meter') is-invalid @enderror"
                                id="add-hours-meter" name="hours_meter" value="{{ old('hours_meter') }}" required>
                            @error('hours_meter')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Tutup</button>
                        <button type="submit" id="submit-tambah" class="btn btn-primary">Simpan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    {{-- edit --}}
    <div class="modal fade" id="modalEditunit" tabindex="-1" aria-labelledby="modalEditUnitLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="form-edit-unit" method="POST">
                    @csrf
                    @method('PUT')
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalEditUnitLabel">Ubah Unit</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="edit-unit-code" class="form-label">Kode Unit</label>
                            <input type="text" class="form-control @error('unit_code') is-invalid @enderror"
                                id="edit-unit-code" name="unit_code" value="{{ old('name') }}" required>
                            @error('unit_code')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="edit-unit-type-id" class="form-label">Jenis Unit</label>
                            <select class="form-select @error('unit_type_id') is-invalid @enderror" id="edit-unit-type-id"
                                name="unit_type_id" required>
                                <option value="">-- Pilih Jenis Unit --</option>
                                @foreach ($unittype as $data)
                                    <option value="{{ $data->id }}" {{ old('unit_type_id') == $data->id ? 'selected' : '' }}>
                                        {{ $data->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('unit_type_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="edit-manufacture-id" class="form-label">Pabrikan</label>
                            <select class="form-select @error('manufacture_id') is-invalid @enderror"
                                id="edit-manufacture-id" name="manufacture_id" required>
                                <option value="">-- Pilih Pabrikan --</option>
                                @foreach ($manufacture as $data)
                                    <option value="{{ $data->id }}" {{ old('manufacture_id') == $data->id ? 'selected' : '' }}>
                                        {{ $data->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('manufacture_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="edit-location-id" class="form-label">Lokasi</label>
                            <select class="form-select @error('location_id') is-invalid @enderror" id="edit-location-id"
                                name="location_id" required>
                                <option value="">-- Pilih Lokasi --</option>
                                @foreach ($locations as $data)
                                    <option value="{{ $data->id }}" {{ old('location_id') == $data->id ? 'selected' : '' }}>
                                        {{ $data->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('location_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="edit-type-unit" class="form-label">Type Unit</label>
                            <input type="text" class="form-control @error('type_unit') is-invalid @enderror"
                                id="edit-type-unit" name="type_unit" value="{{ old('type_unit') }}" required>
                            @error('type_unit')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="edit-production-year" class="form-label">Tahun Produksi</label>
                            <input type="text" class="form-control @error('production_year') is-invalid @enderror"
                                id="edit-production-year" name="production_year" value="{{ old('production_year') }}"
                                required>
                            @error('production_year')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="edit-serial-number-unit" class="form-label">Serial Number Unit</label>
                            <input type="text" class="form-control @error('serial_number_unit') is-invalid @enderror"
                                id="edit-serial-number-unit" name="serial_number_unit"
                                value="{{ old('serial_number_unit') }}" required>
                            @error('serial_number_unit')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="edit-serial-number-chassis" class="form-label">Serial Number Chasis</label>
                            <input type="text" class="form-control @error('serial_number_chassis') is-invalid @enderror"
                                id="edit-serial-number-chassis" name="serial_number_chassis"
                                value="{{ old('serial_number_chassis') }}" required>
                            @error('serial_number_chassis')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="mb-3">
                            <label for="edit-hours-meter" class="form-label">Hours Metes</label>
                            <input type="text" class="form-control @error('hours_meter') is-invalid @enderror"
                                id="edit-hours-meter" name="hours_meter" value="{{ old('hours_meter') }}" required>
                            @error('hours_meter')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Tutup</button>
                        <button type="submit" id="submit-edit" class="btn btn-primary">Simpan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection



@push('extraJS')
    <script type="text/javascript">
        @if (session('success'))
            Swal.fire({
                icon: 'success',
                title: 'Berhasil!',
                text: '{{ session('success') }}',
                showConfirmButton: false,
                timer: 2000
            });
        @endif

        @if (session('error'))
            Swal.fire({
                icon: 'error',
                title: 'Gagal!',
                text: '{{ session('error') }}'
            });
        @endif

            @if ($errors->any())
                const modal = new bootstrap.Modal(document.getElementById('modalTambahUnit'));
                modal.show();
            @endif

        $(function () {
            var table = $('.data-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "{{ route('units.index') }}",
                    error: (er) => {
                        console.log(er);
                    }
                },
                columnDefs: [{
                    width: "50px",
                    targets: 0
                }],
                columns: [{
                    data: 'DT_RowIndex',
                    name: 'DT_RowIndex',
                    className: 'text-center',
                    orderable: false,
                    searchable: false
                },
                { data: 'unit_code', name: 'unit_code' },
                { data: 'unit_type', name: 'unit_type' },
                { data: 'manufacture', name: 'manufacture' },
                { data: 'location', name: 'location' },
                { data: 'unit_type', name: 'unit_type' },
                { data: 'production_year', name: 'production_year' },
                { data: 'serial_number_unit', name: 'serial_number_unit' },
                { data: 'serial_number_chassis', name: 'serial_number_chassis' },
                { data: 'action', name: 'action', orderable: false, searchable: false },
                ]
            });

        });

        $(document).ready(function () {
            $('#btn-tambah-unit').on('click', function () {
                $('#modalTambahunit').modal('show');
                clearFormErrors('#form-tambah-unit');
            });
        });

        $('#form-tambah-unit').on("submit", function (e) {
            e.preventDefault();

            let formData = $(this).serialize();

            $.ajax({
                url: "{{ route('units.store') }}",
                type: "POST",
                data: formData,
                success: function (res) {
                    $('#modalTambahunit').modal('hide');
                    $('.data-table').DataTable().ajax.reload();
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil!',
                        text: 'Unit berhasil ditambahkan',
                        timer: 2000,
                        showConfirmButton: false
                    });

                    $('#add-unit-code').val('');
                    $('#add-type-unit').val('');
                    $('#add-location-id').val('');
                    $('#add-production-year').val('');
                    $('#add-serial-number-unit').val('');
                    $('#add-serial-number-chassis').val('');
                    $('#add-unit-type-id').val('');
                    $('#add-manufacture-id').val('');
                    $('#add-hours-meter').val('');
                },
                error: function (xhr) {
                    clearFormErrors('#form-tambah-unit');
                    handleValidationErrors(xhr, $('#form-tambah-unit'));
                    console.log(xhr);
                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal!',
                        text: 'Harap periksa kembali input Anda.'
                    });
                }
            });
        });

        let routeUpdateLocation = "{{ route('units.update', ':id') }}";
        let routeDeleteLocation = "{{ route('units.destroy', ':id') }}";

        $(document).on('click', '.edit', function () {
            let id = $(this).data('id');
            let unit_code = $(this).data('unit_code');
            let unit_type_id = $(this).data('unit_type_id');
            let manufacture_id = $(this).data('manufacture_id');
            let location_id = $(this).data('location_id');
            let type_unit = $(this).data('type_unit');
            let production_year = $(this).data('production_year');
            let serial_number_unit = $(this).data('serial_number_unit');
            let serial_number_chassis = $(this).data('serial_number_chassis');
            let hours_meter = $(this).data('hours_meter');

            clearFormErrors('#form-edit-unit');

            $('#edit-unit-code').val(unit_code);
            $('#edit-unit-type-id').val(unit_type_id);
            $('#edit-manufacture-id').val(manufacture_id);
            $('#edit-location-id').val(location_id);
            $('#edit-type-unit').val(type_unit);
            $('#edit-production-year').val(production_year);
            $('#edit-serial-number-unit').val(serial_number_unit);
            $('#edit-serial-number-chassis').val(serial_number_chassis);
            $('#edit-hours-meter').val(hours_meter);

            let updateUrl = routeUpdateLocation.replace(':id', id);

            $('#form-edit-unit').attr('action', updateUrl);

            const modal = new bootstrap.Modal(document.getElementById('modalEditunit'));
            modal.show();
        });

        $('#form-edit-unit').on("submit", function (e) {
            e.preventDefault();

            let formData = $(this).serialize();
            let updateUrl = $(this).attr('action');
            console.log(updateUrl);

            $.ajax({
                url: updateUrl,
                type: 'POST',
                data: formData,
                success: function (res) {
                    $('#modalEditunit').modal('hide');
                    $('.data-table').DataTable().ajax.reload();
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil!',
                        text: 'Unit berhasil diperbarui',
                        timer: 2000,
                        showConfirmButton: false
                    });
                },
                error: function (xhr) {
                    clearFormErrors('#form-edit-unit');
                    handleValidationErrors(xhr, $('#form-edit-unit'));

                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal!',
                        text: 'Harap periksa kembali input Anda.'
                    });
                }
            });
        });


        $(document).on('click', '.delete', function () {
            let id = $(this).data('id');

            Swal.fire({
                title: 'Yakin ingin menghapus Unit ini?',
                text: "Data tidak dapat dikembalikan setelah dihapus.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#e3342f',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Ya, hapus!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    const deleteUrl = routeDeleteLocation.replace(':id', id);

                    $.ajax({
                        url: deleteUrl,
                        type: 'POST',
                        data: {
                            _method: 'DELETE',
                            _token: '{{ csrf_token() }}'
                        },
                        success: function () {
                            $('.data-table').DataTable().ajax.reload();
                            Swal.fire({
                                icon: 'success',
                                title: 'Berhasil!',
                                text: 'Unit berhasil dihapus',
                                timer: 2000,
                                showConfirmButton: false
                            });
                        },
                        error: function (xhr) {
                            Swal.fire({
                                icon: 'error',
                                title: 'Gagal!',
                                text: xhr.responseJSON?.message ??
                                    'Data tidak bisa dihapus karena sedang digunakan.'
                            });
                        }
                    });
                }
            });
        });

        function clearFormErrors(formSelector) {
            $(formSelector).find('.is-invalid').removeClass('is-invalid');
            $(formSelector).find('.invalid-feedback').remove();
        }


        function handleValidationErrors(xhr, form) {
            if (xhr.status === 422) {
                let errors = xhr.responseJSON.errors;
                console.log(errors);
                for (let field in errors) {
                    let input = form.find(`[name="${field}"]`);
                    if (input.length === 0 && field.includes('.')) {
                        // For array fields like roles[0]
                        let nameAttr = field.replace(/\.\d+/, '[]');
                        input = form.find(`[name="${nameAttr}"]`);
                    }
                    input.addClass('is-invalid');
                    input.after(`<div class="invalid-feedback d-block">${errors[field][0]}</div>`);
                }
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal!',
                    text: 'Terjadi kesalahan pada server.'
                });
            }
        }
    </script>
@endpush
