@extends('layouts.main')

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

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

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

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

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

                <div class="grid gap-5 card-body">
                    <div class="flex flex-wrap gap-2.5 items-baseline lg:flex-nowrap">
                        @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-sm font-medium text-gray-600">
                                {{ $surveyor->userPenilaiTeam->name }}
                            </p>

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

                            <p class="flex w-full text-sm font-medium text-gray-600">
                                {{ checkRegionUserName($penilai->userPenilaiTeam->id) }}
                            </p>
                        </div>
                    </div>


                </div>


            </div>
        @endforeach


        @if ($permohonan->approval_so)
            <div class="pb-2.5 border card border-agi-100">
                <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($permohonan->approval_so)->name ?? 'N/A' }}</td>
                                <td>{{ $permohonan->approval_so_at ? formatTanggalIndonesia($permohonan->approval_so_at, 1) : 'N/A' }}
                                </td>
                            </tr>
                            @if ($permohonan->approval_eo != null)
                                <tr>
                                    <td>Disetujui Oleh (EO)</td>
                                    <td>{{ getUser($permohonan->approval_eo)->name ?? 'N/A' }}</td>
                                    <td>{{ $permohonan->approval_eo_at ? formatTanggalIndonesia($permohonan->approval_eo_at, 1) : 'N/A' }}
                                    </td>
                                </tr>
                            @endif
                            @if (in_array($permohonan->nilai_plafond_id, [1, 2, 4]) && $permohonan->approval_dd != null)
                                <tr>
                                    <td>Disetujui Oleh (DD)</td>
                                    <td>{{ getUser($permohonan->approval_dd)->name ?? 'N/A' }}</td>
                                    <td>{{ $permohonan->approval_dd_at ? formatTanggalIndonesia($permohonan->approval_dd_at, 1) : 'N/A' }}
                                    </td>
                                </tr>
                            @endif
                        </tbody>
                    </table>
                </div>
            </div>
        @endif


        @if (isset($permohonan->authorization->approve_so) && $dataHeader == 'paparan' )
        <div class="pb-2.5 border card border-agi-100">
            <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($permohonan->authorization->approve_so)->name ?? 'N/A' }}</td>
                            <td>{{ $permohonan->authorization->approve_so_at ? formatTanggalIndonesia($permohonan->authorization->approve_so_at, 1) : 'N/A' }}
                            </td>
                        </tr>
                        @if ($permohonan->authorization->approve_eo != null)
                            <tr>
                                <td>Disetujui Oleh (EO)</td>
                                <td>{{ getUser($permohonan->authorization->approve_eo)->name ?? 'N/A' }}</td>
                                <td>{{ $permohonan->authorization->approve_eo_at ? formatTanggalIndonesia($permohonan->authorization->approve_eo_at, 1) : 'N/A' }}
                                </td>
                            </tr>
                        @endif
                        @if (in_array($permohonan->nilai_plafond_id, [1, 2, 4]) && $permohonan->approve_dd != null)
                            <tr>
                                <td>Disetujui Oleh (DD)</td>
                                <td>{{ getUser($permohonan->authorization->approve_dd)->name ?? 'N/A' }}</td>
                                <td>{{ $permohonan->authorization->approve_dd_at ? formatTanggalIndonesia($permohonan->authorization->approve_dd_at, 1) : 'N/A' }}
                                </td>
                            </tr>
                        @endif
                    </tbody>
                </table>
            </div>
        </div>
    @endif

        <div>
            <div>
                <div class="flex gap-2.5">
                    @php

                        $documentId = null;
                        $jenisJaminanId = null;
                        foreach ($permohonan->documents as $item) {

                            $documentId = $item->id;
                            $jenisJaminanId = $item->jenis_jaminan_id;
                        }
                    @endphp

                    @if ($dataHeader == 'pelaporan')
                        @php
                            $lpj_ = optional(json_decode($permohonan->penilai->lpj));
                            $npw = $lpj_->total_nilai_pasar_wajar ?? 0;
                            $npw = str_replace('.', '', $npw);
                        @endphp
                        <a class="btn btn-success"
                            href="{{ route('otorisator.view-laporan') }}?permohonanId={{ $permohonan->id }}&documentId={{ $documentId }}&jaminanId={{ $jenisJaminanId }}&statusLpj={{ true }}&header={{ $header ?? '' }}">
                            Lihat Laporan
                        </a>
                        @if (Auth::user()->hasAnyRole(['administrator', 'senior-officer']) && $permohonan->approval_so == 0)
                            <button onclick="otorisatorData({{ $permohonan->id }})" type="button" class="btn btn-primary">
                                <i class="ki-filled ki-double-check"></i>
                                Otorisator {{ $header ?? '' }}
                            </button>
                        @endif

                        @if (Auth::user()->hasAnyRole(['administrator', 'EO Appraisal']) &&
                                $permohonan->approval_so &&
                                $permohonan->approval_eo == 0 &&
                                $npw > 1000000000)
                            <button onclick="otorisatorData({{ $permohonan->id }})" type="button" class="btn btn-primary">
                                <i class="ki-filled ki-double-check"></i>
                                Otorisator {{ $header ?? '' }}
                            </button>
                        @endif

                        @if (Auth::user()->hasAnyRole(['administrator', 'DD Appraisal']) &&
                                $permohonan->approval_eo &&
                                $permohonan->approval_dd == 0 &&
                                $npw > 5000000000)
                            <button onclick="otorisatorData({{ $permohonan->id }})" type="button" class="btn btn-primary">
                                <i class="ki-filled ki-double-check"></i>
                                Otorisator {{ $header ?? '' }}
                            </button>
                        @endif
                    @elseif($dataHeader == 'paparan')
                        @if ($permohonan->penilai->file_paparan)
                            <span class="btn btn-success btn-outline"
                                onclick="viewPDF('{{ Storage::url($permohonan->penilai->file_paparan) }}')"><i
                                    class="mr-2 ki-filled ki-eye"></i>Lihat Data Paparan</span>
                        @endif

                        @if ($permohonan->penilai->kertas_kerja)
                            <span class="btn btn-warning btn-outline"
                                onclick="viewPDF('{{ Storage::url($permohonan->penilai->kertas_kerja) }}')"><i
                                    class="mr-2 ki-filled ki-eye"></i>Lihat Kertas Kerja</span>
                        @endif


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


                        @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>
                                Otorisator {{ $header ?? '' }}
                            </button>
                        @endif

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

                        @if (Auth::user()->hasAnyRole(['administrator', 'DD Appraisal']) && $authorization->approve_eo &&  $authorization->approve_dd == null && in_array($permohonan->nilai_plafond_id, [2, 4]) &&$permohonan->status === 'proses-paparan')
                            <button onclick="otorisatorData({{ $authorization->id }},'DD')" type="button"
                                class="btn btn-primary">
                                <i class="ki-filled ki-double-check"></i>
                                Otorisator {{ $header ?? '' }}
                            </button>
                        @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 dataHeader = @json($header);
                            const redirectUrl = `/otorisator/${dataHeader.toLowerCase()}`;
                            window.location.href = redirectUrl;
                        });
                    },
                    error: (error) => {
                        console.error('Error:', error);
                        Swal.fire('Gagal!', errorMessage, 'error');
                    }
                });
            };

            function otorisatorData(dataId, role = '') {
                const dataHeader = @json($header);
                const isPaparanSO = dataHeader === 'Paparan' && role === 'SO';

                const swalHtml = isPaparanSO ? `
        <div class="space-y-4 text-left">
            <p class="text-center text-gray-700">Untuk melakukan otorisasi ${dataHeader}!</p>
            <div>
                <label for="swal-keterangan" class="block mb-1 text-sm font-medium text-gray-700">Keterangan</label>
                <input id="swal-keterangan" class="input" placeholder="Masukkan Keterangan">
            </div>
            <div>
                <label for="swal-tanggal-paparan" class="block mb-1 text-sm font-medium text-gray-700">Tanggal Paparan</label>
                <input id="swal-tanggal-paparan" class="input" type="date" placeholder="Tanggal paparan">
            </div>
        </div>` : '';

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

                            if (!message || !tanggalPaparan) {
                                Swal.showValidationMessage('Keterangan dan Tanggal Paparan harus diisi!');
                                return false;
                            }

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

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