<x-admin.layout>
    <x-slot name="title">New Water Connection / नविन नळजोडणी</x-slot>
    <x-slot name="heading">New Water Connection / नविन नळजोडणी</x-slot>
    {{-- Water Api changes   --}}

    <!-- Add Form -->
    <div class="row" id="addContainer">
        <div class="col-sm-12">
            <div class="card">
                {{-- <form class="theme-form" name="detailfetch" id="detailfetch" enctype="multipart/form-data">
                        @csrf
                         <div class="col-md-4">
                                <input class="form-control" id="marchantid" name="marchantid" type="hidden"  value="MBMCCORE">
                                <span class="text-danger is-invalid marchantid_err"></span>
                        </div>
                         <div class="col-md-4">
                                <label class="col-form-label" for="connno">Connection No<span class="text-danger">*</span></label>
                                <input class="form-control" id="connno" name="connno" type="text" placeholder="Enter Connection No">
                                <span class="text-danger is-invalid connno_err"></span>
                        </div>

                        <button type="Search" class="btn btn-primary mt-2" id="searchdetails">Search</button>
                    </form> --}}

                <form class="theme-form" name="addForm" id="addForm" enctype="multipart/form-data">
                    @csrf

                    <div class="card-header">
                        <h4 class="card-title">Add Details</h4>
                    </div>
                    <div class="card-body">
                        <div class="mb-3 row">

                            <div class="col-md-4">
                                <label class="col-form-label" for="applicant_full_name">Applicant Full Name / अर्जदाराचे संपूर्ण नाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="applicant_full_name" name="applicant_full_name" type="text" placeholder="Enter Applicant Full Name" >
                                <span class="text-danger is-invalid applicant_full_name_err"></span>
                            </div>

                           <div class="col-md-4">
    <label class="col-form-label" for="aadhar_no">Aadhar No / आधार नंबर <span class="text-danger">*</span></label>
    <input 
        class="form-control" 
        id="aadhar_no" 
        name="aadhar_no" 
        type="text" 
        placeholder="Enter Aadhar Card No" 
        maxlength="12"
        oninput="
            // Remove non-digits
            this.value = this.value.replace(/\D/g, '');
            // Limit to 12 digits
            if(this.value.length > 12) this.value = this.value.slice(0, 12);
        "
    >
    <span class="text-danger is-invalid aadhar_no_err"></span>
</div>


                            <div class="col-md-4">
                                <label class="col-form-label" for="mobile_no">Mobile Number / मोबाईल नंबर<span class="text-danger">*</span></label>
                                <input class="form-control" id="mobile_no" name="mobile_no"  oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 10);" maxlength="10" minlength="10" type="number" placeholder="Enter Mobile Number" >
                                <span class="text-danger is-invalid mobile_no_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="email_id">Email ID / ई-मेल आयडी</label>
                                <input class="form-control" id="email_id" name="email_id" type="email" placeholder="Enter Email">
                                <span class="text-danger is-invalid email_id_err"></span>
                            </div>


                            {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="zone">Zone / झोन<span class="text-danger">*</span></label>
                                    <select class="form-select" name="zone" id="zone" required>
                                        <option value="">Select Zone</option>

                                        @foreach ($zones as $zone)
                                        <option value="{{ $zone->name }}">{{ $zone->name }}</option>
                                        @endforeach
                                    </select>
                                    <span class="text-danger is-invalid zone_err"></span>
                                </div> --}}
                            {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="ward_area">Ward Area / प्रभाग क्षेत्र<span class="text-danger">*</span></label>
                                    <select class="form-select" name="ward_area" id="ward_area" required>
                                        <option value="">Select Ward Area</option>

                                        @foreach ($wards as $ward)
                                        <option value="{{ $ward->name }}">{{ $ward->name }}</option>
                                        @endforeach
                                    </select>
                                    <span class="text-danger is-invalid ward_area_err"></span>
                                </div> --}}

                            {{-- <div class="col-md-4">
                                <label class="col-form-label" for="city_servey_no">City Survey Number / सिटी सर्व्हे क्र.<span class="text-danger">*</span></label>
                                <input class="form-control" id="city_servey_no" name="city_servey_no" type="text" placeholder="Enter City Survey Number" required>
                                <span class="text-danger is-invalid city_servey_no_err"></span>
                            </div> --}}

                            <div class="col-md-4">
                                <label class="col-form-label" for="address">Applicant Full Address / अर्जदाराचा संपूर्ण पत्ता <span class="text-danger">*</span></label>
                                <textarea class="form-control" name="address" id="address" cols="30" rows="2" placeholder="Enter  Address" ></textarea>
                                <span class="text-danger is-invalid address_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="landmark">Landmark / हद्द खूण</label>
                                <input class="form-control" id="landmark" name="landmark" type="text" placeholder="Enter Landmark">
                                <span class="text-danger is-invalid landmark_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="no_of_flats_shops">Number of Flats / Shops. / फ्लॅट्स / दुकानांची संख्या.<span class="text-danger">*</span></label>
                                <input class="form-control" id="no_of_flats_shops" name="no_of_flats_shops" type="text" placeholder="Enter Number of Flats / Shops" >
                                <span class="text-danger is-invalid no_of_flats_shops_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="property_no">Property Number / मालमत्ता क्र.<span class="text-danger">*</span></label>
                                <input class="form-control" id="property_no" name="property_no" type="text" placeholder="Enter Property Number" >
                                <span class="text-danger is-invalid property_no_err"></span>
                            </div>

                            {{-- <div class="col-md-4">
                                <label class="col-form-label" for="total_person">Total Person / एकूण व्यक्ती<span class="text-danger">*</span></label>
                                <input class="form-control" id="total_person" name="total_person" type="number" placeholder="Enter Total Person" required>
                                <span class="text-danger is-invalid total_person_err"></span>
                            </div> --}}

                            {{-- <div class="col-md-4">
                                <label class="col-form-label" for="distance">Distance / अंतर<span class="text-danger">*</span></label>
                                <input class="form-control" id="distance" name="distance" type="text" placeholder="Enter Distance" required>
                                <span class="text-danger is-invalid distance_err"></span>
                            </div> --}}

                            {{-- <div class="col-md-4">
                                <label class="col-form-label" for="water_connection_use">Usage Of Water Connection / पाणी कनेक्शनचा वापर<span class="text-danger">*</span></label>
                                <select class="form-select" name="water_connection_use" id="water_connection_use" required>
                                    <option value="">Select option</option>
                                    @php
                                        $options = ['अनिवासी व्यवसाय', 'औद्योगीक', 'निवासी', 'विशेष प्रवर्ग (शैक्षणिक संस्था,शासकीय,निमशासकीय कार्यालय,पथसंस्था,इतर)', 'व्यावसायिक अथवा वाणिज्य'];
                                    @endphp
                                    @foreach ($options as $option)
                                        <option value="{{ $option }}">{{ $option }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid water_connection_use_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="water_connection_sub_use">Sub usage Of Water Connection / पाणी कनेक्शनचा उप-वापर</label>
                                <select class="form-select" name="water_connection_sub_use" id="water_connection_sub_use">
                                    <option value="">Select option</option>
                                </select>
                                <span class="text-danger is-invalid water_connection_sub_use_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="pipe_size">Pipe Size / पाईपचा आकार <span class="text-danger">*</span></label>
                                

                                <select class="form-select" name="pipe_size" id="pipe_size" required>
                                    <option value="">Select option</option>
                                    @php
                                        $options = ['1/2', '1']; // sirf 1/2 inch aur 1 inch
                                    @endphp
                                    @foreach ($options as $option)
                                        <option value="{{ $option }}">{{ $option }} inch</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid pipe_size_err"></span>
                            </div> --}}


                            <div class="col-md-4">
    <label class="col-form-label" for="water_connection_use">Usage Of Water Connection / पाणी कनेक्शनचा वापर<span class="text-danger">*</span></label>
    <select class="form-select" name="water_connection_use" id="water_connection_use" >
        <option value="">Select option</option>
        @php
            $options = [
                'अनिवासी व्यवसाय',
                'औद्योगीक',
                'निवासी',
                'विशेष प्रवर्ग (शैक्षणिक संस्था,शासकीय,निमशासकीय कार्यालय,पथसंस्था,इतर)',
                'व्यावसायिक अथवा वाणिज्य'
            ];
        @endphp
        @foreach ($options as $option)
            <option value="{{ $option }}">{{ $option }}</option>
        @endforeach
    </select>
    <span class="text-danger is-invalid water_connection_use_err"></span>
</div>

<!-- Sub Usage -->
<div class="col-md-4">
    <label class="col-form-label" for="water_connection_sub_use">Sub usage Of Water Connection / पाणी कनेक्शनचा उप-वापर</label>
    <select class="form-select" name="water_connection_sub_use" id="water_connection_sub_use">
        <option value="">Select option</option>
    </select>
    <span class="text-danger is-invalid water_connection_sub_use_err"></span>
</div>

<!-- Pipe Size -->
<div class="col-md-4">
    <label class="col-form-label" for="pipe_size">Pipe Size / पाईपचा आकार <span class="text-danger">*</span></label>
    <select class="form-select" name="pipe_size" id="pipe_size" >
        <option value="">Select option</option>
    </select>
    <span class="text-danger is-invalid pipe_size_err"></span>
</div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="no_of_tap">Required No Of Tap Connection / नळजोडणी ची आवश्यक संख्या <span class="text-danger">*</span></label>
                                <input class="form-control" type="number" name="no_of_tap" id="no_of_tap" placeholder="Enter Required No Of Tap Connection" >
                                <span class="text-danger is-invalid no_of_tap_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="current_no_of_tap">Number Of Existing Tap Connections / नळजोडणी सध्याची एकूण संख्या <span class="text-danger">*</span></label>
                                <input class="form-control" type="number" name="current_no_of_tap" id="current_no_of_tap" placeholder="EnterNumber Of Existing Tap Connections" >
                                <span class="text-danger is-invalid current_no_of_tap_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="prabhag">Prabhag / प्रभाग <span class="text-danger">*</span></label>
                                <select class="form-select" name="prabhag" id="prabhag" >
                                    <option value="">Select option</option>
                                    @foreach ($prabhags as $prabhag)
                                        <option value="{{ $prabhag->id }}">{{ $prabhag->name }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid prabhag_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="wards">ward / वॉर्ड <span class="text-danger">*</span></label>
                                <select class="form-select" name="wards" id="wards" >
                                    <option value="">Select option</option>
                                </select>
                                <span class="text-danger is-invalid wards_err"></span>
                            </div>

                            {{-- <div class="col-md-4">
                                <label class="col-form-label" for="total_tenants">Total Tenants / एकूण भाडेकरू<span class="text-danger">*</span></label>
                                <input class="form-control" id="total_tenants" name="total_tenants" type="number" placeholder="Enter Total Tenants" required>
                                <span class="text-danger is-invalid total_tenants_err"></span>
                            </div> --}}

                            <div class="col-md-4">
                                <label class="col-form-label" for="water_connection_no">Existing Water Connection No / पूर्वीचा पाणी कनेक्शन क्र<span class="text-danger"></span></label>
                                <input class="form-control" id="water_connection_no" name="water_connection_no" type="text" placeholder="CNNP01B0000001">
                                <span class="text-danger is-invalid water_connection_no_err"></span>
                            </div>

                           

                            <div class="col-md-4">
                                <label class="col-form-label" for="address_proof">Electricity Bill / Aadhar Card/ Voter ID / Ration Card / वीज बिल / आधार कार्ड / मतदार ओळखपत्र / रेशन कार्ड <span class="text-danger">*</span></label>
                                <input class="form-control" id="address_proof" name="address_proof" type="file" >
                                <span class="text-danger is-invalid address_proof_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="ownership_document">Upload Land ownership documents / मालकी हक्काची कागदपत्रे अपलोड करा <span class="text-danger">*</span></label>
                                <input class="form-control" id="ownership_document" name="ownership_document" type="file" >
                                <span class="text-danger is-invalid ownership_document_err"></span>
                            </div>

                            {{-- <div class="col-md-4">
                                <label class="col-form-label" for="no_dues_document">Upload Certificate Of No Dues / थकबाकी नसल्याचा दाखला अपलोड करा <span class="text-danger">*</span></label>
                                <input class="form-control" id="no_dues_document" name="no_dues_document" type="file" required>
                                <span class="text-danger is-invalid no_dues_document_err"></span>
                            </div> --}}

                            <div class="col-md-4">
                                <label class="col-form-label" for="stamp_karnama">100Rs Stamp Kararnama / १०० रुपयांचा करनामा स्टॅम्प.<span class="text-danger">*</span></label>
                                <input class="form-control" id="stamp_karnama" name="stamp_karnama" type="file" >
                                <span class="text-danger is-invalid stamp_karnama_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="oc_and_cc">O/C and CC Certificate / bandkam praranbh patra / Bhogavata dakhala / O/C आणि CC प्रमाणपत्र / बांधकाम प्रारंभ पत्र / भोगवटा दाखला.</label>
                                <input class="form-control" id="oc_and_cc" name="oc_and_cc" type="file">
                                <span class="text-danger is-invalid oc_and_cc_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="structure_photo">Upload Structure Photo/ स्ट्रक्चर फोटो अपलोड करा<span class="text-danger">*</span></label>
                                <input class="form-control" id="structure_photo" name="structure_photo" type="file" >
                                <span class="text-danger is-invalid structure_photo_err"></span>
                            </div>

                            {{-- <div class="col-md-4">
                                <label class="col-form-label" for="jote_doc">Upload Tillage certificate / जोते प्रमाणपत्र अपलोड करा <span class="text-danger">*</span></label>
                                <input class="form-control" id="jote_doc" name="jote_doc" type="file" required>
                                <span class="text-danger is-invalid jote_doc_err"></span>
                            </div> --}}

                            {{-- <div class="col-md-6" id="upload_section" style="display:none;">
                                <label class="col-form-label" for="uploaded_applications">Upload Application In Prescribed Format / विहित नमुन्यातील अर्ज अपलोड करा <span class="text-danger">*</span></label>
                                <input class="form-control" id="uploaded_applications" name="uploaded_applications" type="file">
                                <span class="text-danger is-invalid uploaded_applications_err"></span>
                            </div> --}}


                             <div class="col-md-4" id="upload_section" style="display:none;">
                                <label class="col-form-label" for="written_application_document">Upload Application in the prescribed format / विहित नमून्यातील अर्ज<span class="text-danger">*</span></label>
                                <input class="form-control" id="written_application_document" name="written_application_document" type="file">
                                <span class="text-danger is-invalid written_application_document_err"></span>
                            </div>

                           <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" 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 d-block mt-1"></span>
</div>


                        </div>
                    </div>
                    <div class="form-group" style="text-align: center;">
                        <button type="button" id="saveAndPrintBtn" class="btn btn-success">Save and Print</button>
                    </div>
                    <div class="card-footer" id="card-footer" style="display:none;">
                        <button type="submit" class="btn btn-primary" id="addSubmit">Submit</button>
                        <button type="reset" class="btn btn-warning">Reset</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

</x-admin.layout>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

<!--<script>
    //   $('#searchdetails').on('click', function (e) {
    //     e.preventDefault();

    //     let formData = {
    //         marchantid: $('#marchantid').val(),
    //         connno: $('#connno').val(),
    //         _token: $('input[name="_token"]').val()
    //     };

    //     $.ajax({
    //         url: '{{ route('fetch.water.details') }}',
    //         method: 'POST',
    //         data: formData,
    //         success: function (response) {
    //             console.log("Encrypted Data:", response.jsonData.encr_request);
    //         },
    //         error: function (xhr) {
    //             console.error(xhr.responseText);
    //         }
    //     });
    // });
</script>-->

 {{-- <script>
    document.getElementById('saveAndPrintBtn').addEventListener('click', function() {
        const form = document.getElementById('addForm');
        if (form.checkValidity()) {
            document.getElementById('upload_section').style.display = 'block';
            document.getElementById('card-footer').style.display = 'block';
            html2canvas(form).then(canvas => {
                const imgData = canvas.toDataURL('image/png');
                const {
                    jsPDF
                } = window.jspdf;
                const pdf = new jsPDF('p', 'mm', 'a4');

                const title = "Water New Connection";
                pdf.setFont("helvetica", "bold");
                pdf.setFontSize(14);

                const pageWidth = pdf.internal.pageSize.getWidth();
                const margin = 10;
                const maxTextWidth = pageWidth - margin * 2;
                const lines = pdf.splitTextToSize(title, maxTextWidth);

                pdf.text(lines, margin, 15);

                const imgProps = pdf.getImageProperties(imgData);
                const pdfWidth = pageWidth;
                const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;

                pdf.addImage(imgData, 'PNG', 0, 30, pdfWidth, pdfHeight);
                pdf.save('Water New Connection.pdf');

                 document.getElementById('saveAndPrintBtn').style.display = 'none';
            });
        } else {
            form.reportValidity();
        }
    });

    
    const getWards = async function(id) {
        const wards = document.querySelector("#wards");
        wards.innerHTML = '<option value="">Select option</option>';
        const response = await fetch(`/get-water-wards-by-prabhag/${id}`);
        const data = await response.json();

        data.forEach(ward => {
            wards.insertAdjacentHTML('beforeend',`<option value="${ward.id}">${ward.ward_name}</option>`);
        });
    }

    document.querySelector('#prabhag').addEventListener('change', async (event) => {
        const id = event.target.value;
        await getWards(id)
    })



const usageEl = document.querySelector('#water_connection_use');
const subUsageEl = document.querySelector('#water_connection_sub_use');
const pipeSizeEl = document.querySelector('#pipe_size');


const subUsageMap = {
    'निवासी': ['इमारत', 'गावठाण स्वतंत्र घर', 'गट कनेक्शन', 'रो हाउस / बंगला'],
    'अनिवासी व्यवसाय': ['व्यवसाय 1', 'व्यवसाय 2'], 
    'औद्योगीक': ['इमारत'],
    'विशेष प्रवर्ग (शैक्षणिक संस्था,शासकीय,निमशासकीय कार्यालय,पथसंस्था,इतर)': ['इमारत'],
    'व्यावसायिक अथवा वाणिज्य': ['गट कनेक्शन', 'इमारत']
};


const pipeMap = {
    'इमारत': '1',
    'गावठाण स्वतंत्र घर': '1/2',
    'गट कनेक्शन': '1/2',
    'रो हाउस / बंगला': '1/2',
    'व्यवसाय 1': '1',
    'व्यवसाय 2': '1/2'
};

usageEl.addEventListener('change', function() {
    const selectedUsage = this.value;
    subUsageEl.innerHTML = '<option value="">Select option</option>';
    pipeSizeEl.innerHTML = '<option value="">Select option</option>'; // reset pipe size

    if(subUsageMap[selectedUsage]){
        subUsageMap[selectedUsage].forEach(function(sub){
            const opt = document.createElement('option');
            opt.value = sub;
            opt.text = sub;
            subUsageEl.appendChild(opt);
        });
    }
});


subUsageEl.addEventListener('change', function() {
    const selectedSub = this.value;
    pipeSizeEl.innerHTML = '<option value="">Select option</option>'; // reset first
    if(pipeMap[selectedSub]){
        const opt = document.createElement('option');
        opt.value = pipeMap[selectedSub];
        opt.text = pipeMap[selectedSub] + ' inch';
        opt.selected = true;
        pipeSizeEl.appendChild(opt);
    }
});

</script> --}}






{{-- <script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('addForm');
    const saveBtn = document.getElementById('saveAndPrintBtn');
    const uploadSection = document.getElementById('upload_section');
    const cardFooter = document.getElementById('card-footer');

    const messages = {
        applicant_full_name: 'Applicant Name is Required',
        aadhar_no: 'Aadhar No is Required',
        mobile_no: 'Mobile No is Required',
        email_id: 'Email is Required',
        address: 'Address is Required',
        no_of_flats_shops: 'No of Flats/Shops is Required',
        property_no: 'Property No is Required',
        water_connection_use: 'Water Connection Use is Required',
        pipe_size: 'Pipe Size is Required',
        no_of_tap: 'No of Tap is Required',
        current_no_of_tap: 'Current No of Tap is Required',
        prabhag: 'Prabhag is Required',
        wards: 'Wards is Required',
        stamp_karnama: 'Stamp Karnama is Required',
        structure_photo: 'Structure Photo is Required',
        address_proof: 'Address Proof is Required',
        ownership_document: 'Ownership Document is Required',
        is_correct_info: 'Please Accept the Declaration'
    };

    // 🧩 Show error
    function showError(el, message) {
        const oldMsg = el.nextElementSibling;
        if (oldMsg && oldMsg.classList.contains('error-msg')) oldMsg.remove();

        const errorEl = document.createElement('div');
        errorEl.classList.add('error-msg');
        errorEl.style.color = 'red';
        errorEl.style.fontSize = '0.9em';
        errorEl.textContent = message;

        el.style.border = '1px solid red';
        el.parentNode.insertBefore(errorEl, el.nextSibling);
    }

    // 🧹 Clear errors
    function clearErrors() {
        Object.keys(messages).forEach(id => {
            const el = document.getElementById(id);
            if (el) {
                el.style.border = '';
                const errorEl = el.nextElementSibling;
                if (errorEl && errorEl.classList.contains('error-msg')) {
                    errorEl.remove();
                }
            }
        });
    }

    // ✅ Checkbox error helpers
    function showCheckboxError(el, message) {
        const errorSpan = document.querySelector('.is_correct_info_err');
        if (errorSpan) errorSpan.textContent = message;
    }

    function clearCheckboxError() {
        const errorSpan = document.querySelector('.is_correct_info_err');
        if (errorSpan) errorSpan.textContent = '';
    }

    // 🖱️ Save & Print button event
    saveBtn.addEventListener('click', function(e) {
        e.preventDefault();
        clearErrors();
        clearCheckboxError();

        let isValid = true;
        let firstErrorEl = null;

        // 🔍 Validate fields
        Object.keys(messages).forEach(id => {
            const el = document.getElementById(id);
            if (el) {
                if (id === 'is_correct_info' && !el.checked) {
                    showCheckboxError(el, messages[id]);
                    if (!firstErrorEl) firstErrorEl = el;
                    isValid = false;
                } else if (id !== 'is_correct_info' && !el.value.trim()) {
                    showError(el, messages[id]);
                    if (!firstErrorEl) firstErrorEl = el;
                    isValid = false;
                }
            }
        });

        // 🔢 Aadhaar, Mobile, Email validations
        const aadhar = document.getElementById('aadhar_no').value.trim();
        const mobile = document.getElementById('mobile_no').value.trim();
        const email = document.getElementById('email_id').value.trim();

        if (aadhar && !/^\d{12}$/.test(aadhar)) {
            const el = document.getElementById('aadhar_no');
            showError(el, 'Aadhar number must be 12 digits.');
            if (!firstErrorEl) firstErrorEl = el;
            isValid = false;
        }

        if (mobile && !/^\d{10}$/.test(mobile)) {
            const el = document.getElementById('mobile_no');
            showError(el, 'Mobile number must be 10 digits.');
            if (!firstErrorEl) firstErrorEl = el;
            isValid = false;
        }

        if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            const el = document.getElementById('email_id');
            showError(el, 'Please enter a valid email.');
            if (!firstErrorEl) firstErrorEl = el;
            isValid = false;
        }

        // 🚫 Stop if invalid
        if (!isValid) {
            firstErrorEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
            firstErrorEl.focus();
            return;
        }

        // 🕵️ Hide sections temporarily during PDF
        const originalUploadDisplay = uploadSection.style.display;
        const originalFooterDisplay = cardFooter.style.display;
        uploadSection.style.display = 'none';
        cardFooter.style.display = 'none';

        // 🧾 Generate PDF
        html2canvas(form).then(canvas => {
            const imgData = canvas.toDataURL('image/png');
            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF('p', 'mm', 'a4');

            const title = "Water New Connection Certificate";
            pdf.setFont("helvetica", "bold");
            pdf.setFontSize(14);

            const pageWidth = pdf.internal.pageSize.getWidth();
            const margin = 10;
            const lines = pdf.splitTextToSize(title, pageWidth - margin * 2);
            pdf.text(lines, margin, 15);

            const imgProps = pdf.getImageProperties(imgData);
            const pdfWidth = pageWidth;
            const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;

            pdf.addImage(imgData, 'PNG', 0, 30, pdfWidth, pdfHeight);
            pdf.save('Water_New_Connection.pdf');

            // ✅ After saving PDF
            saveBtn.style.display = 'none';         // Hide Save & Print
            uploadSection.style.display = 'block';  // Show Upload file section
            cardFooter.style.display = 'block';     // Show Submit & Reset buttons

        }).catch(err => {
            console.error('PDF generation failed:', err);
            alert('PDF generation failed. Check console.');
        }).finally(() => {
            // Restore display (not needed if we show after PDF)
            uploadSection.style.display = 'block';
            cardFooter.style.display = 'block';
        });
    });

    // 🌐 Prabhag → Wards dropdown
    async function getWards(id) {
        const wards = document.querySelector("#wards");
        wards.innerHTML = '<option value="">Select option</option>';
        const response = await fetch(`/get-water-wards-by-prabhag/${id}`);
        const data = await response.json();
        data.forEach(ward => {
            wards.insertAdjacentHTML('beforeend', `<option value="${ward.id}">${ward.ward_name}</option>`);
        });
    }

    document.querySelector('#prabhag').addEventListener('change', async (event) => {
        const id = event.target.value;
        await getWards(id);
    });

    // 💧 Usage → SubUsage → Pipe Size dropdowns
    const usageEl = document.querySelector('#water_connection_use');
    const subUsageEl = document.querySelector('#water_connection_sub_use');
    const pipeSizeEl = document.querySelector('#pipe_size');

    const subUsageMap = {
        'निवासी': ['इमारत', 'गावठाण स्वतंत्र घर', 'गट कनेक्शन', 'रो हाउस / बंगला'],
        'अनिवासी व्यवसाय': ['व्यवसाय 1', 'व्यवसाय 2'],
        'औद्योगीक': ['इमारत'],
        'विशेष प्रवर्ग (शैक्षणिक संस्था,शासकीय,निमशासकीय कार्यालय,पथसंस्था,इतर)': ['इमारत'],
        'व्यावसायिक अथवा वाणिज्य': ['गट कनेक्शन', 'इमारत']
    };

    const pipeMap = {
        'इमारत': '1',
        'गावठाण स्वतंत्र घर': '1/2',
        'गट कनेक्शन': '1/2',
        'रो हाउस / बंगला': '1/2',
        'व्यवसाय 1': '1',
        'व्यवसाय 2': '1/2'
    };

    usageEl.addEventListener('change', function() {
        const selectedUsage = this.value;
        subUsageEl.innerHTML = '<option value="">Select option</option>';
        pipeSizeEl.innerHTML = '<option value="">Select option</option>';

        if (subUsageMap[selectedUsage]) {
            subUsageMap[selectedUsage].forEach(function(sub) {
                const opt = document.createElement('option');
                opt.value = sub;
                opt.text = sub;
                subUsageEl.appendChild(opt);
            });
        }
    });

    subUsageEl.addEventListener('change', function() {
        const selectedSub = this.value;
        pipeSizeEl.innerHTML = '<option value="">Select option</option>';
        if (pipeMap[selectedSub]) {
            const opt = document.createElement('option');
            opt.value = pipeMap[selectedSub];
            opt.text = pipeMap[selectedSub] + ' inch';
            opt.selected = true;
            pipeSizeEl.appendChild(opt);
        }
    });
});
</script> --}}


{{-- <script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('addForm');
    const saveBtn = document.getElementById('saveAndPrintBtn');
    const uploadSection = document.getElementById('upload_section');
    const cardFooter = document.getElementById('card-footer');

    // 🧩 Validation messages
    const messages = {
        applicant_full_name: 'Applicant Name is Required',
        aadhar_no: 'Aadhar No is Required',
        mobile_no: 'Mobile No is Required',
        email_id: 'Email is Required',
        address: 'Address is Required',
        no_of_flats_shops: 'No of Flats/Shops is Required',
        property_no: 'Property No is Required',
        water_connection_use: 'Water Connection Use is Required',
        pipe_size: 'Pipe Size is Required',
        no_of_tap: 'No of Tap is Required',
        current_no_of_tap: 'Current No of Tap is Required',
        prabhag: 'Prabhag is Required',
        wards: 'Wards is Required',
        stamp_karnama: 'Stamp Karnama is Required',
        structure_photo: 'Structure Photo is Required',
        address_proof: 'Address Proof is Required',
        ownership_document: 'Ownership Document is Required',
        is_correct_info: 'Please Accept the Declaration'
    };

  
    function showError(el, message) {
        const oldMsg = el.nextElementSibling;
        if (oldMsg && oldMsg.classList.contains('error-msg')) oldMsg.remove();

        const errorEl = document.createElement('div');
        errorEl.classList.add('error-msg');
        errorEl.style.color = 'red';
        errorEl.style.fontSize = '0.9em';
        errorEl.textContent = message;

        el.style.border = '1px solid red';
        el.parentNode.insertBefore(errorEl, el.nextSibling);
    }

    
    function clearErrors() {
        Object.keys(messages).forEach(id => {
            const el = document.getElementById(id);
            if (el) {
                el.style.border = '';
                const errorEl = el.nextElementSibling;
                if (errorEl && errorEl.classList.contains('error-msg')) {
                    errorEl.remove();
                }
            }
        });
    }

    
    function showCheckboxError(message) {
        const err = document.querySelector('.is_correct_info_err');
        if (err) err.textContent = message;
    }
    function clearCheckboxError() {
        const err = document.querySelector('.is_correct_info_err');
        if (err) err.textContent = '';
    }

   
    saveBtn.addEventListener('click', function(e) {
        e.preventDefault();
        clearErrors();
        clearCheckboxError();

        let isValid = true;
        let firstErrorEl = null;

       
        Object.keys(messages).forEach(id => {
            const el = document.getElementById(id);
            if (el) {
                if (id === 'is_correct_info' && !el.checked) {
                    showCheckboxError(messages[id]);
                    if (!firstErrorEl) firstErrorEl = el;
                    isValid = false;
                } else if (id !== 'is_correct_info' && !el.value.trim()) {
                    showError(el, messages[id]);
                    if (!firstErrorEl) firstErrorEl = el;
                    isValid = false;
                }
            }
        });

        
        const aadhar = document.getElementById('aadhar_no').value.trim();
        const mobile = document.getElementById('mobile_no').value.trim();
        const email = document.getElementById('email_id').value.trim();

        if (aadhar && !/^\d{12}$/.test(aadhar)) {
            const el = document.getElementById('aadhar_no');
            showError(el, 'Aadhar number must be 12 digits.');
            if (!firstErrorEl) firstErrorEl = el;
            isValid = false;
        }

        if (mobile && !/^\d{10}$/.test(mobile)) {
            const el = document.getElementById('mobile_no');
            showError(el, 'Mobile number must be 10 digits.');
            if (!firstErrorEl) firstErrorEl = el;
            isValid = false;
        }

        if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            const el = document.getElementById('email_id');
            showError(el, 'Please enter a valid email.');
            if (!firstErrorEl) firstErrorEl = el;
            isValid = false;
        }

        // 🚫 Stop if invalid
        if (!isValid) {
            firstErrorEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
            firstErrorEl.focus();
            return;
        }

        // 🖨️ PDF generation section (Styled like Reference Script)
        const addContainer = document.getElementById('addContainer') || form;
        const printClone = addContainer.cloneNode(true);

        // PDF Styling
        Object.assign(printClone.style, {
            fontSize: '15px',
            lineHeight: '1.4',
            padding: '20px',
            margin: '0 auto',
            background: '#fff',
            width: '210mm',
            minHeight: '297mm',
            boxSizing: 'border-box'
        });

        // Hide upload + buttons
        printClone.querySelectorAll('#upload_section, #card-footer, button').forEach(el => el.style.display = 'none');

        // Style cards
        printClone.querySelectorAll('.card').forEach(card => {
            Object.assign(card.style, {
                background: 'white',
                border: '1px solid #ccc',
                boxShadow: 'none',
                marginBottom: '12px',
                padding: '12px'
            });
        });

        // Add title
        const title = document.createElement('h2');
        title.style.cssText = 'text-align:center; margin-bottom:18px; font-size:18px;';
        title.textContent = 'Certificate of Water New Connection';
        printClone.insertBefore(title, printClone.firstChild);

        // Hidden offscreen container
        let printContainer = document.getElementById('printContainer');
        if (!printContainer) {
            printContainer = document.createElement('div');
            printContainer.id = 'printContainer';
            printContainer.style.position = 'fixed';
            printContainer.style.left = '-9999px';
            document.body.appendChild(printContainer);
        }
        printContainer.innerHTML = '';
        printContainer.appendChild(printClone);

        // Generate PDF
        setTimeout(() => {
            html2canvas(printClone, {
                scrollY: -window.scrollY,
                backgroundColor: '#fff',
                scale: 1
            }).then(canvas => {
                const imgData = canvas.toDataURL('image/jpeg', 0.7);
                const { jsPDF } = window.jspdf;
                const pdf = new jsPDF('p', 'mm', 'a4');
                const margin = 10;

                pdf.addImage(
                    imgData,
                    'JPEG',
                    margin,
                    margin,
                    pdf.internal.pageSize.getWidth() - margin * 2,
                    pdf.internal.pageSize.getHeight() - margin * 2
                );

                pdf.save('Water_New_Connection.pdf');
                saveBtn.style.display = 'none';
                uploadSection.style.display = 'block';
                cardFooter.style.display = 'block';
            }).catch(err => {
                console.error('PDF generation failed:', err);
                alert('PDF generation failed. Check console.');
            });
        }, 100);
    });

    // 🌐 Prabhag → Wards
    async function getWards(id) {
        const wards = document.querySelector("#wards");
        wards.innerHTML = '<option value="">Select option</option>';
        const response = await fetch(`/get-water-wards-by-prabhag/${id}`);
        const data = await response.json();
        data.forEach(ward => {
            wards.insertAdjacentHTML('beforeend', `<option value="${ward.id}">${ward.ward_name}</option>`);
        });
    }
    document.querySelector('#prabhag').addEventListener('change', async (event) => {
        await getWards(event.target.value);
    });

    // 💧 Use → Subuse → Pipe
    const usageEl = document.querySelector('#water_connection_use');
    const subUsageEl = document.querySelector('#water_connection_sub_use');
    const pipeSizeEl = document.querySelector('#pipe_size');

    const subUsageMap = {
        'निवासी': ['इमारत', 'गावठाण स्वतंत्र घर', 'गट कनेक्शन', 'रो हाउस / बंगला'],
        'अनिवासी व्यवसाय': ['व्यवसाय 1', 'व्यवसाय 2'],
        'औद्योगीक': ['इमारत'],
        'विशेष प्रवर्ग (शैक्षणिक संस्था,शासकीय,निमशासकीय कार्यालय,पथसंस्था,इतर)': ['इमारत'],
        'व्यावसायिक अथवा वाणिज्य': ['गट कनेक्शन', 'इमारत']
    };

    const pipeMap = {
        'इमारत': '1',
        'गावठाण स्वतंत्र घर': '1/2',
        'गट कनेक्शन': '1/2',
        'रो हाउस / बंगला': '1/2',
        'व्यवसाय 1': '1',
        'व्यवसाय 2': '1/2'
    };

    usageEl.addEventListener('change', function() {
        const selectedUsage = this.value;
        subUsageEl.innerHTML = '<option value="">Select option</option>';
        pipeSizeEl.innerHTML = '<option value="">Select option</option>';

        if (subUsageMap[selectedUsage]) {
            subUsageMap[selectedUsage].forEach(function(sub) {
                const opt = document.createElement('option');
                opt.value = sub;
                opt.text = sub;
                subUsageEl.appendChild(opt);
            });
        }
    });

    subUsageEl.addEventListener('change', function() {
        const selectedSub = this.value;
        pipeSizeEl.innerHTML = '<option value="">Select option</option>';
        if (pipeMap[selectedSub]) {
            const opt = document.createElement('option');
            opt.value = pipeMap[selectedSub];
            opt.text = pipeMap[selectedSub] + ' inch';
            opt.selected = true;
            pipeSizeEl.appendChild(opt);
        }
    });
});
</script> --}}


<script>
document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('addForm');
    const saveBtn = document.getElementById('saveAndPrintBtn');
    const uploadSection = document.getElementById('upload_section');
    const cardFooter = document.getElementById('card-footer');

    // Validation messages
    const messages = {
        applicant_full_name: 'Applicant Name is Required',
        aadhar_no: 'Aadhar No is Required',
        mobile_no: 'Mobile No is Required',
        email_id: 'Email is Required',
        address: 'Address is Required',
        no_of_flats_shops: 'No of Flats/Shops is Required',
        property_no: 'Property No is Required',
        water_connection_use: 'Water Connection Use is Required',
        water_connection_sub_use: 'Sub Usage of Water Connection is Required',
        pipe_size: 'Pipe Size is Required',
        no_of_tap: 'No of Tap is Required',
        current_no_of_tap: 'Current No of Tap is Required',
        prabhag: 'Prabhag is Required',
        wards: 'Ward is Required',
        stamp_karnama: 'Stamp Karnama is Required',
        structure_photo: 'Structure Photo is Required',
        address_proof: 'Address Proof is Required',
        ownership_document: 'Ownership Document is Required',
        is_correct_info: 'Please Accept the Declaration'
    };

    function showError(el, message) {
        const oldMsg = el.nextElementSibling;
        if (oldMsg && oldMsg.classList.contains('error-msg')) oldMsg.remove();
        const errorEl = document.createElement('div');
        errorEl.classList.add('error-msg');
        errorEl.style.color = 'red';
        errorEl.style.fontSize = '0.9em';
        errorEl.textContent = message;
        el.style.border = '1px solid red';
        el.parentNode.insertBefore(errorEl, el.nextSibling);
    }

    function clearErrors() {
        Object.keys(messages).forEach(id => {
            const el = document.getElementById(id);
            if (el) {
                el.style.border = '';
                const err = el.nextElementSibling;
                if (err && err.classList.contains('error-msg')) err.remove();
            }
        });
    }

    function showCheckboxError(message) {
        const err = document.querySelector('.is_correct_info_err');
        if (err) err.textContent = message;
    }
    function clearCheckboxError() {
        const err = document.querySelector('.is_correct_info_err');
        if (err) err.textContent = '';
    }

    // MAIN BUTTON
    saveBtn.addEventListener('click', function (e) {
        e.preventDefault();
        clearErrors();
        clearCheckboxError();

        let isValid = true;
        let firstErrorEl = null;

        Object.keys(messages).forEach(id => {
            const el = document.getElementById(id);
            if (el) {
                if (id === 'is_correct_info' && !el.checked) {
                    showCheckboxError(messages[id]);
                    if (!firstErrorEl) firstErrorEl = el;
                    isValid = false;
                } else if (id !== 'is_correct_info' && !el.value.trim()) {
                    showError(el, messages[id]);
                    if (!firstErrorEl) firstErrorEl = el;
                    isValid = false;
                }
            }
        });


        const aadharEl = document.getElementById('aadhar_no');
    const mobileEl = document.getElementById('mobile_no');
    const emailEl = document.getElementById('email_id');

    const aadhar = aadharEl?.value.trim();
    const mobile = mobileEl?.value.trim();
    const email = emailEl?.value.trim();

    if (aadhar && !/^\d{12}$/.test(aadhar)) {
        showError(aadharEl, 'Aadhar number must be 12 digits.');
        if (!firstErrorEl) firstErrorEl = aadharEl;
        isValid = false;
    }

    if (mobile && !/^\d{10}$/.test(mobile)) {
        showError(mobileEl, 'Mobile number must be 10 digits.');
        if (!firstErrorEl) firstErrorEl = mobileEl;
        isValid = false;
    }

    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        showError(emailEl, 'Please enter a valid email.');
        if (!firstErrorEl) firstErrorEl = emailEl;
        isValid = false;
    }

    

        if (!isValid) {
            firstErrorEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
            firstErrorEl.focus();
            return;
        }

        // ✅ Store dropdown display values
        document.querySelectorAll('select').forEach(sel => {
            const selectedOption = sel.options[sel.selectedIndex];
            if (selectedOption && selectedOption.text) {
                sel.setAttribute('data-display', selectedOption.text);
            }
        });

        // Clone for PDF
        const addContainer = document.getElementById('addContainer') || form;
        const printClone = addContainer.cloneNode(true);

        // Replace selects with textbox-like readonly
        printClone.querySelectorAll('select').forEach(sel => {
            const displayValue = sel.getAttribute('data-display') || sel.value || '';
            const textInput = document.createElement('input');
            textInput.type = 'text';
            textInput.value = displayValue;
            textInput.readOnly = true;
            textInput.style.width = '100%';
            textInput.style.border = '1px solid #ccc';
            textInput.style.padding = '4px';
            textInput.style.fontSize = '14px';
            textInput.style.boxSizing = 'border-box';
            textInput.style.background = '#ffffff'; // ✅ textbox white
            sel.parentNode.replaceChild(textInput, sel);
        });

        // Hide UI not needed for PDF
        printClone.querySelectorAll('#upload_section, #card-footer, button').forEach(el => el.style.display = 'none');

        // Add heading
        const title = document.createElement('h2');
        title.style.cssText = 'text-align:center; margin-bottom:18px; font-size:18px;';
        title.textContent = 'Certificate of Water New Connection';
        printClone.insertBefore(title, printClone.firstChild);

        // ✅ Force entire form background to white for PDF
        printClone.style.background = '#ffffff';
        printClone.style.padding = '20px';
        printClone.style.fontSize = '15px';
        printClone.style.lineHeight = '1.4';
        printClone.style.margin = '0 auto';
        printClone.style.width = '210mm';
        printClone.style.minHeight = '297mm';
        printClone.style.boxSizing = 'border-box';
        printClone.style.boxShadow = 'none';
        printClone.style.border = 'none';

        // Hidden container
        let printContainer = document.getElementById('printContainer');
        if (!printContainer) {
            printContainer = document.createElement('div');
            printContainer.id = 'printContainer';
            printContainer.style.position = 'fixed';
            printContainer.style.left = '-9999px';
            printContainer.style.top = '0';
            printContainer.style.background = '#ffffff'; // ✅ white base layer
            document.body.appendChild(printContainer);
        }
        printContainer.innerHTML = '';
        printContainer.appendChild(printClone);

        // ✅ White background render
        setTimeout(() => {
            html2canvas(printClone, {
                scrollY: -window.scrollY,
                backgroundColor: '#ffffff', // ✅ main fix: full white
                scale: 2, // better quality
                useCORS: true
            }).then(canvas => {
                const imgData = canvas.toDataURL('image/jpeg', 1.0);
                const { jsPDF } = window.jspdf;
                const pdf = new jsPDF('p', 'mm', 'a4');
                const margin = 10;
                const pageWidth = pdf.internal.pageSize.getWidth() - margin * 2;
                const pageHeight = pdf.internal.pageSize.getHeight() - margin * 2;
                pdf.addImage(imgData, 'JPEG', margin, margin, pageWidth, pageHeight);
                pdf.save('Water_New_Connection.pdf');

                // ✅ Show upload & footer, hide Save & Print
                if (uploadSection) uploadSection.style.display = 'block';
                if (cardFooter) cardFooter.style.display = 'block';
                if (saveBtn) saveBtn.style.display = 'none';
            }).catch(err => {
                console.error('PDF generation failed:', err);
                alert('PDF generation failed. Check console.');
            });
        }, 200);
    });

    // Dynamic wards
    async function getWards(id) {
        const wards = document.querySelector("#wards");
        wards.innerHTML = '<option value="">Select option</option>';
        const response = await fetch(`/get-water-wards-by-prabhag/${id}`);
        const data = await response.json();
        data.forEach(ward => {
            wards.insertAdjacentHTML('beforeend', `<option value="${ward.id}">${ward.ward_name}</option>`);
        });
    }

    document.querySelector('#prabhag').addEventListener('change', async (event) => {
        await getWards(event.target.value);
    });

    // Auto sub-usage & pipe size
    const usageEl = document.querySelector('#water_connection_use');
    const subUsageEl = document.querySelector('#water_connection_sub_use');
    const pipeSizeEl = document.querySelector('#pipe_size');

    const subUsageMap = {
        'निवासी': ['इमारत', 'गावठाण स्वतंत्र घर', 'गट कनेक्शन', 'रो हाउस / बंगला'],
        'अनिवासी व्यवसाय': ['व्यवसाय 1', 'व्यवसाय 2'],
        'औद्योगीक': ['इमारत'],
        'विशेष प्रवर्ग (शैक्षणिक संस्था,शासकीय,निमशासकीय कार्यालय,पथसंस्था,इतर)': ['इमारत'],
        'व्यावसायिक अथवा वाणिज्य': ['गट कनेक्शन', 'इमारत']
    };

    const pipeMap = {
        'इमारत': '1',
        'गावठाण स्वतंत्र घर': '1/2',
        'गट कनेक्शन': '1/2',
        'रो हाउस / बंगला': '1/2',
        'व्यवसाय 1': '1',
        'व्यवसाय 2': '1/2'
    };

    usageEl.addEventListener('change', function () {
        const selectedUsage = this.value;
        subUsageEl.innerHTML = '<option value="">Select option</option>';
        pipeSizeEl.innerHTML = '<option value="">Select option</option>';
        if (subUsageMap[selectedUsage]) {
            subUsageMap[selectedUsage].forEach(sub => {
                const opt = document.createElement('option');
                opt.value = sub;
                opt.text = sub;
                subUsageEl.appendChild(opt);
            });
        }
    });

    subUsageEl.addEventListener('change', function () {
        const selectedSub = this.value;
        pipeSizeEl.innerHTML = '<option value="">Select option</option>';
        if (pipeMap[selectedSub]) {
            const opt = document.createElement('option');
            opt.value = pipeMap[selectedSub];
            opt.text = pipeMap[selectedSub] + ' inch';
            opt.selected = true;
            pipeSizeEl.appendChild(opt);
        }
    });
});
</script>







































{{-- <script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('addForm');
    const saveBtn = document.getElementById('saveAndPrintBtn');
    const uploadSection = document.getElementById('upload_section');
    const cardFooter = document.getElementById('card-footer');

    // 📝 Validation messages
    const messages = {
        applicant_full_name: 'Applicant Name is Required',
        aadhar_no: 'Aadhar No is Required',
        mobile_no: 'Mobile No is Required',
        email_id: 'Email is Required',
        address: 'Address is Required',
        no_of_flats_shops: 'No of Flats/Shops is Required',
        property_no: 'Property No is Required',
        water_connection_use: 'Water Connection Use is Required',
        pipe_size: 'Pipe Size is Required',
        no_of_tap: 'No of Tap is Required',
        current_no_of_tap: 'Current No of Tap is Required',
        prabhag: 'Prabhag is Required',
        wards: 'Wards is Required',
        stamp_karnama: 'Stamp Karnama is Required',
        structure_photo: 'Structure Photo is Required',
        address_proof: 'Address Proof is Required',
        ownership_document: 'Ownership Document is Required',
        is_correct_info: 'Please Accept the Declaration'
    };

    // ❌ Show error
    function showError(el, message) {
        const oldMsg = el.nextElementSibling;
        if (oldMsg && oldMsg.classList.contains('error-msg')) oldMsg.remove();

        const errorEl = document.createElement('div');
        errorEl.classList.add('error-msg', 'text-danger');
        errorEl.style.fontSize = '0.9em';
        errorEl.textContent = message;

        el.style.border = '1px solid red';
        el.parentNode.insertBefore(errorEl, el.nextSibling);
    }

    // 🧹 Clear errors
    function clearErrors() {
        Object.keys(messages).forEach(id => {
            const el = document.getElementById(id);
            if (el) {
                el.style.border = '';
                const errorEl = el.nextElementSibling;
                if (errorEl && errorEl.classList.contains('error-msg')) errorEl.remove();
            }
        });
        const errSpan = document.querySelector('.is_correct_info_err');
        if (errSpan) errSpan.textContent = '';
    }

    // 🖱️ Save & Print button
    saveBtn.addEventListener('click', async function(e) {
        e.preventDefault();
        clearErrors();

        let isValid = true;
        let firstErrorEl = null;

        // Validate fields
        Object.keys(messages).forEach(id => {
            const el = document.getElementById(id);
            if (!el) return;

            if (id === 'is_correct_info' && !el.checked) {
                document.querySelector('.is_correct_info_err').textContent = messages[id];
                if (!firstErrorEl) firstErrorEl = el;
                isValid = false;
            } else if (id !== 'is_correct_info' && !el.value.trim()) {
                showError(el, messages[id]);
                if (!firstErrorEl) firstErrorEl = el;
                isValid = false;
            }
        });

        // Aadhaar, Mobile, Email validations
        const aadhar = document.getElementById('aadhar_no')?.value.trim();
        const mobile = document.getElementById('mobile_no')?.value.trim();
        const email = document.getElementById('email_id')?.value.trim();

        if (aadhar && !/^\d{12}$/.test(aadhar)) {
            showError(document.getElementById('aadhar_no'), 'Aadhar number must be 12 digits.');
            if (!firstErrorEl) firstErrorEl = document.getElementById('aadhar_no');
            isValid = false;
        }

        if (mobile && !/^\d{10}$/.test(mobile)) {
            showError(document.getElementById('mobile_no'), 'Mobile number must be 10 digits.');
            if (!firstErrorEl) firstErrorEl = document.getElementById('mobile_no');
            isValid = false;
        }

        if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            showError(document.getElementById('email_id'), 'Please enter a valid email.');
            if (!firstErrorEl) firstErrorEl = document.getElementById('email_id');
            isValid = false;
        }

        if (!isValid) {
            firstErrorEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
            firstErrorEl.focus();
            return;
        }

        // 🔒 Hide upload section + footer before capturing PDF
        const originalUploadDisplay = uploadSection.style.display;
        const originalFooterDisplay = cardFooter.style.display;
        uploadSection.style.display = 'none';
        cardFooter.style.display = 'none';
        saveBtn.style.display = 'none';

        // 📜 Clone clean version for better PDF layout
        const formClone = form.cloneNode(true);
        formClone.querySelectorAll('button').forEach(btn => btn.remove());

        Object.assign(formClone.style, {
            background: '#fff',
            fontSize: '16px',
            lineHeight: '1.5',
            padding: '20px',
            width: '210mm',
            minHeight: '297mm',
            boxSizing: 'border-box',
            border: '1px solid #ccc'
        });

        // Add title
        const pdfTitle = document.createElement('h2');
        pdfTitle.textContent = 'Certificate of Water New Connection';
        pdfTitle.style.cssText = 'text-align:center; font-size:18px; margin-bottom:18px; font-weight:bold;';
        formClone.insertBefore(pdfTitle, formClone.firstChild);

        // Create hidden container
        let pdfContainer = document.getElementById('pdfContainer');
        if (!pdfContainer) {
            pdfContainer = document.createElement('div');
            pdfContainer.id = 'pdfContainer';
            pdfContainer.style.position = 'fixed';
            pdfContainer.style.left = '-9999px';
            document.body.appendChild(pdfContainer);
        }
        pdfContainer.innerHTML = '';
        pdfContainer.appendChild(formClone);

        // 🧾 Generate PDF
        try {
            const canvas = await html2canvas(formClone, { scale: 1.2, backgroundColor: '#fff' });
            const imgData = canvas.toDataURL('image/jpeg', 0.6);

            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF('p', 'mm', 'a4');
            const margin = 10;

            pdf.addImage(
                imgData, 'JPEG',
                margin, margin,
                pdf.internal.pageSize.getWidth() - margin * 2,
                pdf.internal.pageSize.getHeight() - margin * 2
            );

            pdf.save('Water_New_Connection_Certificate.pdf');
        } catch (err) {
            console.error('PDF generation failed:', err);
            alert('PDF generation failed. Check console.');
        } finally {
            // ✅ Restore UI
            uploadSection.style.display = originalUploadDisplay;
            cardFooter.style.display = originalFooterDisplay;
            // Keep saveBtn hidden after successful generation
        }
    });

    // 🌐 Prabhag → Wards dropdown
    async function getWards(id) {
        const wards = document.querySelector("#wards");
        wards.innerHTML = '<option value="">Select option</option>';
        const response = await fetch(`/get-water-wards-by-prabhag/${id}`);
        const data = await response.json();
        data.forEach(ward => {
            wards.insertAdjacentHTML('beforeend', `<option value="${ward.id}">${ward.ward_name}</option>`);
        });
    }
    document.querySelector('#prabhag').addEventListener('change', async (event) => {
        await getWards(event.target.value);
    });

    // 💧 Usage → SubUsage → Pipe Size dropdowns
    const usageEl = document.querySelector('#water_connection_use');
    const subUsageEl = document.querySelector('#water_connection_sub_use');
    const pipeSizeEl = document.querySelector('#pipe_size');

    const subUsageMap = {
        'निवासी': ['इमारत', 'गावठाण स्वतंत्र घर', 'गट कनेक्शन', 'रो हाउस / बंगला'],
        'अनिवासी व्यवसाय': ['व्यवसाय 1', 'व्यवसाय 2'],
        'औद्योगीक': ['इमारत'],
        'विशेष प्रवर्ग (शैक्षणिक संस्था,शासकीय,निमशासकीय कार्यालय,पथसंस्था,इतर)': ['इमारत'],
        'व्यावसायिक अथवा वाणिज्य': ['गट कनेक्शन', 'इमारत']
    };

    const pipeMap = {
        'इमारत': '1',
        'गावठाण स्वतंत्र घर': '1/2',
        'गट कनेक्शन': '1/2',
        'रो हाउस / बंगला': '1/2',
        'व्यवसाय 1': '1',
        'व्यवसाय 2': '1/2'
    };

    usageEl.addEventListener('change', function() {
        const selectedUsage = this.value;
        subUsageEl.innerHTML = '<option value="">Select option</option>';
        pipeSizeEl.innerHTML = '<option value="">Select option</option>';
        if (subUsageMap[selectedUsage]) {
            subUsageMap[selectedUsage].forEach(sub => {
                const opt = document.createElement('option');
                opt.value = sub;
                opt.text = sub;
                subUsageEl.appendChild(opt);
            });
        }
    });

    subUsageEl.addEventListener('change', function() {
        const selectedSub = this.value;
        pipeSizeEl.innerHTML = '<option value="">Select option</option>';
        if (pipeMap[selectedSub]) {
            const opt = document.createElement('option');
            opt.value = pipeMap[selectedSub];
            opt.text = pipeMap[selectedSub] + ' inch';
            opt.selected = true;
            pipeSizeEl.appendChild(opt);
        }
    });
});
</script> --}}




















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

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('water-new-connection.store') }}',
            type: 'POST',
            data: formdata,
            contentType: false,
            processData: false,
            beforeSend: function() {
                $('#preloader').css('opacity', '0.5');
                $('#preloader').css('visibility', 'visible');
            },
            success: function(data) {
                $("#addSubmit").prop('disabled', false);
                if (!data.error)
                    swal("Successful!", data.success, "success")
                    .then((action) => {
                        window.location.href = '{{ route('my-application') }}';
                    });
                else
                    swal("Error!", data.error, "error");
            },
            statusCode: {
                422: function(responseObject, textStatus, jqXHR) {
                    $("#addSubmit").prop('disabled', false);
                    resetErrors();
                    printErrMsg(responseObject.responseJSON.errors);
                },
                500: function(responseObject, textStatus, errorThrown) {
                    $("#addSubmit").prop('disabled', false);
                    swal("Error occured!", "Something went wrong please try again", "error");
                }
            },
            complete: function() {
                $('#preloader').css('opacity', '0');
                $('#preloader').css('visibility', 'hidden');
            },
        });

    });
</script> 


{{-- <script>
document.getElementById('saveAndPrintBtn').addEventListener('click', function () {
    const form = document.getElementById('addForm');
    if (!form) return alert('Form not found!');

    // ✅ Custom validation messages for each field
    const messages = {
        applicant_full_name: 'Applicant Name is Required',
        aadhar_no: 'Adhar No is Required',
        mobile_no: 'Mobile No is Required',
        address: 'Address is Required',
        no_of_flats_shops: 'No of flats is Required',
        property_no: 'Property No is Required',
        water_connection_use: 'Water Connection Use is Required',
        pipe_size: 'Pipe Size is Required',
        no_of_tap: 'No of Tap is Required',
        current_no_of_tap: 'Current No of Tap is Required',
        prabhag: 'Prabhag is Required',
        wards: 'Wards is Required',
        stamp_karnama: 'Stamp Karnama is Required',
        structure_photo: 'Structure Photo is Required',
        address_proof:'Address Proof is Required',
        is_correct_info:'is_correct_info',
    };

    let isValid = true;

    // Remove old error messages
    form.querySelectorAll('.error-message').forEach(e => e.remove());

    // Loop through required fields and show inline error
    Object.keys(messages).forEach(name => {
        const field = form.querySelector(`[name="${name}"]`);
        if (!field) return;

        let errorText = '';
        if (field.type === 'checkbox') {
            if (!field.checked) errorText = messages[name];
        } else if (!field.value.trim()) {
            errorText = messages[name];
        }

        if (errorText) {
            isValid = false;
            const error = document.createElement('div');
            error.className = 'error-message text-danger mt-1';
            error.style.fontSize = '13px';
            error.textContent = errorText;

            if (field.parentNode) {
                field.parentNode.appendChild(error);
            }
        }
    });

    if (!isValid) {
        // Scroll to first error field
        const firstError = form.querySelector('.error-message');
        if (firstError) firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
        return; // Stop PDF creation if validation fails
    }

    // ✅ Continue if form is valid
    const uploadSection = document.getElementById('upload_section');
    if (uploadSection) uploadSection.style.display = 'block';

    const cardFooter = document.getElementById('card-footer');
    if (cardFooter) cardFooter.style.display = 'block';

    const addContainer = document.getElementById('addContainer');
    if (!addContainer) return alert('Content container not found!');

    // Generate PDF
    html2canvas(addContainer, {
        scrollY: -window.scrollY,
        backgroundColor: '#fff',
        scale: 1
    }).then(canvas => {
        const imgData = canvas.toDataURL('image/jpeg', 0.8);

        if (!window.jspdf || !window.jspdf.jsPDF) {
            return alert('jsPDF library not loaded!');
        }

        const pdf = new window.jspdf.jsPDF('p', 'mm', 'a4');
        const margin = 10;
        pdf.addImage(
            imgData, 'JPEG',
            margin, margin,
            pdf.internal.pageSize.getWidth() - margin * 2,
            pdf.internal.pageSize.getHeight() - margin * 2
        );

        pdf.save('Water_New_Connection.pdf');

        const saveBtn = document.getElementById('saveAndPrintBtn');
        if (saveBtn) saveBtn.style.display = 'none';
    }).catch(err => {
        console.error('PDF generation failed:', err);
        alert('PDF generation failed. Check console.');
    });
});
</script> --}}

<script>
const nameInput = document.getElementById('applicant_full_name');

// Allow only letters on keypress
nameInput.addEventListener('keypress', function(e) {
    const char = String.fromCharCode(e.which);
    if (!/^[a-zA-Z\s]$/.test(char)) { // letters and space allowed
        e.preventDefault();
    }
});

// Prevent numbers/special chars on paste
nameInput.addEventListener('paste', function(e) {
    e.preventDefault();
    const pasteData = (e.clipboardData || window.clipboardData).getData('text');
    const sanitized = pasteData.replace(/[^a-zA-Z\s]/g, ''); // remove everything except letters and spaces
    document.execCommand('insertText', false, sanitized);
});
</script>



