@extends('layouts.main')

@php
    if ($header == 'sla') {
        $header = 'Freze SLA';
    }
@endphp

@section('breadcrumbs')
    {{ Breadcrumbs::render(request()->route()->getName(), $permohonan->id, $header) }}
@endsection

@section('content')
    <div class="w-full grid gap-5 lg:gap-7.5 mx-auto">

        @php
            $dataHeader = strtolower($header ?? '');
        @endphp

        @include('lpj::component.detail-jaminan', ['backLink' => 'otorisator.' . $dataHeader . '.index'])

        @foreach ($permohonan->documents as $dokumen)
            <div class="card border border-agi-100 pb-2.5">
                <div class="card-header bg-agi-50" id="basic_settings">
                    <h3 class="card-title">
                        Team
                    </h3>
                </div>

                <div class="card-body grid gap-5">
                    <div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                        @php
                            $surveyor = $permohonan->penilaian->userPenilai->where('role', 'surveyor')->first();
                            $penilai = $permohonan->penilaian->userPenilai->where('role', 'penilai')->first();

                        @endphp
                        <label class="form-label max-w-56">
                            Surveyor
                        </label>
                        <div class="flex flex-wrap items-baseline w-full">

                            <p class="flex w-full text-gray-600 font-medium text-sm">
                                {{ $surveyor->userPenilaiTeam->name }}
                            </p>

                            <p class="flex w-full text-gray-600 font-medium text-sm">
                                {{ checkRegionUserName($surveyor->userPenilaiTeam->id) }}
                            </p>
                        </div>
                        <label class="form-label max-w-56">
                            Penilai
                        </label>
                        <div class="flex flex-wrap items-baseline w-full">

                            <p class="flex w-full text-gray-600 font-medium text-sm">
                                {{ $penilai->userPenilaiTeam->name }}
                            </p>

                            <p class="flex w-full text-gray-600 font-medium text-sm">
                                {{ checkRegionUserName($penilai->userPenilaiTeam->id) }}
                            </p>
                        </div>
                    </div>
                </div>
                @php
                    $inspeksiId = null;
                    foreach ($dokumen->inspeksi as $item) {
                        $inspeksiId = $item->id;
                    }
                @endphp
            </div>
        @endforeach

        <div class="card border border-agi-100 pb-2.5">
            <div class="card-header bg-agi-50" id="basic_settings">
                <h3 class="card-title">
                    Alasan Freze SLA
                </h3>
            </div>

            <div class="card-body grid gap-5">
                {{ $authorization->keterangan ?? '' }}
                <table class="table table-border">
                    <tbody>
                    <tr>
                        <td>Pemohon</td>
                        <td>{{ $authorization->user->name }}</td>
                    </tr>
                    <tr>
                        <td>Alasan</td>
                        <td>{{ $authorization->keterangan }}</td>
                    </tr>
                    <tr>
                        <td>Tanggal Permohonan</td>
                        <td>{{ formatTanggalIndonesia($authorization->created_at, 1) }}</td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>

        @php
            if ($header == 'SLA') {
                $header = 'Freze SLA';
            }
        @endphp

        @if ($authorization->approve_so)
            <div class="card border border-agi-100 pb-2.5">
                <div class="card-header bg-agi-50" id="basic_settings">
                    <h3 class="card-title">
                        Approval
                    </h3>
                </div>

                <div class="card-body">
                    <table class="table table-border">
                        <tbody>
                        <tr>
                            <td>Diperiksa Oleh</td>
                            <td>{{ getUser($authorization->approve_so)->name ?? 'N/A' }}</td>
                            <td>{{ $authorization->approve_so_at ? formatTanggalIndonesia($authorization->approve_so_at, 1) : 'N/A' }}
                            </td>
                        </tr>
                        @if ($authorization->approve_eo != null)
                            <tr>
                                <td>Disetujui Oleh (EO)</td>
                                <td>{{ getUser($authorization->approve_eo)->name ?? 'N/A' }}</td>
                                <td>{{ $authorization->approve_eo_at ? formatTanggalIndonesia($authorization->approve_eo_at, 1) : 'N/A' }}
                                </td>
                            </tr>
                        @endif
                        @if (in_array($authorization->nilai_eafond_id, [1, 4]) && $authorization->approve_dd != null)
                            <tr>
                                <td>Disetujui Oleh (DD)</td>
                                <td>{{ getUser($authorization->approve_dd)->name ?? 'N/A' }}</td>
                                <td>{{ $authorization->approve_dd_at ? formatTanggalIndonesia($authorization->approve_dd_at, 1) : 'N/A' }}
                                </td>
                            </tr>
                        @endif
                        </tbody>
                    </table>
                </div>
            </div>
        @endif
        <div>
            <div>
                <div class="flex gap-2.5">
                    @php
                        $inspeksiId = null;
                        $documentId = null;
                        $jenisJaminanId = null;
                        foreach ($permohonan->documents as $item) {
                            foreach ($item->inspeksi as $key => $value) {
                                $inspeksiId = $item->id;
                            }
                            $documentId = $item->id;
                            $jenisJaminanId = $item->jenis_jaminan_id;
                        }
                    @endphp

                    @if ($dataHeader == 'pelaporan')
                        <a class="btn btn-success"
                           href="{{ route('otorisator.view-laporan') }}?permohonanId={{ $permohonan->id }}&documentId={{ $documentId }}&inspeksiId={{ $inspeksiId }}&jaminanId={{ $jenisJaminanId }}&statusLpj={{ true }}&header={{ $header }}">
                            Lihat Laporan
                        </a>
                    @endif

                    @if (Auth::user()->hasAnyRole(['administrator', 'senior-officer']) && $authorization->approve_so == null)
                        <button onclick="otorisatorData({{ $authorization->id }}, 'SO')" type="button"
                                class="btn btn-primary">
                            <i class="ki-filled ki-double-check"></i>
                            Otorisasi {{ $header ?? '' }}
                        </button>
                    @endif

                    @if (Auth::user()->hasAnyRole(['administrator', 'EO Appraisal']) &&
                            $authorization->approve_so &&
                            $authorization->approve_eo == null)
                        <button onclick="otorisatorData({{ $authorization->id }}, 'EO')" type="button"
                                class="btn btn-primary">
                            <i class="ki-filled ki-double-check"></i>
                            Otorisasi {{ $header ?? '' }}
                        </button>
                    @endif

                    @if (Auth::user()->hasAnyRole(['administrator', 'DD Appraisal']) &&
                            $authorization->approve_eo &&
                            $authorization->approve_dd == null &&
                            in_array($permohonan->nilai_plafond_id, [1, 4]))
                        <button onclick="otorisatorData({{ $authorization->id }}, 'DD')" type="button"
                                class="btn btn-primary">
                            <i class="ki-filled ki-double-check"></i>
                            Otorisasi {{ $header ?? '' }}
                        </button>
                    @endif

                    @if (
                            (Auth::user()->hasAnyRole(['administrator', 'senior-officer']) &&
                                $authorization->approve_so != null &&
                                $authorization->approve_eo != null) ||
                                $authorization->approve_dd != null
                        )
                        @php
                            $memoDeviasiExists = false;
                            if ($authorization->permohonan && $authorization->permohonan->lampiranDokumen) {
                                $memoDeviasiExists = $authorization->permohonan->lampiranDokumen()
                                    ->whereHas('jenisLampiran', function($query) {
                                        $query->where('nama', 'memo-deviasi');
                                    })
                                    ->exists();
                            }
                        @endphp

                        @if ($memoDeviasiExists)
                            <button onclick="otorisatorData({{ $authorization->id }}, 'UNFREZE')" type="button"
                                    class="btn btn-primary">
                                <i class="ki-filled ki-double-check"></i>
                                Otorisasi Un{{ $header ?? '' }}
                            </button>
                        @else
                            <span class="badge badge-warning">
                                Memo Deviasi Belum Ada
                            </span>
                        @endif
                    @endif
                </div>
            </div>
        </div>
        @endsection

        @push('scripts')
            <script>
                const handleRejection = (dataId, dataHeader = '') => {
                    Swal.fire({
                        title: 'Masukkan alasan penolakan:',
                        input: 'textarea',
                        inputPlaceholder: 'Tuliskan alasan...',
                        showCancelButton: true,
                        confirmButtonColor: '#f39c12',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'Kirim',
                        cancelButtonText: 'Batal',
                        preConfirm: (alasan) => {
                            if (!alasan) {
                                Swal.showValidationMessage('Alasan harus diisi!');
                                return false;
                            }
                            return alasan;
                        }
                    }).then((rejectResult) => {
                        if (rejectResult.isConfirmed) {
                            handleAjaxRequest(
                                `/otorisator/revisi-laporan/${dataId}`, {
                                    keterangan: rejectResult.value,
                                    dataHeader: dataHeader
                                },
                                'Data berhasil ditolak.',
                                'Terjadi kesalahan saat melakukan penolakan.'
                            );
                        }
                    });
                };

                const showSwalConfirmation = (
                    title, text, html, confirmText, denyText, cancelText, preConfirm, icon = 'question'
                ) => {
                    return Swal.fire({
                        title: title,
                        text: text,
                        html: html,
                        icon: icon,
                        focusConfirm: false,
                        preConfirm: preConfirm,
                        showCancelButton: true,
                        showDenyButton: !!denyText,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
                        denyButtonColor: '#f39c12',
                        confirmButtonText: confirmText,
                        denyButtonText: denyText,
                        cancelButtonText: cancelText,
                    });
                };

                const handleAjaxRequest = (url, data, successMessage, errorMessage) => {
                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        },
                    });
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        success: () => {
                            Swal.fire('Berhasil!', successMessage, 'success').then(() => {
                                const redirectUrl = `/otorisator/sla`;
                                window.location.href = redirectUrl;
                            });
                        },
                        error: (error) => {
                            console.error('Error:', error);
                            Swal.fire('Gagal!', errorMessage, 'error');
                        }
                    });
                };

                function otorisatorData(dataId, role = '') {
                    let dataHeader = @json($header);

                    // Update dataHeader if condition matches
                    if (dataHeader === 'Freze SLA' && (role === 'UNFREZE' || role === 'FREZE')) {
                        dataHeader = 'Unfreeze SLA';
                    }

                    const isPaparanSO = dataHeader === 'Unfreeze SLA' && role === 'UNFREZE';
                    const hideDenyButton = (dataHeader === 'Unfreeze SLA' && (role === 'UNFREZE' || role === 'FREZE'));

                    const swalHtml = isPaparanSO ? `
        <div class="text-left space-y-4">
            <p class="text-gray-700 text-center">Untuk melakukan otorisasi ${dataHeader}!</p>
            <div>
                <textarea id="swal-keterangan" class="textarea" placeholder="Masukkan Keterangan"></textarea>
            </div>
        </div>` : '';

                    showSwalConfirmation(
                        'Apakah Anda yakin?',
                        `Untuk melakukan otorisasi ${dataHeader}!`,
                        swalHtml,
                        'Ya, Lanjutkan!',
                        hideDenyButton ? null : 'Tolak',
                        'Batal',
                        () => {
                            if (isPaparanSO) {
                                const message = document.getElementById('swal-keterangan')?.value;

                                if (!message) {
                                    Swal.showValidationMessage('Keterangan harus diisi!');
                                    return false;
                                }

                                return {
                                    message,
                                };
                            } else {
                                return {
                                    message: 'Ya, lanjutkan.'
                                };
                            }
                        },
                        'question'
                    ).then((result) => {
                        if (result.isConfirmed) {
                            const requestData = isPaparanSO ? {
                                keterangan: result.value.message,
                            } : {
                                keterangan: result.value.message
                            };

                            handleAjaxRequest(
                                `/otorisator/otorisator/${dataId}/${dataHeader}`,
                                requestData,
                                'Data berhasil diotorisasi.',
                                'Terjadi kesalahan saat melakukan otorisasi.'
                            );
                        } else if (!hideDenyButton && result.isDenied) {
                            handleRejection(dataId, dataHeader);
                        }
                    });
                }
            </script>
    @endpush
