<x-admin.layout>
    <x-slot name="title">Completion Certificate for Development Work / विकास कामाबाबत पूर्णत्वाचा दाखला</x-slot>
    <x-slot name="heading">Completion Certificate for Development Work / विकास कामाबाबत पूर्णत्वाचा दाखला</x-slot>
    @php
        $can_update  = (Auth::check() && Auth::user()->hasRole('Clerk')) || Auth::user()->hasRole('JuniorEngineer');
        $approve_require_fields = !empty($completitioncertificate->upload_photo) && !empty($completitioncertificate->upload_report);
    @endphp
    <div class="row" id="addContainer">
        <div class="col-sm-12">
            <div class="card">
                <form class="theme-form" name="addForm" id="addForm" enctype="multipart/form-data">
                    @csrf

                    <div class="card-header">
                        <h4 class="card-title">View Details</h4>
                    </div>

                    <div class="card-body">
                        <div class="mb-3 row">
                            <input type="hidden" model-id="id" value="{{ $status->id }}">

                            {{-- 1. Applicant Details --}}
                            <h5 class="mb-3">Applicant Details / अर्जदाराची माहिती</h5>
                            <div class="col-md-4">
                                <label for="applicant_name">Applicant Name / अर्जदाराचे नाव<span class="text-danger">*</span></label>
                                <input type="text" name="applicant_name" id="applicant_name" class="form-control" placeholder="Enter applicant name" value="{{ $completitioncertificate->applicant_name }}" readonly>
                                <span class="text-danger is-invalid applicant_name_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label for="applicant_address">Applicant Address / अर्जदाराचा पत्ता<span class="text-danger">*</span></label>
                                <input type="text" name="applicant_address" id="applicant_address" class="form-control" placeholder="Enter applicant address" value="{{ $completitioncertificate->applicant_address }}" readonly>
                                <span class="text-danger is-invalid applicant_address_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label for="mobile_no">Mobile Number / मोबाईल नंबर<span class="text-danger">*</span></label>
                                <input type="text" name="mobile_no" id="mobile_no" class="form-control" placeholder="Enter mobile number" value="{{ $completitioncertificate->mobile_no }}" readonly>
                                <span class="text-danger is-invalid mobile_no_err"></span>
                            </div>

                           <div class="col-md-4">
                                <label class="col-form-label" for="email_id">Email ID / ईमेल आयडी<span class="text-danger">*</span></label>
                                <input class="form-control" id="email_id" name="email_id" type="email" placeholder="Enter Email ID / ईमेल भरा" value="{{ $completitioncertificate->email_id }}"  readonly>
                                <span class="text-danger is-invalid email_id_err"></span>
                            </div>




                            {{-- 2. Owner Details --}}
                            <h5 class="mt-4 mb-3">Work Details / मालकाची माहिती</h5>
                            <div class="col-md-4">
                                <label class="col-form-label" for="company_name">Company Name / कंपनीचे नाव<span class="text-danger">*</span></label>
                                <input type="text" name="company_name" id="company_name" class="form-control" placeholder="Enter owner name" value="{{ $completitioncertificate->company_name }}" readonly>
                                <span class="text-danger is-invalid company_name_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="work_name">Work Name /कामाचे नाव<span class="text-danger">*</span></label>
                                <input type="text" name="work_name" id="work_name" class="form-control" placeholder="Enter property address" value="{{ $completitioncertificate->work_name }}" readonly>
                                <span class="text-danger is-invalid work_name_err"></span>
                            </div>

                            {{-- <div class="col-md-4">
                                <label for="work_order_no">Work Order No / कार्य आदेश क्रमांक<span class="text-danger">*</span></label>
                                <input type="text" name="work_order_no" id="work_order_no" class="form-control" placeholder="Enter work order number" value="{{ $completitioncertificate->work_order_no }}" readonly>
                                <span class="text-danger is-invalid work_order_no_err"></span>
                            </div> --}}
{{--
                            <div class="col-md-3">
                                <label for="work_comp_certi">Work Completion Certificate<span class="text-danger">*</span></label>
                                <select class="form-select" name="work_comp_certi" id="work_comp_certi" readonly>
                                    <option value="" disabled>-- Select --</option>
                                    <option value="Yes" {{ $completitioncertificate->work_comp_certi == 'Yes' ? 'selected' : '' }}>Yes / होय</option>
                                    <option value="No" {{ $completitioncertificate->work_comp_certi == 'No' ? 'selected' : '' }}>No / नाही</option>
                                </select>
                                <span class="text-danger is-invalid work_comp_certi_err"></span>
                            </div> --}}

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="ward">Ward Area / प्रभाग क्षेत्र <span class="text-danger">*</span></label>
                                <select name="ward_area" id="ward" class="form-select" readonly>
                                    @foreach ($options as $option)
                                        <option {{ $completitioncertificate->ward_area == $option->id ? 'selected' : '' }} value="{{ $option->id }}">{{ $option->name }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid ward_err"></span>
                            </div>

                            {{-- 4. Document Uploads --}}


                            <h5 class="mt-4 mb-3">Document Uploads / दस्तऐवज अपलोड करा</h5>

                            <div class="col-md-3">
                                <label  class="col-form-label" for="work_order_doc">Work Order Doc / कार्यदेश  कागदपत्रे<span class="text-danger">*</span></label>
                                {{-- <input type="file" name="work_order_doc" id="work_order_doc" class="form-control" accept="image/*,.pdf" > --}}
                              <div>
                                    @if ($completitioncertificate->work_order_doc)
                                    <a href="{{ asset('storage/' . $completitioncertificate->work_order_doc) }}" target="_blank">View Doc</a>
                                @endif
                              </div>
                                
                                <span class="text-danger is-invalid work_order_doc_err"></span>
                            </div>

                            <div class="col-md-3">
                                <label  class="col-form-label" for="work_completition_certificate">Work Completion Certificate (Last 3 years) / काम पूर्णत्वाचे प्रमाणपत्र (मागील ३ वर्षांचे)<span class="text-danger">*</span></label>
                                {{-- <input type="file" name="work_completition_certificate" id="work_completition_certificate" class="form-control" accept="image/*" > --}}
                                @if ($completitioncertificate->work_completition_certificate)
                                    <a href="{{ asset('storage/' . $completitioncertificate->work_completition_certificate) }}" target="_blank">View Doc</a>
                                @endif
                                <span class="text-danger is-invalid work_completition_certificate_err"></span>
                            </div>

                             <div class="col-md-4" id="upload_section">
                                <label class="col-form-label" for="prescribed_doc">Upload Application In Prescribed Format / विहित नमुन्यातील अर्ज अपलोड करा <span class="text-danger">*</span></label>
                                {{-- <input class="form-control" id="prescribed_doc" name="prescribed_doc" type="file" placeholder="Enter Document No. / दस्तऐवज क्रमांक भरा" required> --}}
                                  @if ($completitioncertificate->prescribed_docs)
                                    <a href="{{ asset('storage/' . $completitioncertificate->prescribed_docs) }}">View File</a>
                                    @endif
                                <span class="text-danger is-invalid prescribed_doc_err"></span>
                               </div>


                             @if(Auth::user()->hasRole('JuniorEngineer') || Auth::user()->hasRole('Clerk'))
                                <div class="col-md-4 mb-2">
                                    <label class="col-form-label" >Upload Report<span class="text-danger">*</span></label>
                                    <input class="form-control" id="upload_reports" name="upload_reports" type="file">
                                    <div>
                                      @if (!empty($completitioncertificate->upload_report))
                                        <small>
                                            <a href="{{ asset('storage/' . $completitioncertificate->upload_report) }}" target="_blank">
                                                View Document
                                            </a>
                                        </small>
                                    @endif

                                    </div>                               
                                    <span class="text-danger is-invalid upload_reports_err"></span>
                                </div>
                            @else
                                <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="upload_reports">Upload Report<span class="text-danger">*</span></label>
                                    {{-- <input type="file" name="upload_reports" id="upload_reports" class="form-control" accept="image/*" > --}}                                  
                                    <div>
                                    <small><a href="{{ asset('storage/' . $completitioncertificate->upload_report) }}" target="_blank">View Document</a></small>
                                    </div>
                                    <span class="text-danger is-invalid upload_reports_err"></span>
                                </div>
                            @endif

                            @if(Auth::user()->hasRole('JuniorEngineer') || Auth::user()->hasRole('Clerk'))
                                <div class="col-md-4 mb-2">
                                    <label class="col-form-label"  for="upload_photos" for="upload_photos">Upload Statement<span class="text-danger">*</span></label>
                                    <input class="form-control" id="upload_photos" name="upload_photos" type="file">
                                    <div>
                                     @if (!empty($completitioncertificate->upload_photo))
                                    <small><a href="{{ asset('storage/' . $completitioncertificate->upload_photo) }}" target="_blank">View Document</a></small>
                                    @endif
                                   </div>
                                    <span class="text-danger is-invalid upload_photos_err"></span>
                                </div>
                            @else
                                <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="upload_photos">Upload Statement<span class="text-danger">*</span></label>
                                   
                                 {{-- <input type="file" name="upload_photo" id="upload_photo" class="form-control" accept="image/*" > --}}
                                   <div>
                                    <small><a href="{{ asset('storage/' . $completitioncertificate->upload_photo) }}" target="_blank">View Document</a></small>
                                   </div>
                                    <span class="text-danger is-invalid upload_photos_err"></span>
                                </div>
                            @endif

                              @if (Auth::check() && Auth::user()->hasRole('JuniorEngineer') || Auth::user()->hasRole('ExecutiveEngineer') ||Auth::user()->hasRole('DeputyEngineer'))
                                @if(empty($completitioncertificate->geotags))
                                <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="geotag">Upload Geo Tag Photo<span class="text-danger">*</span></label>
                                    <span style="color:red;">please upload photo</span>
                                    <input class="form-control" id="geotag" name="geotag" type="file" required>
                                    <span class="text-danger is-invalid geotag_err"></span>
                                </div>
                            @else
                                <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="geotag">Upload Geo Tag Photo<span class="text-danger">*</span></label>
                                    {{-- <input type="file" name="upload_photo" id="upload_photo" class="form-control" accept="image/*" > --}}
                                    <small><a href="{{ asset('storage/' . $completitioncertificate->geotags) }}" target="_blank">View Document</a></small>
                                    <span class="text-danger is-invalid geotag_err"></span>
                                </div>
                            @endif
                              @endif
                              

                            <div class="col-md-4">
                                <label for="remark">Remark<span class="text-danger">*</span></label>
                                <textarea id="Remark" name="remark" class="form-control" rows="4" maxlength="255"></textarea>
                            </div>

                                @php
                            $currentUser = Auth::user();
                        @endphp

                        @if(!$currentUser->hasRole('clerk'))
                            <div class="mt-2">
                                @foreach($approvaldata as $approval)
                                    @if(!is_null($approval->remark))
                                        <div class="mb-3 p-2 border rounded bg-light">
                                            <p><strong>Approver Name:</strong> {{ $approval->approver->name ?? 'N/A' }}</p>
                                            <p><strong>Approver Time:</strong> {{ $approval->updated_at?? 'N/A' }}</p>

                                            @if($approval->approver_user_id == Auth::user()->id)
                                                <p><strong>Matched Auth User:</strong> {{ Auth::user()->name }}</p>
                                            @else
                                            @endif

                                            <p><strong>Remark:</strong> {{ $approval->remark }}</p>
                                        </div>
                                    @endif
                                @endforeach
                            </div>
                        @endif

                            {{-- <div class="col-md-3">
                                <label for="property_doc">Property Document / मालमत्तेचे दस्तऐवज<span class="text-danger">*</span></label>
                                <input type="file" name="property_doc" id="property_doc" class="form-control" accept="image/*,.pdf">
                                @if ($completitioncertificate->property_doc)
                                    <a href="{{ asset('storage/' . $completitioncertificate->property_doc) }}" target="_blank">View Doc</a>
                                @endif
                                <span class="text-danger is-invalid property_doc_err"></span>
                            </div> --}}

                            {{-- 5. Declaration --}}
                            {{-- <div class="col-md-12 mt-4">
                                <label for="is_correct_info">Declaration / घोषणापत्र:</label>
                                <div class="form-check d-flex align-items-start">
                                    <input type="checkbox" class="form-check-input mt-1" id="is_correct_info" name="is_correct_info" checked value="yes">
                                    <label class="form-check-label ms-2" for="is_correct_info">
                                        "All information provided above is correct and I shall be fully responsible for any discrepancy. <br>
                                        वरील पुरविलेली सर्व माहिती ही अचूक असून, त्यात कुठल्याही प्रकारची तफावत आढळल्यास त्यास मी पूर्णतः जबाबदार असेन."
                                    </label>
                                </div>
                                <span class="text-danger is-invalid is_correct_info_err"></span>
                            </div> --}}

                        </div>
                    </div>

                    <div class="card-footer">
                        <button type="button" class="btn btn-primary approveBtn" @if($can_update && !$approve_require_fields) disabled @endif  data-id="{{ $status->id }}">Approve</button>
                        <button type="button" class="btn btn-danger rejectBtn" data-id="{{ $status->id }}">Reject</button>
                        <button id="btnCancel" type="button" class="btn btn-warning">Cancel</button>
                        @if (Auth::check() && Auth::user()->hasRole('Clerk') || Auth::user()->hasRole('JuniorEngineer') )
                        <button type="submit" class="btn btn-secondary" id="addSubmit">Update</button>
                    @endif
                    </div>
                </form>
            </div>
        </div>
    </div>
</x-admin.layout>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    document.getElementById('btnCancel').addEventListener('click', function() {
        window.location.href = "{{ route('pendinglist') }}";
    });

     $("#addForm").submit(function(e) {
        e.preventDefault();
        $("#addSubmit").prop('disabled', true);

        var formdata = new FormData(this);
        var updateUrl = '{{ route('completition-certificate.update', $completitioncertificate->id) }}';
        formdata.append('_method', 'PUT');
        $.ajax({
            url: updateUrl,
            type: 'POST',
            data: formdata,
            contentType: false,
            processData: false,
            beforeSend: function() {
                $('#preloader').css('opacity', '0.5');
                $('#preloader').css('visibility', 'visible');
            },
            success: function(response) {
                Swal.fire({
                    icon: 'success',
                    title: 'Updated Sucessfully!',
                    text: response.message,
                    confirmButtonText: 'OK'
                }).then(() => {
                  window.location.href = "{{ route('pendinglist') }}";
                });
            }, 
            statusCode: {
                422: function(xhr) {
                    printErrMsg(xhr.responseJSON.errors);
                    $("#addSubmit").prop("disabled", false);
                },
                500: function() {
                    swal("Error!", "Something went wrong!", "error");
                    $("#addSubmit").prop("disabled", false);
                }
            },
            complete: function() {
                $('#preloader').css('opacity', '0');
                $('#preloader').css('visibility', 'hidden');
            },
        });

        function printErrMsg(msg) {
            $("span.text-danger").text(""); // Clear previous errors
            $.each(msg, function(key, value) {
                $("span." + key + "_err").text(value[0]);
            });
        }
    });
</script>
<script>
    $(document).ready(function() {
        $('.approveBtn').on('click', function() {
            let statusId = $(this).data('id');
            let remark = $('#Remark').val();

            if (remark.trim() !== '') {
                $.ajax({
                    url: '/approve-item/' + statusId,
                    type: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}',
                        remark: remark
                    },
                    success: function(response) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            text: response.message,
                            confirmButtonText: 'OK'
                        }).then(() => {
                            window.location.href = response.redirect_url;
                        });
                    },
                    error: function(xhr) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error!',
                            text: 'Error: ' + xhr.responseText,
                            confirmButtonText: 'OK'
                        });
                    }
                });
            } else {
                Swal.fire({
                    icon: 'warning',
                    title: 'Warning!',
                    text: 'Please Add Remark',
                    confirmButtonText: 'OK'
                });
            }
        });
          
    });


    $(document).ready(function() {
        $('.rejectBtn').on('click', function() {
            var statusId = $(this).data('id');
            let remark = $('#Remark').val();

            if (remark !== null && remark.trim() !== '') {
                $.ajax({
                    url: '/reject-item/' + statusId,
                    type: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}',
                        remark: remark
                    },
                    success: function(response) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            text: response.message,
                            confirmButtonText: 'OK'
                        }).then(() => {
                      window.location.href = response.redirect_url;

                        });
                    },
                    error: function(xhr) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error!',
                            text: 'Error: ' + xhr.responseText,
                            confirmButtonText: 'OK'
                        });
                    }
                });
            } else {
                Swal.fire({
                    icon: 'warning',
                    title: 'Warning!',
                    text: 'Please Add Remark',
                    confirmButtonText: 'OK'
                });
            }
        });
    });
</script>
