<style>
    .badge {
        line-height: 1.95;
        font-size: small;
    }
</style>
<x-admin.layout>
    <x-slot name="title">Approve List</x-slot>
    <x-slot name="heading">Approve List</x-slot>

    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header">
                </div>
                <div class="card-body">
                    <div class="table-responsive">

                        <table id="buttons-datatables" class="table table-bordered nowrap align-middle" style="width:100%">
                            <thead>
                                <tr>
                                    <th>Sr.No</th>
                                    <th>Application.No</th>
                                    <th>Applicant Name</th>
                                    <th>Service</th>
                                    <th>Date</th>
                                    {{-- @if (Auth::check() && Auth::user()->hasRole('CityEngineer')) --}}
                                    {{-- <th>View</th> --}}
                                    {{-- @endif --}}
                                    {{-- <th>Status</th> --}}
                                    <th>Demand Note</th>
                                    <th>Certificate</th>
                                    <th>Receipt</th>
                                    {{-- @if (Auth::check() && Auth::user()->hasRole('Clerk')) --}}
                                    <th>upload certificate</th>
                                    {{-- @endif --}}
                                    {{-- @if (Auth::check() && Auth::user()->hasRole('Clerk'))
                                    <th>view</th>
                                     @endif --}}
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($approvedItems as $pro)
                                    <tr data-id="{{ $pro->status()->where('service_id', $pro->service_id)->first()?->id }}">
                                        <td>{{ $loop->iteration }}</td>
                                        <td>{{ $pro->application_no }}</td>
                                        <td>{{ $user->where('id', $pro->user_id)->first()?->name }}</td>
                                        <td title="{{ $serviceName->where('service_id', $pro->service_id)->first()?->service_name }}">
                                            {{ \Illuminate\Support\Str::limit($serviceName->where('service_id', $pro->service_id)->first()?->service_name, 30) }}
                                        </td>
                                        <td>{{ isset($pro->created_at) ? date('d-m-Y h:i A', strtotime($pro->created_at)) : 'N/A' }}
                                        </td>

                                        {{-- <td>
                                            @if (Auth::check() && Auth::user()->hasRole('JuniorEngineer'))
                                                <span class="badge text-bg-success">Generated Demand Note & Approved By
                                                    JuniorEngineer In Process at DE</span>
                                            @else
                                                @if (Auth::check() && Auth::user()->hasRole('DeputyEngineer'))
                                                    <span class="badge text-bg-success">Approved By DeputyEngineer In
                                                        Process at EE</span>
                                                @elseif (Auth::check() && Auth::user()->hasRole('ExecutiveEngineer'))
                                                    <span class="badge text-bg-success">Approved By
                                                        ExecutiveEngineer</span>
                                                @elseif (Auth::check() && Auth::user()->hasRole('Clerk'))
                                                    <span class="badge text-bg-success">Approved By Clerk In Process at
                                                        JE</span>
                                                @endif
                                            @endif
                                        </td> --}}
                                        <td>
                                            @if ((Auth::check() && Auth::user()->hasRole('CityEngineer')) || Auth::user()->hasRole('ExecutiveEngineer') || Auth::user()->hasRole('Clerk'))
                                                @php
                                                    $serviceId = $pro->service_id;
                                                    $statusExists = $pro->status()->where('service_id', $serviceId)->first()?->id;
                                                    $allowedServices = [187, 2032, 2005];
                                                @endphp

                                                @if ($statusExists && in_array($serviceId, $allowedServices))
                                                    <a href="{{ array_key_exists($serviceId, $demandnote) && $demandnote[$serviceId] != '' ? route($demandnote[$serviceId], encrypt($pro->id)) : '#' }}" class="btn btn-primary btn-sm">
                                                        Demand Note
                                                    </a>
                                                @else
                                                    -
                                                @endif
                                            @endif
                                        </td>

                                        <!--kishori comment purana code-->
                                        {{-- <td>
                                            @php
                                                $status = $statusdata->where('service_id', $pro->service_id)->where('table_id', $pro->id)->value('status');

                                                $statusdoc = $statusdata->where('service_id', $pro->service_id)->where('table_id', $pro->id)->value('document_upload');

                                                $payStatus = $paydata->where('service_id', $pro->service_id)->where('table_id', $pro->id)->value('status');
                                            @endphp

                                            @if ($payStatus == 1)
                                                @if ($pro->service_id == 8925  || $pro->service_id == 6042 || $pro->service_id == 8042 || $pro->service_id == 9041 || $pro->service_id == 7042 || $pro->service_id == 8920 || $pro->service_id == 8990)
                                                    @if ($statusdoc)
                                                        <a href="{{ asset('storage/' . $statusdoc) }}" target="_blank" class="btn btn-primary btn-sm p-1">View
                                                            Document</a>
                                                    @endif
                                                @elseif(array_key_exists($pro->service_id, $certificateRoute) && $certificateRoute[$pro->service_id] != '')
                                                    <a href="{{ route($certificateRoute[$pro->service_id], encrypt($pro->id)) }}" class="btn btn-primary btn-sm p-1" >
                                                        Download Certificate
                                                    </a>
                                                @endif
                                            @else
                                                
                                                <a href="#" class="btn btn-primary btn-sm p-1" style="display:none;">
                                                    Download Certificate
                                                </a>
                                            @endif
                                        </td> --}}
                                        <!--kishori end purana code -->

                                        <td>
                                            @php
                                                $status = $statusdata->where('service_id', $pro->service_id)
                                                                    ->where('table_id', $pro->id)
                                                                    ->value('status');

                                                $statusdoc = $statusdata->where('service_id', $pro->service_id)
                                                                        ->where('table_id', $pro->id)
                                                                        ->value('document_upload');

                                                $payStatus = $paydata->where('service_id', $pro->service_id)
                                                                    ->where('table_id', $pro->id)
                                                                    ->value('status');

                                                // 🟢 service_id = 187 केस में रोड कटिंग से value लेना
                                                $isStartDateEndDate = null;
                                                if ($pro->service_id == 187) {
                                                    $isStartDateEndDate = $roadCuttingData[$pro->id]->is_generated ?? 0;
                                                }

                                                $isStartEnddate = null;
                                                if($pro->service_id == 2032){
                                                     $isStartEnddate  = $GrantingData[$pro->id]->is_generated ?? 0;
                                                }
                                                
                                            @endphp

                                            @if ($isStartDateEndDate == 1 || $isStartEnddate==1 )

                                                {{-- 🟢 Special case only for service_id = 187 --}}
                                                @if ($pro->service_id == 187 || $pro->service_id == 2032)
                                                       @if ($isStartDateEndDate == 1 || $isStartEnddate == 1)
                                                            <a href="{{ route($certificateRoute[$pro->service_id], encrypt($pro->id)) }}" 
                                                            class="btn btn-primary btn-sm p-1">
                                                            Download Certificate
                                                            </a>
                                                        @endif

                                                
                                                
                                                        @elseif ($pro->service_id == 8925 || $pro->service_id == 6042 || 
                                                                $pro->service_id == 8042 || $pro->service_id == 9041 || 
                                                                $pro->service_id == 7042 || $pro->service_id == 8920 || 
                                                                $pro->service_id == 8990)

                                                            @if ($statusdoc)
                                                                <a href="{{ asset('storage/' . $statusdoc) }}" target="_blank" 
                                                                class="btn btn-primary btn-sm p-1">View Document</a>
                                                            @endif

                                                        @elseif(array_key_exists($pro->service_id, $certificateRoute) && 
                                                                $certificateRoute[$pro->service_id] != '')

                                                            <a href="{{ route($certificateRoute[$pro->service_id], encrypt($pro->id)) }}" 
                                                            class="btn btn-primary btn-sm p-1">
                                                                Download Certificate
                                                            </a>

                                                        @endif

                                            @else
                                                <a href="#" class="btn btn-primary btn-sm p-1" style="display:none;">
                                                    Download Certificate
                                                </a>
                                            @endif
                                        </td>
                                        <td>
                                            @if ($paydata->where('service_id', $pro->service_id)->where('table_id', $pro->id)->value('status') == 1)
                                                <a href="{{ array_key_exists($pro->service_id, $receiptroute) && $receiptroute[$pro->service_id] != '' ? route($receiptroute[$pro->service_id], encrypt($pro->id)) : '#' }}" class="btn btn-primary btn-sm p-1" style="display:block;">
                                                    Receipt Download
                                                </a>
                                            @else
                                                <a href="#" class="btn btn-primary btn-sm p-1" style="display:none;">
                                                    Receipt Download
                                                </a>
                                            @endif

                                            @php
                                                $statusEntry = $statusdata->where('service_id', $pro->service_id)->where('table_id', $pro->id)->first();
                                            @endphp

                                            @if (Auth::check() && Auth::user()->hasRole('Clerk'))
                                                @if ($statusEntry && $statusEntry->status == 1)
                                                    @php
                                                        $receiptPath = $statusEntry->offlinereceipt;
                                                    @endphp

                                                    @if ($receiptPath)
                                                        <a href="{{ asset('storage/' . $receiptPath) }}" target="_blank" class="btn btn-primary btn-sm">
                                                            View Receipt
                                                        </a>
                                                    @else
                                                        {{-- <span class="text-muted">No receipt uploaded</span> --}}
                                                    @endif
                                                @endif
                                            @endif

                                        </td>
                                        <td>
                                            {{-- @if (Auth::check() && Auth::user()->hasRole('Clerk')) --}}
                                            {{-- @if (Auth::check() && Auth::user()->hasRole('sectionengineer')) --}}
                                            @if (Auth::check() && (Auth::user()->hasRole('sectionengineer') || Auth::user()->hasRole('Clerk')))
                                                @php
                                                    $status = $statusdata->where('service_id', $pro->service_id)->where('table_id', $pro->id)->value('status');
                                                    $statuses = $statusdata->where('service_id', $pro->service_id)->where('table_id', $pro->id)->first();

                                                    $statusRecord = $pro->status()->where('service_id', $pro->service_id)->first();
                                                    $statusId = $statusRecord?->table_id;
                                                    $serviceId = $statusRecord?->service_id;

                                                    $allowedServiceIds = ['6042', '8042', '9041', '7042', '8920', '8990','8925'];
                                                @endphp

                                                @if ($statusId && in_array($serviceId, $allowedServiceIds) && $status == 1)
                                                    @if ($statuses->document_upload)
                                                        <a href="{{ asset('storage/' . $statuses->document_upload) }}" target="_blank" class="btn btn-primary btn-sm">
                                                            View Certificate
                                                        </a>
                                                    @else
                                                        <button type="button" class="btn btn-success btn-sm upload-certificate-btn" data-status-id="{{ $statusId }}" data-service-id="{{ $serviceId }}">
                                                            Upload
                                                        </button>
                                                    @endif
                                                @else
                                                    -
                                                @endif
                                            @endif

                                        </td>

                                        <!--kishori start code-->
                                        {{-- @if (Auth::check() && Auth::user()->hasRole('Clerk') && $pro->service_id == '187')
                                        <td>
                                            <a href="{{ array_key_exists($pro->service_id, $editRoute) && $editRoute[$pro->service_id] != '' ? route($editRoute[$pro->service_id], encrypt($pro->id)) : '#' }}"
                                               class="btn btn-primary">View</a>
                                        </td>
                                        @endif --}}
                                        @if (Auth::check() && ($pro->service_id == '187' || $pro->service_id == '2032'))
                                        
                                            @if (Auth::user()->hasRole('Clerk') || Auth::user()->hasRole('ExecutiveEngineer'))
                                                <td>
                                                    <a href="{{ array_key_exists($pro->service_id, $editRoute) && $editRoute[$pro->service_id] != '' 
                                                                ? route($editRoute[$pro->service_id], encrypt($pro->id)) 
                                                                : '#' }}"
                                                    class="btn btn-primary">
                                                        View
                                                    </a>
                                                </td>
                                            @endif
                                        @endif

                                        <!--kishori end code-->

                                    </tr>
                                @endforeach
                            </tbody>

                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Certificate Upload Modal -->
    <div class="modal fade" id="uploadCertificateModal" tabindex="-1" aria-labelledby="uploadCertificateModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="uploadCertificateModalLabel">Upload Certificate Document</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <div class="modal-body">
                    <form id="uploadCertificateForm" method="POST" enctype="multipart/form-data" action="">
                        @csrf
                        <input type="hidden" name="statusId" id="certificateStatusId">
                        <input type="hidden" name="serviceId" id="serviceId">

                        <div class="mb-3">
                            <label class="col-form-label" for="document_upload">
                                Select Certificate Document <span class="text-danger">*</span>
                            </label>
                            <input type="file" name="document_upload" id="document_upload" class="form-control" accept=".pdf,.jpg,.jpeg,.png" required>
                            <span class="text-danger document_upload_err"></span>
                        </div>
                    </form>

                    <div id="certificateUploadMessage" class="alert d-none" role="alert"></div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="submitCertificateUploadForm">Upload</button>
                </div>
            </div>
        </div>
    </div>



    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    {{-- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> --}}
    <script>
        $('.upload-certificate-btn').on('click', function(e) {
            e.preventDefault();

            let statusId = this.dataset.statusId;
            let serviceId = this.dataset.serviceId;

            $('#certificateStatusId').val(statusId);
            $('#serviceId').val(serviceId);

            console.log('Status ID:', statusId);
            console.log('Service ID:', serviceId);

            $('#certificateUploadMessage').addClass('d-none').removeClass('alert-success alert-danger').text('');
            $('.document_upload_err').text('');

            var uploadUrl = "{{ route('upload_certitficate', ['statusId' => '__STATUS_ID__']) }}";
            uploadUrl = uploadUrl.replace('__STATUS_ID__', statusId);

            $('#uploadCertificateForm').attr('action', uploadUrl);

            var uploadModal = new bootstrap.Modal(document.getElementById('uploadCertificateModal'));
            uploadModal.show();



            $(document).ready(function() {

                // Submit button click triggers form submission
                $('#submitCertificateUploadForm').on('click', function() {
                    $('#uploadCertificateForm').submit();
                });

                // Handle form submission via AJAX
                $('#uploadCertificateForm').on('submit', function(event) {
                    event.preventDefault();

                    var formData = new FormData(this);
                    var uploadMessage = $('#certificateUploadMessage');
                    var fileErr = $('.document_upload_err');

                    uploadMessage.addClass('d-none').removeClass('alert-success alert-danger').text('');
                    fileErr.text('');

                    $.ajax({
                        url: $(this).attr('action'),
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function(data) {
                            if (data.success) {
                                uploadMessage
                                    .removeClass('d-none')
                                    .addClass('alert-success')
                                    .text(data.message);

                                // Hide modal after success
                                var uploadModal = bootstrap.Modal.getInstance(document.getElementById('uploadCertificateModal'));

                                // Reload after short delay
                                setTimeout(function() {
                                    location.reload();
                                    uploadModal.hide();
                                }, 2000);




                            } else {
                                uploadMessage
                                    .removeClass('d-none')
                                    .addClass('alert-danger')
                                    .text(data.message);

                                if (data.errors && data.errors.document_upload) {
                                    fileErr.text(data.errors.document_upload[0]);
                                }
                            }
                        },
                        error: function(xhr) {
                            let errors = xhr.responseJSON?.errors;
                            let allMessages = [];

                            if (errors) {
                                Object.values(errors).forEach(errorArr => {
                                    allMessages.push(errorArr[0]);
                                });
                            } else {
                                allMessages.push('Something went wrong. Please try again.');
                            }

                            uploadMessage
                                .removeClass('d-none')
                                .addClass('alert-danger')
                                .html(allMessages.join('<br>'));
                        }
                    });
                });
            });

        });
    </script>
</x-admin.layout>
