<x-admin.layout>
    <style>
        .form_select_readonly{
            cursor: not-allowed;
             pointer-events: none;
        }
    </style>
    <x-slot name="title">Development Works Quantity-wise Statement / विकास कामांचा प्रमाणानुसार तपशील</x-slot>
    <x-slot name="heading">Development Works Quantity-wise Statement / विकास कामांचा प्रमाणानुसार तपशील</x-slot>
    @php
        $can_update  = (Auth::check() && Auth::user()->hasRole('Clerk')) || Auth::user()->hasRole('JuniorEngineer');
        $approve_require_fields = !empty($developmentworkquantity->upload_photo) && !empty($developmentworkquantity->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 }}">

                            <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="{{ $developmentworkquantity->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="{{ $developmentworkquantity->applicant_address }}" readonly>
                                <span class="text-danger is-invalid applicant_address_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="mobile_no"> Mobile Number / मोबाईल नंबर<span class="text-danger">*</span></label>
                                <input class="form-control" id="mobile_no" name="mobile_no" type="text" placeholder="Enter Mobile No. / मोबाईल नंबर भरा" maxlength="10" pattern="\d{10}" title="Please enter exactly 10 digits" required inputmode="numeric" value="{{ old('mobile_no', $developmentworkquantity->mobile_no) }}" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0,10);" readonly>
                                <span class="text-danger is-invalid mobile_no_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label for="email_id">Email id<span class="text-danger">*</span></label>
                                <input type="text" name="email_id" id="email_id" class="form-control" placeholder="Enter email id" value="{{ $developmentworkquantity->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 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="{{ $developmentworkquantity->company_name }}" readonly>
                                <span class="text-danger is-invalid company_name_err"></span>
                            </div>

                            <div class="col-md-4">
                                <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="{{ $developmentworkquantity->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 Number / काम आदेश क्रमांक<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="{{ $developmentworkquantity->work_order_no }}" readonly>
                                <span class="text-danger is-invalid work_order_no_err"></span>
                            </div> --}}

                            {{-- <div class="col-md-4">
                                <label for="work_completition_date">Work Completion Date / काम पूर्ण होण्याची तारीख</label>
                                <input type="date" name="work_completition_date" id="work_completition_date" class="form-control" placeholder="Enter work order number" value="{{ $developmentworkquantity->work_completition_date }}" readonly>
                                <span class="text-danger is-invalid work_completition_date_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">
                                    <option value="" disabled>-- Select --</option>
                                    <option value="Yes" {{ $developmentworkquantity->work_comp_certi == 'Yes' ? 'selected' : '' }}>Yes / होय</option>
                                    <option value="No" {{ $developmentworkquantity->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_area">Ward Area / प्रभाग क्षेत्र <span class="text-danger">*</span></label>
                                <select name="ward_area" id="ward_area" class="form-select @if(!$can_update) form_select_readonly  @endif>">
                                    @foreach ($options as $option)
                                        <option {{ $developmentworkquantity->ward_area == $option->id ? 'selected' : '' }} value="{{ $option->id }}">{{ $option->name }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid ward_area_err"></span>
                            </div>

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

                            <div class="col-md-4">
                                <label for="work_order_do">Work Order Doc / कार्य आदेश दस्तऐवज<span class="text-danger">*</span></label> <br>
                                {{-- <input type="file" name="work_order_do" id="work_order_do" class="form-control" accept="image/*,.pdf" > --}}
                                @if ($developmentworkquantity->work_order_doc)
                                    <a href="{{ asset('storage/' . $developmentworkquantity->work_order_doc) }}" target="_blank">View Document</a>
                                @endif
                                <span class="text-danger is-invalid work_order_do_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label for="work_completition_do">Work Completion Certificate (Last 3 years) / साइट भेट फोटो<span class="text-danger">*</span></label>
                                {{-- <input type="file" name="work_completition_do" id="work_completition_do" class="form-control" accept="image/*"  > --}}
                                <br>
                                @if ($developmentworkquantity->work_completition_doc)
                                    <a href="{{ asset('storage/' . $developmentworkquantity->work_completition_doc) }}" target="_blank">View Document</a>
                                @endif
                                <span class="text-danger is-invalid work_completition_do_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="prescribed_doc">Upload Application In Prescribed Format / विहित नमुन्यातील अर्ज अपलोड करा <span class="text-danger">*</span></label>
                                <br>
                                @if ($developmentworkquantity->prescribed_docs)
                                    <a href="{{ asset('storage/' . $developmentworkquantity->prescribed_docs) }}" target="_blank">View Document</a>
                                @endif
                            </div>


                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="upload_photos">Upload Report<span class="text-danger">*</span></label>
                                {{-- <span style="color:red;">please upload Report</span> --}}
                                 @if($can_update)
                                   <input class="form-control" id="upload_photos" name="upload_photos" type="file">
                                 @endif
                                <span class="text-danger is-invalid upload_photos_err"></span>
                                @if (!empty($developmentworkquantity->upload_photo))
                                <br>
                                    <a href="{{ asset('storage/' . $developmentworkquantity->upload_photo) }}" target="_blank">View Document</a>

                                @endif
                            </div>



                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="upload_reports">Upload Statement<span class="text-danger">*</span></label>
                                {{-- <span style="color:red;">please upload Statement</span> --}}
                                 @if($can_update)
                                    <input class="form-control" id="upload_reports" name="upload_reports" type="file">
                                 @endif
                                <span class="text-danger is-invalid upload_reports_err"></span>
                                @if (!empty($developmentworkquantity->upload_report))
                                 <br>
                                    <a href="{{ asset('storage/' . $developmentworkquantity->upload_report) }}" target="_blank">View Document</a>
                                @endif
                            </div>


                            {{-- @if ((Auth::check() && Auth::user()->hasRole('JuniorEngineer')) || Auth::user()->hasRole('ExecutiveEngineer') || Auth::user()->hasRole('DeputyEngineer'))
                                @if (empty($developmentworkquantity->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>
                                    <small><a href="{{ asset('storage/' . $developmentworkquantity->geotags) }}" target="_blank">View Document</a></small>
                                    <span class="text-danger is-invalid geotag_err"></span>
                                </div>
                            @endif
                              @endif --}}


                            <div class="col-md-12">
                                <div class="row">
                                    <div class="col-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>
                                </div>

                            </div>

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

                            @if (!$currentUser->hasRole('clerk'))
                                <div>
                                    @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> {{ $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 ($developmentworkquantity->property_doc)
                                    <a href="{{ asset('storage/' . $developmentworkquantity->property_doc) }}" target="_blank">View Document</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">

                        {{-- @php
                            dd($can_update && $approve_require_fields);
                        @endphp --}}

                        <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 type="button"  id="btnCancel" class="btn btn-warning">Cancel</button>
                        @if($can_update)
                            <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('development-work-quantity.update', $developmentworkquantity->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');
            },
        });

    });
</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'
                });
            }
        });

        function printErrMsg(msg) {
            $("span.text-danger").text(""); // Clear previous errors
            $.each(msg, function(key, value) {
                $("span." + key + "_err").text(value[0]);
            });
        }

    });


    $(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>
