<x-admin.layout>
    <x-slot name="title">Issuance of death certificate/ मृत्यू दाखला मिळविणेबाबत.</x-slot>
    <x-slot name="heading">Issuance of death certificate/ मृत्यू दाखला मिळविणेबाबत.</x-slot>

    <div class="row" id="addContainer">
        <div class="col-sm-12">
            <div class="card">
                <form class="theme-form" name="addForm" id="addForm" enctype="multipart/form-data">
                    @csrf

                    <div class="card-header">
                        <h4 class="card-title">Add Details / माहिती भरा</h4>
                    </div>

                    <div class="card-body">
                        {{-- Applicant Details --}}
                        <h5 class="text-primary">Details of Applicant / अर्जदाराची माहिती</h5>
                        <div class="mb-3 row">
                            {{-- Row 1 --}}
                            <div class="col-md-4 mb-3">
                                <label class="col-form-label" for="surname">Surname / आडनाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="surname" name="surname" type="text" placeholder="Enter Surname" oninput="this.value = this.value.replace(/[^a-zA-Z\s]/g, '')" required >
                                <span class="text-danger is-invalid surname_err"></span>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="col-form-label" for="name">Name / नाव <span class="text-danger">*</span></label>
                                <input class="form-control" id="name" name="name" type="text" placeholder="Enter Name" oninput="this.value = this.value.replace(/[^a-zA-Z\s]/g, '')" required >
                                <span class="text-danger is-invalid name_err"></span>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label for="father_name" class="col-form-label">Father Name / वडिलांचे नाव <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="father_name" name="father_name" placeholder="Enter Father Name" oninput="this.value = this.value.replace(/[^a-zA-Z\s]/g, '')" required >
                                <span class="text-danger is-invalid father_name_err"></span>
                            </div>

                            {{-- Row 2 --}}
                            <div class="col-md-4 mb-3">
                                <label for="address" class="col-form-label">Address / पत्ता <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="address" name="address" placeholder="Enter Address" required >
                                <span class="text-danger is-invalid address_err"></span>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label for="society_name" class="col-form-label">Society Name/ सोसायटीचे नाव<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="society_name" name="society_name" placeholder="Enter society name" required >
                                <span class="text-danger is-invalid society_name_err"></span>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label for="block_no" class="col-form-label">Block Number / ब्लॉक क्रमांक<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="block_no" name="block_no" placeholder="Enter Block Number" required >
                                <span class="text-danger is-invalid block_no_err"></span>
                            </div>

                            {{-- Row 3 --}}
                            <div class="col-md-4 mb-3">
                                <label for="road_name" class="col-form-label">Road Name / रस्त्याचे नाव<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="road_name" name="road_name" placeholder="Enter Road Name" required >
                                <span class="text-danger is-invalid road_name_err"></span>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label for="place" class="col-form-label">Place / जागा<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="place" name="place" placeholder="Enter Place" oninput="this.value = this.value.replace(/[^a-zA-Z\s]/g, '')" required >
                                <span class="text-danger is-invalid place_err"></span>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label for="pincode" class="col-form-label">PinCode Number / पिनकोड क्रमांक<span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="pincode" name="pincode" placeholder="Enter Pincode Number" min="100000" max="999999" oninput="this.value = this.value.slice(0, 6)" required >
                                <span class="text-danger is-invalid pincode_err"></span>
                            </div>

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

                            <div class="col-md-4 mb-3">
                                <label for="mbmc_elec_ward_no" class="col-form-label">Mbmc electric ward number / Mbmc इलेक्ट्रिक वार्ड क्रमांक<span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="mbmc_elec_ward_no" name="mbmc_elec_ward_no" placeholder="Enter mbmc elextric ward number" required >
                                <span class="text-danger is-invalid mbmc_elec_ward_no_err"></span>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label for="mobile_no" class="col-form-label">Contact Number/संपर्क क्रमांक<span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="mobile_no" name="mobile_no" placeholder="Enter Contact Number" maxlength="10" pattern="\d{10}" title="Please enter 10 digit number" inputmode="numeric" oninput="this.value=this.value.replace(/[^0-9]/g,'').slice(0,10);" required >
                                <span class="text-danger is-invalid mobile_no_err"></span>
                            </div>
                        </div>

                        {{-- Important Details --}}
                        <h5 class="text-primary">Details Of Deceased / मृतांचा तपशील</h5>
                        <div class="mb-3 row">

                            {{-- Row 1 --}}
                            <div class="col-md-4 mb-3">
                                <label for="date_of_death" class="col-form-label">Date of Death/मृत्यूची तारीख<span class="text-danger">*</span></label>
                                {{-- Set max to today's date for validation --}}
                                <input type="date" class="form-control" id="date_of_death" name="date_of_death" max="{{ now()->format('Y-m-d') }}" required>
                                <span class="text-danger is-invalid date_of_death_err"></span>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label for="name_of_deceased" class="col-form-label">Name Of Deceased / मृत व्यक्तीचे नाव<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="name_of_deceased" name="name_of_deceased" placeholder="Enter name of deceased" oninput="this.value = this.value.replace(/[^a-zA-Z\s]/g, '')" required>
                                <span class="text-danger is-invalid name_of_deceased_err"></span>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label for="name_in_english" class="col-form-label">Name In English/इंग्रजीत नाव<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="name_in_english" name="name_in_english" placeholder="Enter name in english" oninput="this.value = this.value.replace(/[^a-zA-Z\s]/g, '')" required>
                                <span class="text-danger is-invalid name_in_english_err"></span>
                            </div>

                            {{-- Row 2 --}}
                            <div class="col-md-4 mb-3">
                                <label for="gender" class="col-form-label">Gender/लिंग<span class="text-danger">*</span></label>
                                <select name="gender" id="gender" class="form-select" required>
                                    <option value="">Select Gender</option>
                                    <option value="Male">Male</option>
                                    <option value="Female">Female</option>
                                    <option value="Other">Other</option>
                                </select>
                                <span class="text-danger is-invalid gender_err"></span>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label for="age" class="col-form-label">Age/वय<span class="text-danger">*</span></label>
                                <input
                                    type="number"
                                    class="form-control"
                                    id="age"
                                    name="age"
                                    placeholder="Enter Age"
                                    maxlength="3"
                                    oninput="if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
                                    required
                                >
                                <span class="text-danger is-invalid age_err"></span>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label for="place_of_death" class="col-form-label">Place Of Death/मृत्यूचे ठिकाण<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="place_of_death" name="place_of_death" placeholder="Enter Place Of Death" oninput="this.value = this.value.replace(/[^a-zA-Z\s]/g, '')" required>
                                <span class="text-danger is-invalid place_of_death_err"></span>
                            </div>

                            {{-- Row 3 --}}
                            <div class="col-md-4 mb-3">
                                <label for="permanenent_address" class="col-form-label">Place Of Death Address/मृत्यूचे ठिकाण पत्ता<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="permanenent_address" name="permanenent_address" placeholder="Enter Permanent Address" required>
                                <span class="text-danger is-invalid permanenent_address_err"></span>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="col-form-label" for="no_of_certificate">No. Of Certificate/प्रमाणपत्राची संख्या <span class="text-danger">*</span></label>
                                <input class="form-control" id="no_of_certificate" name="no_of_certificate" placeholder="Enter number of certificate" type="number" min ="1" oninput="validateCertificates()" required>
                                <span class="text-danger is-invalid no_of_certificate_err"></span>
                            </div>

                            {{-- Document Upload Section (maintaining col-md-6) --}}
                            <div class="col-md-6 mb-3" 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" required>
                                <span class="text-danger is-invalid uploaded_applications_err"></span>
                            </div>

                        </div>

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

                        <div 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>
                    </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 src="{{ asset('admin/js/save_print.js') }}"></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 = "Issuance of death certificate";
                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('page-content.pdf');
            });
        } else {
            form.reportValidity();
        }
    });
</script> -->

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

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('death-insurance.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.addEventListener('DOMContentLoaded', function() {
    attachGlobalValidation('#addForm', '#saveAndPrintBtn', {
        containerId: 'addContainer',
        printTitle: 'Death Certificate',
    });
});
</script>
<script>
    function displayFileName(input) {
        const fileNameDisplay = document.getElementById(input.id.replace('_pics', '_file_name'));
        if (input.files.length > 0) {
            // .name property only provides the file name, not the path
            fileNameDisplay.textContent = 'Selected: ' + input.files[0].name;
            fileNameDisplay.style.color = 'green';
        } else {
            fileNameDisplay.textContent = 'No file selected';
            fileNameDisplay.style.color = 'gray';
        }
    }

    function validateCertificates() {
        const input = document.getElementById('no_of_certificate');
        const errorSpan = document.querySelector('.no_of_certificate_err'); // <-- correct span

        let value = parseInt(input.value);

        if (isNaN(value) || value <= 0) {
            errorSpan.textContent = "Value must be greater than 0.";
            errorSpan.style.display = 'block'; // ensure visibility
            input.classList.add('is-invalid');
            return false;
        }

        errorSpan.textContent = "";
        input.classList.remove('is-invalid');
        return true;
    }
</script>
