<x-admin.layout>
    <x-slot name="title">Road Cutting Permission / रस्ते खोदणे परवानगी </x-slot>
    <x-slot name="heading">Road Cutting Permission / रस्ते खोदणे परवानगी </x-slot>

  
{{-- @php
$payStatus = $paydata
    ->where('service_id', $data->service_id)
    ->where('table_id', $data->id)
    ->value('status');

$restrictRoles = [
    'Clerk',
    'JuniorEngineer',
    'DeputyEngineer',
    'ExecutiveEngineer'
];

$hasRestrictedRole = Auth::check() && Auth::user()->hasAnyRole($restrictRoles);

$disableForZeroPayment = ($payStatus == 0 && Auth::user()->hasAnyRole(['DeputyEngineer', 'ExecutiveEngineer']));

$disableField = (($payStatus == 1 && $hasRestrictedRole) || $disableForZeroPayment)
                ? 'readonly' 
                : '';

$hideDeleteBtn = ($payStatus == 1 || $status->receipt_status == 1 && $hasRestrictedRole);
$allowAddRow = !(($payStatus == 1 || $status->receipt_status == 1 && $hasRestrictedRole) || $disableForZeroPayment);

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

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;
    }
}

if (Auth::check() && Auth::user()->hasRole('JuniorEngineer')) {

    if (empty($data->upload_photo)) {
        $approve_require_fields = false;
    }
}
@endphp --}}

@php

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


$restrictRoles = [
    'Clerk',
    'JuniorEngineer',
    'DeputyEngineer',
    'ExecutiveEngineer'
];

$hasRestrictedRole = Auth::check() && Auth::user()->hasAnyRole($restrictRoles);


$disableForZeroPayment =
    ($payStatus == 0 && Auth::user()->hasAnyRole(['DeputyEngineer', 'ExecutiveEngineer']));


// $disableField =
//     (
//         ($payStatus == 1 || $status->receipt_status == 1)  && $hasRestrictedRole                                 
//     )
//     || $disableForZeroPayment
//         ? 'readonly'
//         : '';

$disableField = (
        (($payStatus == 1) || ($status->receipt_status == 1)) 
        && $hasRestrictedRole
    )
    || ($disableForZeroPayment)
    ? 'readonly'
    : '';

        


$hideDeleteBtn =
    (
        ($payStatus == 1 || $status->receipt_status == 1)
        && $hasRestrictedRole
    );


$allowAddRow =
    !(
        ($payStatus == 1 || $status->receipt_status == 1)
        && $hasRestrictedRole
    ) &&
    !$disableForZeroPayment;


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


$approve_require_fields = true;


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;
    }
}

// for JE → upload photo required
if (Auth::check() && Auth::user()->hasRole('JuniorEngineer')) {
    if (empty($data->upload_photo)) {
        $approve_require_fields = false;
    }
}
@endphp









        <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 Road Cutting Permission / रस्ते खोदणे परवानगी </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 mb-2">
                                <label class="col-form-label" for="applicant_type">Applicant Type ( Indivisual/Company)
                                    / अर्ज प्रकार (वैयक्तिक / कंपनी) <span class="text-danger">*</span></label>
                                <input class="form-control" id="applicant_type" name="applicant_type" type="text"
                                    placeholder="Enter Applicant Type" value="{{ $data->applicant_type }}" readonly>
                                <span class="text-danger is-invalid applicant_type_err"></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="applicant_name">Applicant's Full Name / अर्जदाराचे
                                    संपूर्ण नाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="applicant_name" name="applicant_name" type="text"
                                    pattern="^[A-Za-zअ-हऀ-ॿ\s]+$"
                                    title="Only letters and spaces are allowed. No numbers or special characters."
                                    onkeypress="return isLetterOrSpace(event)" placeholder="Enter Applicant Name"
                                    value="{{ $data->applicant_name }}" readonly>
                                <span class="text-danger is-invalid applicant_name_err"></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="applicant_full_address">Applicant's Full Address /
                                    अर्जदाराचा संपूर्ण पत्ता <span class="text-danger">*</span></label>
                                <textarea class="form-control" name="applicant_full_address" id="applicant_full_address"
                                    cols="30" rows="2" placeholder="Enter Applicant Address"
                                    readonly>{{ $data->applicant_full_address }}</textarea>
                                <span class="text-danger is-invalid applicant_full_address_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" readonly  @if($disableField) style="pointer-events:none; background:#e9ecef;" @endif> --}}
                                    <select name="ward_area" id="ward_area" class="form-select" {{ $disableField }}
                                  @if($disableField) style="pointer-events:none; background:#e9ecef;" @endif>
                                    <option value="">Select Ward</option>
                                    @foreach ($options as $option)
                                        <option {{ $data->ward_area == $option->id ? 'selected' : '' }}
                                            value="{{ $option->id }}">{{ $option->name }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid ward_area_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" required {{ $disableField }}>
                                    <option value="">Select Ward</option>
                                    @foreach ($options as $option)
                                        <option value="{{ $option->id }}">{{ $option->name }}</option>
                                    @endforeach
                                </select>

                                <span class="text-danger is-invalid ward_area_err"></span>
                                <div class="selected-value d-none" id="ward_area"></div>
                            </div> --}}
                            
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="company_name">Name of Company / कंपनीचे नाव</label>
                                <input class="form-control" id="company_name" name="company_name" type="text"
                                    placeholder="Enter Company Name" value="{{$data->company_name }}" readonly>
                                <span class="text-danger is-invalid company_name_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="designation">Designation / पद</label>
                                <input class="form-control" id="designation" name="designation" type="text"
                                    placeholder="Enter Designation" value="{{$data->designation }}" readonly>
                                <span class="text-danger is-invalid designation_err"></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <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" maxlength="10"
                                    oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 10);" type="number"
                                    placeholder="Enter Mobile Number" value="{{ $data->mobile_no }}" readonly>
                                <span class="text-danger is-invalid mobile_no_err"></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="aadhar_no">Aadhar Number / आधार क्रमांक </label>
                                <input class="form-control" id="aadhar_no" name="aadhar_no" type="number"
                                    onkeypress="return isNumberKey(event)" oninput="limitAadharLength(this)"
                                    placeholder="Enter Aadhar Card No" value="{{ $data->aadhar_no }}" readonly>
                                <span class="text-danger is-invalid aadhar_no_err"></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="email_id">Email ID / ई-मेल आयडी<span
                                        class="text-danger">*</span></label>
                                <input class="form-control" id="email_id" name="email_id" type="email"
                                    placeholder="Enter Email" value="{{ $data->email_id }}" readonly>
                                <span class="text-danger is-invalid email_id_err"></span>
                            </div>
                            {{-- <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 {{ $data->road_cutting_purpose == 'Faults' ? 'selected' : '' }}
                                        value="Faults">Faults</option>
                                    <option {{ $data->road_cutting_purpose == 'Cable Shifting' ? 'selected' : '' }}
                                        value="Cable Shifting">Cable Shifting</option>
                                    <option {{ $data->road_cutting_purpose == 'New Connection' ? 'selected' : '' }}
                                        value="New Connection">New Connection</option>
                                    <option {{ $data->road_cutting_purpose == 'Optical Fibre' ? 'selected' : '' }}
                                        value="Optical Fibre">Optical Fibre</option>
                                    <option {{ $data->road_cutting_purpose == 'New Cable Laying' ? 'selected' : '' }}
                                        value="New Cable Laying">New Cable Laying</option>
                                    <option {{ $data->road_cutting_purpose == 'Gas pipeline connection' ? 'selected' : '' }} value="Gas pipeline connection">Gas pipeline connection</option>
                                    <option {{ $data->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> --}}
                            <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" class="form-select" {{ $disableField }}
    @if($disableField) style="pointer-events:none; background:#e9ecef;" @endif>

                                    <option value="">Select Road Purpose</option>
                                    <option value="Faults" {{ $data->road_cutting_purpose == 'Faults' ? 'selected' : '' }}>Faults</option>
                                    <option value="Cable Shifting" {{ $data->road_cutting_purpose == 'Cable Shifting' ? 'selected' : '' }}>Cable Shifting</option>
                                    <option value="New Connection" {{ $data->road_cutting_purpose == 'New Connection' ? 'selected' : '' }}>New Connection</option>
                                    <option value="Optical Fibre" {{ $data->road_cutting_purpose == 'Optical Fibre' ? 'selected' : '' }}>Optical Fibre</option>
                                    <option value="New Cable Laying" {{ $data->road_cutting_purpose == 'New Cable Laying' ? 'selected' : '' }}>New Cable Laying</option>
                                    <option value="Gas pipeline connection" {{ $data->road_cutting_purpose == 'Gas pipeline connection' ? 'selected' : '' }}>Gas pipeline connection</option>
                                    <option value="any other" {{ $data->road_cutting_purpose == 'any other' ? 'selected' : '' }}>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>


                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="road_cutting_address">Address of the Road for cutting
                                    / रस्ता खोदण्याच्या ठिकाणाचा पत्ता <span class="text-danger">*</span></label>
                                <input class="form-control" id="road_cutting_address" name="road_cutting_address"
                                    type="text" placeholder="Enter road cutting address "
                                    value="{{ $data->road_cutting_address }}" readonly>
                                <span class="text-danger is-invalid road_cutting_address_err"></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="location_size">Size in MM for each location / आकार
                                    (मी.मी) मध्ये </label>
                                <input class="form-control" id="location_size" name="location_size" type="number"
                                    placeholder="Enter Size in MM for each location" value="{{ $data->location_size }}"
                                    readonly>
                                <span class="text-danger is-invalid location_size_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>
                                {{-- <input class="form-control" id="upload_prescribed_formats"
                                    name="upload_prescribed_formats" type="file" readonly> --}}
                                <small><a href="{{ asset('storage/' . $data->upload_prescribed_format) }}"
                                        target="_blank">View Document</a></small>
                                <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="upload_gov_instructed_docs">Upload Map / नकाशा<span
                                        class="text-danger">*</span></label>
                                {{-- <input class="form-control" id="upload_gov_instructed_docs"
                                    name="upload_gov_instructed_docs" type="file" readonly> --}}
                                <small><a href="{{ asset('storage/' . $data->upload_gov_instructed_doc) }}"
                                        target="_blank">View Document</a></small>
                                <span class="text-danger is-invalid upload_gov_instructed_docs_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="upload_related_docs">Related Documents / संबंधित दस्तऐवज <span
                                        class="text-danger">*</span></label>
                                {{-- <input class="form-control" id="upload_gov_instructed_docs"
                                    name="upload_gov_instructed_docs" type="file" readonly> --}}
                                <small><a href="{{ asset('storage/' . $data->upload_related_doc) }}"
                                        target="_blank">View Document</a></small>
                                <span class="text-danger is-invalid upload_related_docs_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="upload_gps_docs">GPS Photo / जीपीएस फोटो <span
                                        class="text-danger">*</span></label>
                                {{-- <input class="form-control" id="upload_gov_instructed_docs"
                                    name="upload_gov_instructed_docs" type="file" readonly> --}}
                                <small><a href="{{ asset('storage/' . $data->upload_gps_doc) }}" target="_blank">View
                                        Document</a></small>
                                <span class="text-danger is-invalid upload_gps_docs_err"></span>
                            </div>
                        </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 class="form-select" name="roadtype[]"
                        @if($disableField) style="pointer-events:none; background:#eee;" @endif>
                        <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>
                      
                {{-- <input type="hidden" name="roadtype[]" value="{{ $item->roadtype }}"> --}}
                  <span class="text-danger error-roadtype-{{ $loop->index }}">
                                                @error("roadtype.$loop->index") {{ $message }} @enderror
                                            </span>
            </td>


               {{-- <td>
                <input type="text" name="startpoint[]" class="form-control"
                    value="{{ $item->startpoint }}" 
                    placeholder="Enter Start Point" {{ $disableField }}>
                    <span class="text-danger error-startpoint-{{ $loop->index }}">
                                            @error("startpoint.$loop->index") {{ $message }} @enderror
                                        </span>
            </td> --}}
            <td>
    <input type="text" 
           name="startpoint[]" 
           class="form-control"
           value="{{ $item->startpoint }}" 
           {{ $disableField }}
           @if($disableField) style="pointer-events:none; background:#e9ecef;" @endif
           placeholder="Enter Start Point">
           
    <span class="text-danger error-startpoint-{{ $loop->index }}">
        @error("startpoint.$loop->index") {{ $message }} @enderror
    </span>
</td>


                <td>
                    <input type="text" name="endpoint[]" class="form-control"
                        value="{{ $item->endpoint }}" 
                        placeholder="Enter End Point" {{ $disableField }}>
                          <span class="text-danger error-endpoint-{{ $loop->index }}">
                                                    @error("endpoint.$loop->index") {{ $message }} @enderror
                                                </span>
                </td>

               <td>
                    <input type="number" name="road_length[]" class="form-control"
                        value="{{ $item->length }}" 
                        placeholder="Enter Length" {{ $disableField }}>
                         <span class="text-danger error-road_length-{{ $loop->index }}">
                                                @error("road_length.$loop->index") {{ $message }} @enderror
                                            </span>
                </td>

                <td>
                    <select name="defect_factor[]" class="form-select" 
                    @if($disableField) style="pointer-events:none; background:#eee;" @endif>
                        <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>
                    @if (!$hideDeleteBtn)
                        <button type="button" class="btn btn-danger removeRow">Delete</button>
                    @else
                        <span class="text-muted">Locked</span>
                    @endif
                </td>

            </tr>
        @endforeach
    </tbody>
</table>


                        <button type="button" class="btn btn-primary" id="addmore" style="width: 10%;">Add More</button>
                        <div class="row">
                            <div class="col-md-3 mb-2">
                                <label class="col-form-label" for="no_of_location">Name of Locations / ठिकाणांची
                                    नावे<span class="text-danger">*</span></label>
                                {{-- <input class="form-control" id="no_of_location" name="no_of_location" type="text"
                                    placeholder="Enter Number of Locations" value="{{ $data->no_of_location }}"  @if($disableField) style="pointer-events:none; background:#e9ecef;" @endif> --}}
                                    <input type="text" name="no_of_location" class="form-control"
    value="{{ $data->no_of_location }}" {{ $disableField }}
    @if($disableField) style="pointer-events:none; background:#e9ecef;" @endif>
                                <span class="text-danger is-invalid no_of_location_err"></span>
                            </div>
                            <div class="col-md-3 mb-2">
                                <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"
                                    placeholder="Enter Number Of Duct" value="{{ $data->no_duct }}"  @if($disableField) style="pointer-events:none; background:#e9ecef;" @endif>
                                <span class="text-danger is-invalid no_duct_err"></span>
                            </div>
                            <div class="col-md-3 mb-2">
                                <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"
                                    placeholder="Enter Number Of Chamber" value="{{ $data->no_chamber }}"  @if($disableField) style="pointer-events:none; background:#e9ecef;" @endif>
                                <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($data->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/' . $data->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 == '187')
                            <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($data) && isset($data->start_date) ? $data->start_date : '' }}">
                            </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($data) && isset($data->end_date) ? $data->end_date : '' }}">
                            </div>
                            @endif --}}


                          
<script>
    let allowAddRow = {{ $allowAddRow ? 'true' : 'false' }};
</script>





                            @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="{{ $data->start_date ?? '' }}"
                                            {{ $isClerk ? '' : '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="{{ $data->end_date ?? '' }}"
                                            {{ $isClerk ? '' : 'disabled' }}   
                                        >
                                         <span class="text-danger is-invalid end_date_err"></span>
                                    </div>

                                @endif
                            @endif

                         


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

                            @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> {{ $approval->approver->name }}</p>
                                                @else
                                                @endif

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



                        </div>
                    </div>

                    
                </div>
                <div class="card-footer">
                    
                       

                    {{-- @if(Auth::user()->hasRole('ExecutiveEngineer') && $data->is_startdate_enddate == 1)
                        <a href="{{ route('construction-road-cutting.certificateone', encrypt($data->id)) }}" 
                        class="btn btn-primary" target="_blank">
                            Generate Certificate
                        </a>
                        <button type="button" 
                                class="btn btn-warning revertBtn"
                                data-id="{{ $approval->id }}"
                                data-status-id="{{ $approval->status_id }}">
                            Revert Back
                        </button> --}}
                        @if(Auth::user()->hasRole('ExecutiveEngineer') && $data->is_startdate_enddate == 1)
    <a href="{{ route('construction-road-cutting.certificateone', encrypt($data->id)) }}" 
       class="btn btn-primary {{ $data->is_generated == 1 ? 'disabled' : '' }}" 
       target="_blank" 
       {{ $data->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 }}"
            {{ $data->is_generated == 1 ? 'disabled' : '' }}>
        Revert Back
    </button>


                    

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

    
    
    <button type="button"
        class="btn btn-success approveBtn"
        data-id="{{ $status->id }}"
        {{ ($payStatus == 1 && $status->receipt_status == 1  && $data->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 == '187')
                        <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" required>
                            <option value="">Select Road Type</option>
                            @foreach ($roadtype as $option)
                                <option value="{{ $option->id }}">{{ $option->road_type }}</option>
                            @endforeach
                        </select>
                    </td>
                    <td>
                        <input type="text" name="startpoint[]" class="form-control" placeholder="Enter Start Point" required>
                    </td>
                    <td>
                        <input type="text" name="endpoint[]" class="form-control" placeholder="Enter End Point" required>
                    </td>
                    <td>
                        <input type="number" name="road_length[]" class="form-control" placeholder="Enter Length" required>
                    </td>
                    <td>
                        <select name="defect_factor[]" class="form-select" required>
                            <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 () {

            if (!allowAddRow) {
                alert("You cannot add more rows after payment.");
                return false;
            }

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

           const newRow = `
                    <tr>
                        <td>
                            <select class="form-select" name="roadtype[]"
                                @if($disableField) style="pointer-events:none; background:#eee;" @endif>
                                <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" {{ $disableField }}>
                             <span class="text-danger error-startpoint-${index}"></span>
                            </td>
                        <td><input type="text" name="endpoint[]" class="form-control" {{ $disableField }}>
                             <span class="text-danger error-endpoint-${index}"></span>
                            </td>
                        <td><input type="number" name="road_length[]" class="form-control" {{ $disableField }}>
                            <span class="text-danger error-road_length-${index}"></span>
                            </td>

                        <td>
                            <select name="defect_factor[]" class="form-select" 
                            @if($disableField) style="pointer-events:none; background:#eee;" @endif>
                                <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>
                            @if (!$hideDeleteBtn)
                                <button type="button" class="btn btn-danger removeRow">Delete</button>
                            @else
                                <span class="text-muted">Locked</span>
                            @endif
                        </td>
                    </tr>
                    `;


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

        // Delete Row
        $('#roadTable').on('click', '.removeRow', function () {

            if (!allowAddRow) {
                alert("You cannot delete rows after payment.");
                return false;
            }

            $(this).closest('tr').remove();
        });

    });
</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('construction-road-cutting.update', $data->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) {
    //             if (response.status) {
    //                 Swal.fire({
    //                     icon: 'success',
    //                     title: 'Updated Successfully!',
    //                     text: response.message ?? 'Operation completed successfully.',
    //                     confirmButtonText: 'OK'
    //                 }).then(() => {
    //                     window.location.href = response.redirect_url ?? '{{ route('pendinglist') }}';
    //                 });
    //             } 
               
    //             else {
    //                 // Backend returned status false with a message
    //                 Swal.fire({
    //                     icon: 'error',
    //                     title: 'Update Failed!',
    //                     text: response.message ?? 'Something went wrong!',
    //                     confirmButtonText: 'OK'
    //                 });
    //             }
    //         },
    //         complete: function () {
    //             $('#preloader').css('opacity', '0');
    //             $('#preloader').css('visibility', 'hidden');
    //             $("#addSubmit").prop('disabled', false);
    //         },
    //     });

    // });

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

//     var formdata = new FormData(this);
//     var updateUrl = '{{ route('construction-road-cutting.update', $data->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) {

//             console.log("FULL RESPONSE:", response);  // 👈 REAL DATA FROM SERVER

//             if (response.status) {
//                 Swal.fire({
//                     icon: 'success',
//                     title: 'Updated Successfully!',
//                     text: response.message ?? 'Operation completed successfully.',
//                     confirmButtonText: 'OK'
//                 }).then(() => {
//                     window.location.href = response.redirect_url ?? '{{ route('pendinglist') }}';
//                 });
//             } else 
            
//             {

//                 console.error("SERVER ERROR:", response.error);  // 👈 ACTUAL LARAVEL ERROR

//                 Swal.fire({
//                     icon: 'error',
//                     title: 'Update Failed!',
//                     text: response.message ?? 'Something went wrong!',
//                     confirmButtonText: 'OK'
//                 });
//             }
//         },

//         error: function (xhr) {
//             console.error("AJAX ERROR:", xhr.responseText); // 👈 If API didn't respond properly
//         },

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


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

    var formdata = new FormData(this);
    var updateUrl = '{{ route('construction-road-cutting.update', $data->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) {

            console.log("FULL RESPONSE:", response);

            if (response.status) {
                Swal.fire({
                    icon: 'success',
                    title: 'Updated Successfully!',
                    text: response.message ?? 'Operation completed successfully.',
                    confirmButtonText: 'OK'
                }).then(() => {
                    window.location.href = response.redirect_url ?? '{{ route('pendinglist') }}';
                });

            } else {
                console.error("SERVER ERROR:", response.error);

                Swal.fire({
                    icon: 'error',
                    title: 'Update Failed!',
                    text: response.message ?? 'Something went wrong!',
                    confirmButtonText: 'OK'
                });
            }
        },

        // 🔥🔥 422 VALIDATION ERROR HANDLING ADDED HERE
        // error: function (xhr) {

        //     console.log("AJAX ERROR:", xhr.responseText);

        //     if (xhr.status === 422) {

        //         let errors = xhr.responseJSON.errors;

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

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

        //             // 🎯 CASE 1: Dynamic field with index (startpoint.0)
        //             if (index !== undefined) {
        //                 $(`.error-${field}-${index}`).text(message);
        //             }

        //             // 🎯 CASE 2: Normal field (startpoint)
        //             else {
        //                 $(`.${field}_err`).text(message);
        //             }

        //         });

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

        error: function (xhr) {

    console.log("AJAX ERROR:", xhr.responseText);

    if (xhr.status === 422) {

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

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

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

            // 🎯 CASE 1: Dynamic field with index (startpoint.0)
            if (index !== undefined) {
                $(`.error-${field}-${index}`).text(message);
                if (!firstErrorField) firstErrorField = $(`[name="${field}[${index}]"]`);
            }

            // 🎯 CASE 2: Normal field (startpoint)
            else {
                $(`.${field}_err`).text(message);
                if (!firstErrorField) firstErrorField = $(`[name="${field}"]`);
            }

        });

        // Scroll to the first error field
        if (firstErrorField && firstErrorField.length) {
            $('html, body').animate({
                scrollTop: firstErrorField.offset().top - 100  // offset for navbar if any
            }, 500);
        }

        $("#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'
                });
            }
        });
    });


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

<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.back') }}",
                    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>

<script>
    function isNumberKey(evt) {
        var charCode = evt.which ? evt.which : evt.keyCode;
        if (charCode < 48 || charCode > 57) {
            evt.preventDefault();
            return false;
        }
        return true;
    }

    function limitAadharLength(input) {
        if (input.value.length > 12) {
            input.value = input.value.slice(0, 12);
        }
    }
</script>

<script>
    function isLetterOrSpace(e) {
        const char = String.fromCharCode(e.which || e.keyCode);
        const regex = /^[A-Za-zअ-हऀ-ॿ\s]+$/;
        return regex.test(char);
    }
</script>



{{-- @if (((Auth::check() && Auth::user()->hasRole('Clerk')) || Auth::user()->hasRole('JuniorEngineer'))
    && $status->service_id == '187')
 
<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 --}}

@if (((Auth::check() && Auth::user()->hasRole('Clerk')) || Auth::user()->hasRole('JuniorEngineer'))
    && $status->service_id == '187')
<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[]'], \
         input[name='upload_photos']",  
        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>


















