<x-admin.layout>
    <x-slot name="title">Granting permission for laying underground telecommunication ducts/भूमिगत दूरसंचार वाहिनी</x-slot>
    <x-slot name="heading">Granting permission for laying underground telecommunication ducts/भूमिगत दूरसंचार वाहिनी</x-slot>
@php

$can_update = Auth::check() && Auth::user()->hasRole('Clerk');

$isEditable = ((Auth::check() && Auth::user()->hasRole('Clerk')) 
                    || Auth::user()->hasRole('JuniorEngineer'))
                    && $status->service_id == '2032';


                    

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

    // 🔥 Clerk + payStatus == 1 → force disable
if (Auth::check() && Auth::user()->hasRole('Clerk') && $payStatus == 1  || $status->receipt_status == 1) {
    $isEditable = false;
}






    
$approve_require_fields = true;
// if (empty($grantingTelecom->start_date) || empty($grantingTelecom->end_date)) {
//     $approve_require_fields = false;
// }

foreach ($multidata as $row) {

    if (empty($row->roadtype) ||
        empty($row->startpoint) ||
        empty($row->endpoint) ||
        empty($row->length) ||
        empty($row->defect_factor)) {

        $approve_require_fields = false;
        break;
    }
}
 $originalWard = $grantingTelecom->ward_area;
     $currentWard = old('ward_area', $originalWard);
$wardChanged = ($currentWard != $originalWard);

// 2) Junior Engineer mandatory: upload_photo required
if (Auth::check() && Auth::user()->hasRole('JuniorEngineer')) {

    if (empty($grantingTelecom->upload_photo)) {
        $approve_require_fields = false;
    }
}



@endphp

    <!-- Add Form -->
    <div class="row" id="addContainer">
        <div class="col-sm-12">

            <form class="theme-form" name="addForm" id="addForm" enctype="multipart/form-data">
                @csrf
                <div class="card">
                    <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 }}">
                            <input type="hidden" model-id="id" value="{{ $status->service_id }}">


                            <div class="col-md-4">
                                <label class="col-form-label" for="f_name">Applicant's Full Name / अर्जदाराचे संपूर्ण नाव <span class="text-danger">*</span></label>
                                <input class="form-control" id="f_name" name="f_name" type="text" placeholder="Enter First Name" value="{{ $grantingTelecom->f_name }}" readonly>
                                <span class="text-danger is-invalid f_name_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="m_name">Applicant Type ( Indivisual/Company) / अर्ज प्रकार (वैयक्तिक / कंपनी) <span class="text-danger">*</span></label>
                                <input class="form-control" id="m_name" name="m_name" type="text" placeholder="Enter Middle Name" value="{{ $grantingTelecom->m_name }}" readonly>
                                <span class="text-danger is-invalid m_name_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="l_name">Applicant's Full Address / अर्जदाराचा संपूर्ण पत्ता <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="l_name" name="l_name" type="text" placeholder="Enter Last Name" readonly>{{ $grantingTelecom->l_name }}</textarea>
                                <span class="text-danger is-invalid l_name_err"></span>
                            </div>
                                {{-- @if (((Auth::check() && Auth::user()->hasRole('Clerk')) || Auth::user()->hasRole('JuniorEngineer')) && $status->service_id == '2032')

                            <div class="col-md-3">
                                <label class="col-form-label" for="ward_area">Ward Type<span class="text-danger">*</span></label>
                                <select class="form-select" name="ward_area" id="ward_area" readonly>
                                    <option value="">Select Ward</option>
                                    @foreach ($options as $ward)
                                        <option @if ($grantingTelecom->ward_area == $ward->id) selected @endif value="{{ $ward->id }}">{{ $ward->name }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid ward_area_err"></span>
                            </div>
                            @else
                             <div class="col-md-3">
                                <label class="col-form-label" for="ward_area">Ward Type<span class="text-danger">*</span></label>
                                <select class="form-select" name="ward_area" id="ward_area" readonly="" disabled="">
                                    <option value="">Select Ward</option>
                                    @foreach ($options as $ward)
                                        <option @if ($grantingTelecom->ward_area == $ward->id) selected @endif value="{{ $ward->id }}">{{ $ward->name }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid ward_area_err"></span>
                            </div>
                            @endif --}}

                            {{-- @if (
    Auth::check() && (
        (Auth::user()->hasRole('Clerk') && $payStatus != 1  || $status->receipt_status != 1) || 
        Auth::user()->hasRole('JuniorEngineer')
    ) && $status->service_id == '2032'
) --}}

 {{-- @if (
    Auth::check() && (
        (
            Auth::user()->hasRole('Clerk') 
            && ($payStatus != 1 || $status->receipt_status != 1)
        )
        || Auth::user()->hasRole('JuniorEngineer')
    ) && $status->service_id == '2032'
)
    <div class="col-md-3">
        <label class="col-form-label" for="ward_area">Ward Type<span class="text-danger">*</span></label>
        <select class="form-select" name="ward_area" id="ward_area" readonly>
            <option value="">Select Ward</option>
            @foreach ($options as $ward)
                <option @if ($grantingTelecom->ward_area == $ward->id) selected @endif value="{{ $ward->id }}">{{ $ward->name }}</option>
            @endforeach
        </select>
        <span class="text-danger is-invalid ward_area_err"></span>
    </div>
@else
    <div class="col-md-3">
        <label class="col-form-label" for="ward_area">Ward Type<span class="text-danger">*</span></label>
        <select class="form-select" name="ward_area" id="ward_area" readonly disabled>
            <option value="">Select Ward</option>
            @foreach ($options as $ward)
                <option @if ($grantingTelecom->ward_area == $ward->id) selected @endif value="{{ $ward->id }}">{{ $ward->name }}</option>
            @endforeach
        </select>
        <span class="text-danger is-invalid ward_area_err"></span>
    </div>
@endif --}}

@if (
    Auth::check() &&
    (
        (
            Auth::user()->hasRole('Clerk') 
            && ($payStatus != 1 && $status->receipt_status != 1)
        )
        || Auth::user()->hasRole('JuniorEngineer')
    )
    && $status->service_id == '2032'
)
    {{-- ENABLED --}}
    <div class="col-md-3">
        <label class="col-form-label" for="ward_area">Ward Type<span class="text-danger">*</span></label>
        <select class="form-select" name="ward_area" id="ward_area" readonly>
            <option value="">Select Ward</option>
            @foreach ($options as $ward)
                <option @if ($grantingTelecom->ward_area == $ward->id) selected @endif 
                        value="{{ $ward->id }}">{{ $ward->name }}</option>
            @endforeach
        </select>
        <span class="text-danger is-invalid ward_area_err"></span>
    </div>
@else
    {{-- DISABLED --}}
    <div class="col-md-3">
        <label class="col-form-label" for="ward_area">Ward Type<span class="text-danger">*</span></label>
        <select class="form-select" name="ward_area" id="ward_area" readonly disabled>
            <option value="">Select Ward</option>
            @foreach ($options as $ward)
                <option @if ($grantingTelecom->ward_area == $ward->id) selected @endif 
                        value="{{ $ward->id }}">{{ $ward->name }}</option>
            @endforeach
        </select>
        <span class="text-danger is-invalid ward_area_err"></span>
    </div>
@endif




                            <div class="col-md-4">
                                <label class="col-form-label" for="mobile_num">Mobile Number<span class="text-danger">*</span></label>
                                <input class="form-control" id="mobile_num" name="mobile_num" type="text" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter Mobile Number" value="{{ $grantingTelecom->mobile_num }}" readonly>
                                <span class="text-danger is-invalid mobile_num_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="email">Email Id<span class="text-danger">*</span></label>
                                <input class="form-control" id="email" name="email" type="email" placeholder="Enter Email" value="{{ $grantingTelecom->email }}" readonly>
                                <span class="text-danger is-invalid email_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="aadhar_num">Aadhar Number<span class="text-danger">*</span></label>
                                <input class="form-control" id="aadhar_num" name="aadhar_num" type="text" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="12" minlength="12" placeholder="Enter Aadhar  Card Number" value="{{ $grantingTelecom->aadhar_num }}" readonly>
                                <span class="text-danger is-invalid aadhar_num_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="property_num">Name Of Company<span class="text-danger">*</span></label>
                                <input class="form-control" id="property_num" name="property_num" type="text" placeholder="Name Of company" value="{{ $grantingTelecom->property_num }}" readonly>
                                <span class="text-danger is-invalid property_num_err"></span>
                            </div>



                            <div class="col-md-6">
                                <label class="col-form-label" for="address">Address of the Road for cutting / रस्ता खोदण्याच्या ठिकाणाचा पत्ता<span class="text-danger">*</span></label>
                                <textarea class="form-control" name="address" id="address" cols="30" rows="2" placeholder="Enter Address" readonly>{{ $grantingTelecom->address }}</textarea>
                                <span class="text-danger is-invalid address_err"></span>
                            </div>



                             {{-- @if (((Auth::check() && Auth::user()->hasRole('Clerk')) || Auth::user()->hasRole('JuniorEngineer')) && $status->service_id == '2032')
                            
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="road_cutting_purpose">Purpose of Road Cutting / रस्ता खोदण्याचे कारण <span class="text-danger">*</span></label>
                                <select name="road_cutting_purpose" id="road_cutting_purpose" placeholder="Select Purpose of Road Cutting" class="form-select" required>
                                    <option value="">Select Road Purpose</option>
                                    <option {{ $grantingTelecom->road_cutting_purpose == 'Faults' ? 'selected' : '' }} value="Faults">Faults</option>
                                    <option {{ $grantingTelecom->road_cutting_purpose == 'Cable Shifting' ? 'selected' : '' }} value="Cable Shifting">Cable Shifting</option>
                                    <option {{ $grantingTelecom->road_cutting_purpose == 'New Connection' ? 'selected' : '' }} value="New Connection">New Connection</option>
                                    <option {{ $grantingTelecom->road_cutting_purpose == 'Optical Fibre' ? 'selected' : '' }} value="Optical Fibre">Optical Fibre</option>
                                    <option {{ $grantingTelecom->road_cutting_purpose == 'New Cable Laying' ? 'selected' : '' }} value="New Cable Laying">New Cable Laying</option>
                                    <option {{ $grantingTelecom->road_cutting_purpose == 'Gas pipeline connection' ? 'selected' : '' }} value="Gas pipeline connection">Gas pipeline connection</option>
                                    <option {{ $grantingTelecom->road_cutting_purpose == 'any other' ? 'selected' : '' }} value="any other">any other</option>
                                </select>

                                <span class="text-danger is-invalid road_cutting_purpose_err"></span>
                                <div class="selected-value d-none" id="road_cutting_purpose"></div>
                            </div>
                            @else
                                   <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="road_cutting_purpose">Purpose of Road Cutting / रस्ता खोदण्याचे कारण <span class="text-danger">*</span></label>
                                <select name="road_cutting_purpose" id="road_cutting_purpose" placeholder="Select Purpose of Road Cutting" class="form-select" readonly="" disabled="">
                                    <option value="">Select Road Purpose</option>
                                    <option {{ $grantingTelecom->road_cutting_purpose == 'Faults' ? 'selected' : '' }} value="Faults">Faults</option>
                                    <option {{ $grantingTelecom->road_cutting_purpose == 'Cable Shifting' ? 'selected' : '' }} value="Cable Shifting">Cable Shifting</option>
                                    <option {{ $grantingTelecom->road_cutting_purpose == 'New Connection' ? 'selected' : '' }} value="New Connection">New Connection</option>
                                    <option {{ $grantingTelecom->road_cutting_purpose == 'Optical Fibre' ? 'selected' : '' }} value="Optical Fibre">Optical Fibre</option>
                                    <option {{ $grantingTelecom->road_cutting_purpose == 'New Cable Laying' ? 'selected' : '' }} value="New Cable Laying">New Cable Laying</option>
                                    <option {{ $grantingTelecom->road_cutting_purpose == 'Gas pipeline connection' ? 'selected' : '' }} value="Gas pipeline connection">Gas pipeline connection</option>
                                    <option {{ $grantingTelecom->road_cutting_purpose == 'any other' ? 'selected' : '' }} value="any other">any other</option>
                                </select>

                                <span class="text-danger is-invalid road_cutting_purpose_err"></span>
                                <div class="selected-value d-none" id="road_cutting_purpose"></div>
                            </div>
                            @endif --}}

                            {{-- @if (
    Auth::check() && (
        (Auth::user()->hasRole('Clerk') && $payStatus != 1 || $status->receipt_status != 1) || 
        Auth::user()->hasRole('JuniorEngineer')
    ) && $status->service_id == '2032'
) --}}
 {{-- @if (
    Auth::check() && (
        (
            Auth::user()->hasRole('Clerk') 
            && ($payStatus != 1 || $status->receipt_status != 1)
        )
        || Auth::user()->hasRole('JuniorEngineer')
    ) && $status->service_id == '2032'
)
    <div class="col-md-4 mb-2">
        <label class="col-form-label" for="road_cutting_purpose">Purpose of Road Cutting / रस्ता खोदण्याचे कारण <span class="text-danger">*</span></label>
        <select name="road_cutting_purpose" id="road_cutting_purpose" placeholder="Select Purpose of Road Cutting" class="form-select" required>
            <option value="">Select Road Purpose</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Faults' ? 'selected' : '' }} value="Faults">Faults</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Cable Shifting' ? 'selected' : '' }} value="Cable Shifting">Cable Shifting</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'New Connection' ? 'selected' : '' }} value="New Connection">New Connection</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Optical Fibre' ? 'selected' : '' }} value="Optical Fibre">Optical Fibre</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'New Cable Laying' ? 'selected' : '' }} value="New Cable Laying">New Cable Laying</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Gas pipeline connection' ? 'selected' : '' }} value="Gas pipeline connection">Gas pipeline connection</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'any other' ? 'selected' : '' }} value="any other">any other</option>
        </select>

        <span class="text-danger is-invalid road_cutting_purpose_err"></span>
        <div class="selected-value d-none" id="road_cutting_purpose"></div>
    </div>
@else
    <div class="col-md-4 mb-2">
        <label class="col-form-label" for="road_cutting_purpose">Purpose of Road Cutting / रस्ता खोदण्याचे कारण <span class="text-danger">*</span></label>
        <select name="road_cutting_purpose" id="road_cutting_purpose" placeholder="Select Purpose of Road Cutting" class="form-select" readonly disabled>
            <option value="">Select Road Purpose</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Faults' ? 'selected' : '' }} value="Faults">Faults</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Cable Shifting' ? 'selected' : '' }} value="Cable Shifting">Cable Shifting</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'New Connection' ? 'selected' : '' }} value="New Connection">New Connection</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Optical Fibre' ? 'selected' : '' }} value="Optical Fibre">Optical Fibre</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'New Cable Laying' ? 'selected' : '' }} value="New Cable Laying">New Cable Laying</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Gas pipeline connection' ? 'selected' : '' }} value="Gas pipeline connection">Gas pipeline connection</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'any other' ? 'selected' : '' }} value="any other">any other</option>
        </select>

        <span class="text-danger is-invalid road_cutting_purpose_err"></span>
        <div class="selected-value d-none" id="road_cutting_purpose"></div>
    </div>
@endif --}}

@if (
    Auth::check() &&
    (
        (
            Auth::user()->hasRole('Clerk') 
            && ($payStatus != 1 && $status->receipt_status != 1)
        )
        || Auth::user()->hasRole('JuniorEngineer')
    )
    && $status->service_id == '2032'
)
    <div class="col-md-4 mb-2">
        <label class="col-form-label" for="road_cutting_purpose">
            Purpose of Road Cutting / रस्ता खोदण्याचे कारण 
            <span class="text-danger">*</span>
        </label>

        <select name="road_cutting_purpose" id="road_cutting_purpose" 
                placeholder="Select Purpose of Road Cutting" 
                class="form-select" required>
            <option value="">Select Road Purpose</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Faults' ? 'selected' : '' }} value="Faults">Faults</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Cable Shifting' ? 'selected' : '' }} value="Cable Shifting">Cable Shifting</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'New Connection' ? 'selected' : '' }} value="New Connection">New Connection</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Optical Fibre' ? 'selected' : '' }} value="Optical Fibre">Optical Fibre</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'New Cable Laying' ? 'selected' : '' }} value="New Cable Laying">New Cable Laying</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Gas pipeline connection' ? 'selected' : '' }} value="Gas pipeline connection">Gas pipeline connection</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'any other' ? 'selected' : '' }} value="any other">any other</option>
        </select>

        <span class="text-danger is-invalid road_cutting_purpose_err"></span>
    </div>

@else

    <div class="col-md-4 mb-2">
        <label class="col-form-label" for="road_cutting_purpose">
            Purpose of Road Cutting / रस्ता खोदण्याचे कारण 
            <span class="text-danger">*</span>
        </label>

        <select name="road_cutting_purpose" id="road_cutting_purpose" 
                placeholder="Select Purpose of Road Cutting" 
                class="form-select" readonly disabled>
            <option value="">Select Road Purpose</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Faults' ? 'selected' : '' }} value="Faults">Faults</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Cable Shifting' ? 'selected' : '' }} value="Cable Shifting">Cable Shifting</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'New Connection' ? 'selected' : '' }} value="New Connection">New Connection</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Optical Fibre' ? 'selected' : '' }} value="Optical Fibre">Optical Fibre</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'New Cable Laying' ? 'selected' : '' }} value="New Cable Laying">New Cable Laying</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'Gas pipeline connection' ? 'selected' : '' }} value="Gas pipeline connection">Gas pipeline connection</option>
            <option {{ $grantingTelecom->road_cutting_purpose == 'any other' ? 'selected' : '' }} value="any other">any other</option>
        </select>

        <span class="text-danger is-invalid road_cutting_purpose_err"></span>
    </div>

@endif





                            {{-- <div class="col-md-3">
                                <label class="col-form-label" for="width_road">रस्त्याची रुंदी (मीटर)<span class="text-danger">*</span></label>
                                <input class="form-control" id="width_road" name="width_road" type="number" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter Width" value="{{ $grantingTelecom->width_road }}" readonly>
                                <span class="text-danger is-invalid width_road_err"></span>
                            </div> --}}

                            {{-- <div class="col-md-3">
                                <label class="col-form-label" for="length_width">रस्त्याची लांबीरुंदी (चो. मीटर)<span class="text-danger">*</span></label>
                                <input class="form-control" id="length_width" name="length_width" type="number" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter Length & Width" value="{{ $grantingTelecom->length_width }}" readonly>
                                <span class="text-danger is-invalid length_width_err"></span>
                            </div> --}}

                            <div class="col-md-3">
                                <label class="col-form-label" for="digging_size">खोदण्याचे आकार (मीटर)<span class="text-danger">*</span></label>
                                <input class="form-control" id="digging_size" name="digging_size" type="number" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter Digging size" value="{{ $grantingTelecom->digging_size }}" readonly>
                                <span class="text-danger is-invalid digging_size_err"></span>
                            </div>

                            {{-- <div class="col-md-3">
                                <label class="col-form-label" for="latitude">अक्षांश<span class="text-danger">*</span></label>
                                <input class="form-control" id="latitude" name="latitude" type="number" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter latitude" value="{{ $grantingTelecom->latitude }}" readonly>
                                <span class="text-danger is-invalid latitude_err"></span>
                            </div>

                            <div class="col-md-3">
                                <label class="col-form-label" for="longitude">रेखांश<span class="text-danger">*</span></label>
                                <input class="form-control" id="longitude" name="longitude" type="number" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter longitude" value="{{ $grantingTelecom->longitude }}" readonly>
                                <span class="text-danger is-invalid longitude_err"></span>
                            </div> --}}

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="upload_prescribed_formats">Upload Application in Prescribed Format / विहित नमुन्यातील अर्ज अपलोड करा <span class="text-danger">*</span></label>
                                @if ($grantingTelecom->prescribed_docs)
                                    <a href="{{ asset('storage/' . $grantingTelecom->prescribed_docs) }}">View File</a>
                                @endif
                                {{-- <input class="form-control" id="upload_prescribed_formats" name="upload_prescribed_formats" type="file" required readonly> --}}
                                <span class="text-danger is-invalid upload_prescribed_formats_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="government_docs">Documents prescribed by the government/ शासनाने विहित केलेली कागदपत्रे <span class="text-danger">*</span></label>
                                @if ($grantingTelecom->government_doc)
                                    <a href="{{ asset('storage/' . $grantingTelecom->government_doc) }}">View File</a>
                                @endif
                                <span class="text-danger is-invalid government_docs_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                {{-- <label class="col-form-label" for="outstanding_docs">Certificate of no outstanding debts/ थकबाकी नसल्याचा दाखला <span class="text-danger">*</span></label> --}}
                                 <label class="col-form-label" for="outstanding_docs">
                                        Upload Map / नकाशा अपलोड करा <span class="text-danger">*</span>
                                    </label>
                                @if ($grantingTelecom->outstanding_doc)
                                    <a href="{{ asset('storage/' . $grantingTelecom->outstanding_doc) }}">View File</a>
                                @endif
                                <span class="text-danger is-invalid outstanding_docs_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="tax_docs">Tax clearance/ टॅक्स क्लिअरन्स<span class="text-danger">*</span></label>
                                @if ($grantingTelecom->tax_doc)
                                    <a href="{{ asset('storage/' . $grantingTelecom->tax_doc) }}">View File</a>
                                @endif
                                <span class="text-danger is-invalid tax_docs_err"></span>
                            </div>


                             <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="tax_docs">GPS Photo / जीपीएस फोटो अपलोड करा<span class="text-danger">*</span></label>
                                @if ($grantingTelecom->gps_doc)
                                    <a href="{{ asset('storage/' . $grantingTelecom->gps_doc) }}">View File</a>
                                @endif
                                <span class="text-danger is-invalid tax_docs_err"></span>
                            </div>


                        </div>
                    </div>
                    <div class="card">
                        <div class="card-header">
                            <h4 class="card-title">Generate Demand Note</h4>
                        </div>
                        <div class="card-body">
                            <table class="table table-bordered mt-2" id="roadTable">
                                <thead style="background-color: #eff2f7;">
                                    <tr>
                                        <th>Road Type</th>
                                        <th>Start Point</th>
                                        <th>End Point</th>
                                        <th>Length (m)</th>
                                        <th>Defect Liability</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                {{-- <tbody id="roadTableBody">
                                    @foreach ($multidata as $item)
                                        <tr>
                                            <input type="hidden" name="detail_ids[]" value="{{ $item->id }}">
                                            <td>
                                                <select name="roadtype[]" class="form-select" required>
                                                    <option value="">Select Road Type</option>
                                                    @foreach ($roadtype as $option)
                                                        <option value="{{ $option->id }}" {{ $item->roadtype == $option->id ? 'selected' : '' }}>
                                                            {{ $option->road_type }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </td>
                                            <td>
                                                <input type="text" name="startpoint[]" class="form-control" placeholder="Enter Start Point" value="{{ $item->startpoint }}">
                                            </td>
                                            <td>
                                                <input type="text" name="endpoint[]" class="form-control" placeholder="Enter End Point" value="{{ $item->endpoint }}">
                                            </td>
                                            <td>
                                                <input type="number" name="road_length[]" class="form-control" placeholder="Enter Length" value="{{ $item->length }}">
                                            </td>
                                            <td>
                                                <select name="defect_factor[]" class="form-select">
                                                    <option value="">Select Defect Liability</option>
                                                    @foreach ($multifactor as $option)
                                                        <option value="{{ $option->id }}" {{ $item->defect_factor == $option->id ? 'selected' : '' }}>
                                                            {{ $option->item }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </td>
                                            <td>
                                                <button type="button" class="btn btn-danger removeRow">Delete</button>
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody> --}}
                                
                                <tbody id="roadTableBody">
                                @foreach ($multidata as $item)
                                    <tr>
                                        <input type="hidden" name="detail_ids[]" value="{{ $item->id }}">

                                        {{-- Road Type --}}
                                        <td>
                                            <select name="roadtype[]" class="form-select road_type" {{ $isEditable ? '' : 'disabled' }}>
                                                <option value="">Select Road Type</option>
                                                @foreach ($roadtype as $option)
                                                <option value="{{ $option->id }}" {{ $item->roadtype == $option->id ? 'selected' : '' }}>
                                                    {{ $option->road_type }}
                                                </option>
                                                @endforeach
                                            </select>

                                            {{-- ERROR --}}
                                          <span class="text-danger error-roadtype-{{ $loop->index }}">
                                                @error("roadtype.$loop->index") {{ $message }} @enderror
                                            </span>
                                        </td>

                                        {{-- Start Point --}}
                                        <td>
                                            <input type="text" name="startpoint[]" class="form-control"
                                                placeholder="Enter Start Point" value="{{ $item->startpoint }}" {{ $isEditable ? '' : 'disabled' }}>

                                    
                                            <span class="text-danger error-startpoint-{{ $loop->index }}">
                                            @error("startpoint.$loop->index") {{ $message }} @enderror
                                        </span>

                                        </td>

                                        {{-- End Point --}}
                                        <td>
                                            <input type="text" name="endpoint[]" class="form-control"
                                                placeholder="Enter End Point" value="{{ $item->endpoint }}" {{ $isEditable ? '' : 'disabled' }}>

                                           <span class="text-danger error-endpoint-{{ $loop->index }}">
                                                    @error("endpoint.$loop->index") {{ $message }} @enderror
                                                </span>

                                        </td>

                                        {{-- Length --}}
                                        <td>
                                            <input type="number" name="road_length[]" class="form-control"
                                                placeholder="Enter Length" value="{{ $item->length }}" {{ $isEditable ? '' : 'disabled' }}>

                                           <span class="text-danger error-road_length-{{ $loop->index }}">
                                                @error("road_length.$loop->index") {{ $message }} @enderror
                                            </span>

                                        </td>

                                        {{-- Defect Factor --}}
                                        <td>
                                            <select name="defect_factor[]" class="form-select" {{ $isEditable ? '' : 'disabled' }}>
                                                <option value="">Select Defect Liability</option>
                                                @foreach ($multifactor as $option)
                                                <option value="{{ $option->id }}" {{ $item->defect_factor == $option->id ? 'selected' : '' }}>
                                                    {{ $option->item }}
                                                </option>
                                                @endforeach
                                            </select>

                                            <span class="text-danger error-defect_factor-{{ $loop->index }}">
                                                @error("defect_factor.$loop->index") {{ $message }} @enderror
                                            </span>

                                        </td>
                                        <td>
                                            <button type="button" class="btn btn-danger removeRow" {{ $isEditable ? '' : 'disabled' }}>Delete</button>
                                        </td>
                                    </tr>
                                @endforeach
                                </tbody>

                            </table>
                               @if (((Auth::check() && Auth::user()->hasRole('Clerk')) || Auth::user()->hasRole('JuniorEngineer')) && $status->service_id == '2032')

                            <button type="button" class="btn btn-primary" id="addmore" style="width: 10%;">Add More</button>
                            @else
                            <button type="button" class="btn btn-primary" id="addmore" style="width: 10%; display:none">Add More</button>

                            @endif

                            <div class="row">
                                <div class="col-md-3">
                                    <label class="col-form-label" for="locationame">Name Of Locations<span class="text-danger">*</span></label>
                                    <input class="form-control" id="locationame" name="locationame" type="text" value="{{ $grantingTelecom->locationame }}" required {{ $isEditable ? '' : 'disabled' }}>
                                    <span class="text-danger is-invalid locationame_err"></span>
                                </div>
                                <div class="col-md-3">
                                    <label class="col-form-label" for="no_duct">Number of duct/नलिकांची संख्या<span class="text-danger">*</span></label>
                                    <input class="form-control" id="no_duct" name="no_duct" type="number" value="{{ $grantingTelecom->no_duct }}" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter Length" required {{ $isEditable ? '' : 'disabled' }}>
                                    <span class="text-danger is-invalid no_duct_err"></span>
                                </div>

                                <div class="col-md-3">
                                    <label class="col-form-label" for="no_chamber">Number of chamber /चेंबरची संख्या<span class="text-danger">*</span></label>
                                    <input class="form-control" id="no_chamber" name="no_chamber" type="number" value="{{ $grantingTelecom->no_chamber }}" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter Length" required {{ $isEditable ? '' : 'disabled' }}>
                                    <span class="text-danger is-invalid no_chamber_err"></span>
                                </div>

                                @if ((Auth::check() && Auth::user()->hasRole('DeputyEngineer')) || Auth::user()->hasRole('ExecutiveEngineer') || Auth::user()->hasRole('JuniorEngineer'))
                                    @if (empty($grantingTelecom->upload_photo))
                                        <div class="col-md-4 mb-2">
                                            <label class="col-form-label" for="upload_photos">Upload Photos<span class="text-danger">*</span></label>
                                            <span style="color:red;">please upload photo</span>
                                            <input class="form-control" id="upload_photos" name="upload_photos" type="file" required>
                                            <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 Photos<span class="text-danger">*</span></label>
                                            <small><a href="{{ asset('storage/' . $grantingTelecom->upload_photo) }}" target="_blank">View Document</a></small>
                                            <span class="text-danger is-invalid upload_photos_err"></span>
                                        </div>
                                    @endif
                                @endif

                                {{-- @if ((Auth::check() && Auth::user()->hasRole('Clerk')) || Auth::user()->hasRole('JuniorEngineer') || Auth::user()->hasRole('DeputyEngineer') || (Auth::user()->hasRole('ExecutiveEngineer') && $status->service_id == '2032'))
                                    <div class="col-md-3 mb-2">
                                        <label class="col-form-label" for="start_date">Start Date:<span class="text-danger">*</span></label>
                                        <input type="date" name="start_date" id="start_date" class="form-control" value="{{ isset($grantingTelecom) && isset($grantingTelecom->start_date) ? $grantingTelecom->start_date : '' }}" {{ $isEditable ? '' : 'disabled' }}>
                                        <span class="text-danger is-invalid start_date_err"></span>
                                    </div>

                                    <div class="col-md-3 mb-2">
                                        <label class="col-form-label" for="end_date">End Date:<span class="text-danger">*</span></label>
                                        <input type="date" name="end_date" id="end_date" class="form-control" value="{{ isset($grantingTelecom) && isset($grantingTelecom->end_date) ? $grantingTelecom->end_date : '' }}" {{ $isEditable ? '' : 'disabled' }}>
                                         <span class="text-danger is-invalid end_date_err"></span>
                                    </div>
                                @endif --}}
                                
                                @if ($payStatus == 1 || $status->receipt_status == 1)

                                @if(Auth::check() && 
                                   (Auth::user()->hasRole('Clerk') || 
                                    Auth::user()->hasRole('JuniorEngineer') || 
                                    Auth::user()->hasRole('DeputyEngineer') || 
                                    Auth::user()->hasRole('ExecutiveEngineer')))

                                    @php
                                        $isClerk = Auth::user()->hasRole('Clerk');
                                    @endphp

                                    <div class="col-md-3 mb-2">
                                        <label class="col-form-label" for="start_date">
                                            Start Date:<span class="text-danger">*</span>
                                        </label>
                                        <input 
                                            type="date" 
                                            name="start_date" 
                                            id="start_date" 
                                            class="form-control"
                                            value="{{ isset($grantingTelecom) && isset($grantingTelecom->start_date) ? $grantingTelecom->start_date : '' }}" 
                                       {{ Auth::user()->hasRole('ExecutiveEngineer') ? 'disabled' : '' }}>
                                        <span class="text-danger is-invalid start_date_err"></span>
                                    </div>

                                    <div class="col-md-3 mb-2">
                                        <label class="col-form-label" for="end_date">
                                            End Date:<span class="text-danger">*</span>
                                        </label>
                                        <input 
                                            type="date" 
                                            name="end_date" 
                                            id="end_date" 
                                            class="form-control"
                                            value="{{ isset($grantingTelecom) && isset($grantingTelecom->end_date) ? $grantingTelecom->end_date : '' }}"   
                                        {{ Auth::user()->hasRole('ExecutiveEngineer') ? 'disabled' : '' }}>
                                         <span class="text-danger is-invalid end_date_err"></span>
                                    </div>

                                @endif
                            @endif


                                <div class="col-md-3">
                                    <label for="remark">Remark<span class="text-danger">*</span></label>
                                    <textarea id="Remark" name="remark" maxlength="255"  class="form-control" rows="4"></textarea>
                                </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> {{ Auth::user()->name }}</p>
                                            @else
                                            @endif

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

                            </div>
                            <br>

                            {{-- <label class="col-form-label" for="is_correct_info">Declaration / घोषणापत्र:</label>
                            <div class="col-md-12">
                                <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" 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 (((Auth::check() && Auth::user()->hasRole('Clerk')) || Auth::user()->hasRole('JuniorEngineer')) && $status->service_id == '2032')
                            <button type="submit" class="btn btn-secondary" id="addSubmit">Update</button>
                        @endif --}}

                        @if(Auth::user()->hasRole('ExecutiveEngineer') && $grantingTelecom->is_startdate_enddate == 1)
    <a href="{{ route('grant-telecome.certificatetwo', encrypt($grantingTelecom->id)) }}" 
       class="btn btn-primary {{ $grantingTelecom->is_generated == 1 ? 'disabled' : '' }}" 
       target="_blank" 
       {{ $grantingTelecom->is_generated == 1 ? 'aria-disabled=true tabindex=-1' : '' }}>
        Generate Certificate
    </a>

    <button type="button" 
            class="btn btn-warning revertBtn"
            data-id="{{ $approval->id }}"
            data-status-id="{{ $approval->status_id }}"
            {{ $grantingTelecom->is_generated == 1 ? 'disabled' : '' }}>
        Revert Back
    </button>


                    

 @elseif($grantingTelecom->is_startdate_enddate == 0  || $payStatus == 1 || $status->receipt_status == 1)

    
    
    <button type="button"
        class="btn btn-success approveBtn"
        data-id="{{ $status->id }}"
        {{ ($payStatus == 1 && $grantingTelecom->is_startdate_enddate != 1) || !$approve_require_fields ? 'disabled' : '' }}>
    Approve
</button>

   
    <button type="button" class="btn btn-danger rejectBtn" data-id="{{ $status->id }}">
        Reject
    </button>

   
    <button type="button" id="btnCancel" class="btn btn-secondary">
        Cancel
    </button>

    
                    @if ((Auth::check() && Auth::user()->hasRole('Clerk') || Auth::user()->hasRole('JuniorEngineer')) && $status->service_id == '2032')
                        <button type="submit" class="btn btn-secondary" id="addSubmit">Update</button>
                    @endif


@endif
                        
                    </div>
            </form>
        </div>
    </div>

</x-admin.layout>

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

{{-- <script>
    $(document).ready(function() {
        $('#addmore').click(function() {
            const newRow = `
                <tr>
                    <td>
                        <select name="roadtype[]" class="form-select">
                            <option value="">Select Road Type</option>
                            @foreach ($roadtype as $option)
                                <option value="{{ $option->id }}">{{ $option->road_type }}</option>
                            @endforeach
                        </select>
                        <span class="text-danger error-roadtype-${$('.road-row').length}"></span>

                    </td>
                    <td>
                        <input type="text" name="startpoint[]" class="form-control" placeholder="Enter Start Point">
                        <span class="text-danger error-startpoint-${$('.road-row').length}"></span>

                    </td>
                    <td>
                        <input type="text" name="endpoint[]" class="form-control" placeholder="Enter End Point">
                    </td>
                    <td>
                        <input type="number" name="road_length[]" class="form-control" placeholder="Enter Length">
                    </td>
                    <td>
                        <select name="defect_factor[]" class="form-select">
                            <option value="">Select Defect Liability</option>
                            @foreach ($multifactor as $option)
                                <option value="{{ $option->id }}">{{ $option->item }}</option>
                            @endforeach
                        </select>
                    </td>
                    <td>
                        <button type="button" class="btn btn-danger removeRow">Delete</button>
                    </td>
                </tr>
            `;
            $('#roadTableBody').append(newRow);
        });

        $('#roadTable').on('click', '.removeRow', function() {
            $(this).closest('tr').remove();
        });
    });
</script> --}}
<script>
$(document).ready(function () {

    // Add More Button Click
    $('#addmore').click(function () {
        

        let index = $('#roadTableBody tr').length; // row index
      $(".approveBtn").prop("disabled", true);

        const newRow = `
            <tr>

                <td>
                    <select name="roadtype[]" class="form-select" {{ $isEditable ? '' : 'disabled' }}>
                        <option value="">Select Road Type</option>
                        @foreach ($roadtype as $option)
                            <option value="{{ $option->id }}">{{ $option->road_type }}</option>
                        @endforeach
                    </select>
                    <span class="text-danger error-roadtype-${index}"></span>
                </td>

                <td>
                    <input type="text" name="startpoint[]" class="form-control" placeholder="Enter Start Point" {{ $isEditable ? '' : 'disabled' }}>
                    <span class="text-danger error-startpoint-${index}"></span>
                </td>

                <td>
                    <input type="text" name="endpoint[]" class="form-control" placeholder="Enter End Point" {{ $isEditable ? '' : 'disabled' }}>
                    <span class="text-danger error-endpoint-${index}"></span>
                </td>

                <td>
                    <input type="number" name="road_length[]" class="form-control" placeholder="Enter Length" {{ $isEditable ? '' : 'disabled' }}>
                    <span class="text-danger error-road_length-${index}"></span>
                </td>

                <td>
                    <select name="defect_factor[]" class="form-select" {{ $isEditable ? '' : 'disabled' }}>
                        <option value="">Select Defect Liability</option>
                        @foreach ($multifactor as $option)
                            <option value="{{ $option->id }}">{{ $option->item }}</option>
                        @endforeach
                    </select>
                    <span class="text-danger error-defect_factor-${index}"></span>
                </td>

                <td>
                    <button type="button" class="btn btn-danger removeRow" {{ $isEditable ? '' : 'disabled' }}>Delete</button>
                </td>

            </tr>
        `;

        $('#roadTableBody').append(newRow);
    });

    // REMOVE ROW
    $('#roadTableBody').on('click', '.removeRow', function () {
        const totalRows = $('#roadTableBody tr').length;
       if (totalRows <= 1) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Required Field',
                    text: 'It is required field, cannot remove.',
                    confirmButtonColor: '#3085d6',
                });
                return false;
            }

            $(this).closest('tr').remove();
            $(".approveBtn").prop("disabled", false);
        });

    

});
</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('grant-telecome.update', $grantingTelecom->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') }}';
                });
            },
               error: function(xhr) {
            if (xhr.status === 422) {
                let errors = xhr.responseJSON.errors;

                Object.keys(errors).forEach(function(key) {

                    // key = "startpoint.0"
                    let parts = key.split(".");
                    let field = parts[0];  // startpoint
                    let index = parts[1];  // 0
                    let message = errors[key][0];

                    // Show error under correct TD span
                    $(`.error-${field}-${index}`).text(message);
                });

                $("#addSubmit").prop('disabled', false);
            }
        },
            complete: function() {
                $('#preloader').css('opacity', '0');
                $('#preloader').css('visibility', 'hidden');
            },
        });

    });
</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('grant-telecome.update', $grantingTelecom->id) }}';
    formdata.append('_method', 'PUT');

    $.ajax({
        url: updateUrl,
        type: 'POST',
        data: formdata,
        contentType: false,
        processData: false,

        beforeSend: function() {
            $('#preloader').css({ opacity: '0.5', visibility: 'visible' });

            // CLEAR ALL OLD ERRORS
            $("span.text-danger").text("");
        },

        success: function(response) {
            Swal.fire({
                icon: 'success',
                title: 'Updated Sucessfully!',
                text: response.message,
                confirmButtonText: 'OK'
            }).then(() => {
                window.location.href = '{{ route('pendinglist') }}';
            });
        },

        // error: function(xhr) {
        //     if (xhr.status === 422) {
        //         let errors = xhr.responseJSON.errors;

        //         Object.keys(errors).forEach(function(key) {
        //             // key = "startpoint.0"
        //             let parts = key.split(".");
        //             let field = parts[0];  // startpoint
        //             let index = parts[1];  // 0
        //             let message = errors[key][0];

        //             // Show error under correct TD <span>
        //             $(`.error-${field}-${index}`).text(message);
        //               if (index === undefined) {
        //                 $(`.${field}_err`).text(message);
        //                 return;
        //             }
        //         });

                

        //         $("#addSubmit").prop('disabled', false);
        //     }
        // },

        error: function(xhr) {
    if (xhr.status === 422) {
        let errors = xhr.responseJSON.errors;

        let hasStartDateError = false;
        let hasEndDateError = false;

        Object.keys(errors).forEach(function(key) {

            if (key === "start_date") hasStartDateError = true;
            if (key === "end_date") hasEndDateError = true;

            let parts = key.split(".");
            let field = parts[0];
            let index = parts[1];
            let message = errors[key][0];

            if (index === undefined) {
                $(`.${field}_err`).text(message);
                return;
            }

            $(`.error-${field}-${index}`).text(message);
        });

        /** 🔥 Scroll Priority:
         * 1) start_date
         * 2) end_date
         */
        if (hasStartDateError) {
            $('html, body').animate({
                scrollTop: $('#start_date').offset().top - 100
            }, 300);
        } 
        else if (hasEndDateError) {
            $('html, body').animate({
                scrollTop: $('#end_date').offset().top - 100
            }, 300);
        }

        $("#addSubmit").prop('disabled', false);
    }
},


        
        

        complete: function() {
            $('#preloader').css({ opacity: '0', visibility: 'hidden' });
        }
    });

});
</script> --}}

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

    var formdata = new FormData(this);
    formdata.append("_method", "PUT");

    // 🔥 Ensure start_date & end_date always go into FormData
    formdata.set("start_date", $("#start_date").val() || "");
    formdata.set("end_date", $("#end_date").val() || "");

    $.ajax({
        url: "{{ route('grant-telecome.update', $grantingTelecom->id) }}",
        type: "POST",
        data: formdata,
        contentType: false,
        processData: false,

        beforeSend: function () {
            $("#preloader").css({ opacity: "0.5", visibility: "visible" });
            $("span.text-danger").text(""); // clear old errors
        },

        success: function (response) {

            Swal.fire({
                icon: "success",
                title: "Updated Successfully!",
                text: response.message || "Data updated.",
            }).then(() => {
                window.location.href = "{{ route('pendinglist') }}";
            });
        },

        error: function (xhr) {
            if (xhr.status === 422) {

                let errors = xhr.responseJSON.errors;
                let scrollToField = null;

                Object.keys(errors).forEach(function (key) {
                    let msg = errors[key][0];

                    // For indexed dynamic fields
                    let parts = key.split(".");
                    let field = parts[0];
                    let index = parts[1];

                    if (index !== undefined) {
                        $(`.error-${field}-${index}`).text(msg);

                        if (!scrollToField) {
                            scrollToField = $(`[name="${field}[${index}]"]`);
                        }
                    } else {
                        // normal field
                        $(`.${field}_err`).text(msg);

                        if (!scrollToField) {
                            scrollToField = $(`[name="${field}"]`);
                        }
                    }
                });

                // scroll to first error field
                if (scrollToField?.length) {
                    $("html, body").animate(
                        { scrollTop: scrollToField.offset().top - 100 },
                        300
                    );
                }

                $("#addSubmit").prop("disabled", false);
            } else {
                $("#addSubmit").prop("disabled", false);
                Swal.fire("Error!", "Something went wrong.", "error");
            }
        },

        complete: function () {
            $("#preloader").css({ opacity: "0", 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'
                });
            }
        });
    });


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

@if (((Auth::check() && Auth::user()->hasRole('Clerk')) || Auth::user()->hasRole('JuniorEngineer')) 
    && $status->service_id == '2032')

<script>
$(document).ready(function () {
    $(document).on("change input", 
        "select[name='road_cutting_purpose'], \
         select[name='ward_area'], \
         select[name='roadtype[]'], \
         input[name='startpoint[]'], \
         input[name='endpoint[]'], \
         input[name='start_date'], \
         input[name='end_date'], \
         input[name='road_length[]'], \
         select[name='defect_factor[]']",
        function () {
            $(".approveBtn").prop("disabled", true);
        }
    );

});
</script>
@endif


<!--start date and end date script back dated script-->
{{-- <script>
document.addEventListener('DOMContentLoaded', function() {
    const startInput = document.getElementById('start_date');
    const endInput = document.getElementById('end_date');

    // Disable past dates for start date
    const today = new Date().toISOString().split('T')[0];
    startInput.setAttribute('min', today);

    // If start date already has value, set end date min accordingly
    if(startInput.value) {
        endInput.setAttribute('min', startInput.value);
    } else {
        endInput.setAttribute('min', today);
    }

    // Update end date min whenever start date changes
    startInput.addEventListener('change', function() {
        const startDate = this.value;
        endInput.value = startDate; // Optional: set end date default same as start date
        endInput.setAttribute('min', startDate);
    });
});
</script> --}}


<script>
    $(document).ready(function() {
    $('.revertBtn').on('click', function () {

        let id = $(this).data('id');
        let statusId = $(this).data('status-id'); // optional

        Swal.fire({
            title: "Are you sure?",
            text: "Do you really want to revert this file?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes, Revert",
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: "{{ route('file.revert.backgranting') }}",
                    type: "POST",
                    data: {
                        _token: "{{ csrf_token() }}",
                        id: id,
                        status_id: statusId
                    },
                    success: function (response) {
                        Swal.fire({
                            icon: "success",
                            title: "Success!",
                            text: response.message,
                        }).then(() => {
                            location.reload();
                        });
                    },
                    error: function (xhr) {
                        Swal.fire({
                            icon: "error",
                            title: "Error!",
                            text: xhr.responseJSON?.message || "Something went wrong!"
                        });
                    }
                });
            }
        });
    });
});
</script>



