$(document).ready(function () {

    $("body").on("click", '.remove', remove);
    $("#submit").hide();
    $("body").on("focus change blur", ".tour,.vregnno", Getregno);
    $("body").on("blur", ".issdate, .expdate", getDoe);

    var passportData = {};

    $("#extractPassportBtn").click(function () {

        var file = $("#ocrPassportFile")[0].files[0];

        if (!file) {

            alert("Please select Passport Front.");

            return;

        }

        var fd = new FormData();

        fd.append("image", file);

        $.ajax({

            url: "ocr_passport.php",

            type: "POST",

            data: fd,

            processData: false,

            contentType: false,

            dataType: "json",

            beforeSend: function () {

                $("#extractPassportBtn")
                    .html("<i class='fa fa-spinner fa-spin'></i> Extracting...")
                    .prop("disabled", true);

            },

            success: function (res) {

                passportData = res;

                $("#ocrPassportNo").text(passportData["Passport Number"]);
                $("#ocrSurname").text(passportData["Surname"]);
                $("#ocrGiven").text(passportData["Given Names"]);
                $("#ocrNationality").text(passportData["Nationality"]);
                $("#ocrBirth").text(passportData["Date of Birth"]);
                $("#ocrIssue").text(passportData["Date of Issue"]);
                $("#ocrExpiry").text(passportData["Date of Expiry"]);
                $("#ocrIssuePlace").text(passportData["Place of Issue"]);
                $("#ocrBirthPlace").text(passportData["Place of Birth"]);
                $("#ocrGender").text(passportData["Sex"]);

                $("#passportOCRModal").modal("show");

            },

            error: function () {

                alert("OCR failed.");

            },

            complete: function () {

                $("#extractPassportBtn")
                    .html("Extract Passport")
                    .prop("disabled", false);

            }

        });

    });

    $("#fillOnly").click(function () {

        fillPassportData();

        // Remove selected file
        $("#ocrPassportFile").val("");

        // Restore original preview (or clear it)
        $(".view1").attr("src", "");

        $("#passportOCRModal").modal("hide");

    });

    function fillPassportData() {

        $(".redypass").val(passportData["Passport Number"]);

        $(".surname").val(passportData["Surname"]);

        // $(".lastname").val(passportData["Given Names"]);

        $(".nation").val(passportData["Nationality"]);

        $(".dob").val(passportData["Date of Birth"]);

        $(".issdate").val(passportData["Date of Issue"]);

        $(".expdate").val(passportData["Date of Expiry"]);

        $(".issplace").val(passportData["Place of Issue"]);

        $(".plbirth").val(passportData["Place of Birth"]);


        // Handle Given Names → name and middleName
        const givenNames = passportData["Given Names"] || "";
        const parts = givenNames.trim().split(" ");

        if (parts.length > 0) {
            $('.lastname').val(parts[0]); // First name
            $('.midname').val(parts.slice(1).join(" ")); // Rest as middle name
        }

        if (passportData["Sex"] == "M")
            $(".cmbgender").val("M").trigger("change");

        if (passportData["Sex"] == "F")
            $(".cmbgender").val("F").trigger("change");

        $("#passportOCRModal").modal("hide");
    }




    $('.pop').on('click', function () {
        $('.imagepreview').attr('src', $(this).find('img').attr('src'));
        $('#imagemodal').modal('show');
    });

    $(".image").change(function () {
        readURL0(this);
    });
    $(".ppfront").change(function () {
        readURL1(this);
    });
    $(".ppback").change(function () {
        readURL2(this);
    });
    $(".panimg").change(function () {
        readURL3(this);
    });
    $(".aadhaarimg").change(function () {
        readURL4(this);
    });
    $(".insuranc").change(function () {
        readURL5(this);
    });
    $(".visaimg").change(function () {
        readURL6(this);
    });
    $(".healthimg").change(function () {
        readURL7(this);
    });


    function readURL0(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('.paximg').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    function readURL1(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('.view1').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    function readURL2(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('.view2').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    function readURL3(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('.view3').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    function readURL4(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('.view4').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    function readURL5(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('.view5').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    function readURL6(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('.view6').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    function readURL7(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('.view7').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }



    function getDoe() {

        var dob = $(".dob").val(),
            valid = true,
            deptdate = $(".depdate").val(),
            issdate = $(".issdate").val();
        var now = new Date(deptdate);
        var past = new Date(dob);
        var nowYear = now.getFullYear();
        var pastYear = past.getFullYear();
        var age = nowYear - pastYear;

        var expdate = $(".expdate").val(),
            deptdate = $(".depdate").val();
        if (deptdate != "0000-00-00" && deptdate != '' && expdate != "0000-00-00" && expdate != '') {
            var inputEDate = new Date($(".depdate").val());
            var resultEDate = new Date(inputEDate);
            resultEDate.setMonth(inputEDate.getMonth() + 6);
            resultEDate.setDate(resultEDate.getDate() - 1);
            var resultEDateString = resultEDate.toISOString().split("T")[0];

            if (expdate != "0000-00-00" && expdate != '') {

                if (expdate < resultEDateString) {
                    alert("Passport Expiry Should Be Greater Than 6 Months From Departure Date");
                    $(".issdate").val("0000-00-00");
                    $(".expdate").val("0000-00-00");
                    $(".expdate").focus();
                    return false;
                    valid = false;
                }
            }
        }



    }

    function Getregno() {
        var tour = $(".tour").val();
        var vregnno = $(".vregnno").val();

        $.post('getdepdate.php', { vregnno: vregnno }, function (data) {
            $('.depdate').val(data);
        });

    }


    $("#finishTab").click(function () {
        // getDoe();
        var vouchno = $('.vouchno').val(),
            vregnno = $('.vregnno').val(),
            addflg = $('.addflg').val(),
            valid = true,
            a = 1;

        $.post('cntPax.php', { vregnno: vregnno, addflg: addflg }, function (data) {
            if (data > 0) {
                alert("No. Of Pax Does Not Match With Regn. Booking Entry. Please Check");
                valid = false;
                return false;

            }
        });

        if (vouchno == '') {
            var message = "Voucher Cannot Be Empty";
            alert(message);
            $("#finishTab").show();

            return false;
            valid = false;
        }
        if (vregnno == '') {
            var message = "Regn. No. Cannot Be Empty";
            alert(message);
            $("#finishTab").show();

            return false;
            valid = false;
        }

        if (valid) {
            var isValid = true;
            if (isValid) {
                $("#finishTab").hide();
                $("#submit").click();
                $("#cancel").hide();
            }
        }

    });

    $('#addnew').click(function () {
        AddRows();
    });



    function AddRows() {
        var ctr = $('#items').val();
        var hide_check = "";
        if ($("#del_all").prop("checked")) {
            hide_check = 0;
        } else {
            hide_check = 1;
        }
        var detail = ".fetchpart_" + ctr;

        $.post('paxform_add.php', { ctr: ctr, hide: hide_check }, function (data) {
            $(data).appendTo('.tbody');
            ctr++;
            $('#items').val(ctr);
            $(detail).select2();
        });
    }

    function remove() {
        $(this).closest("tr").remove();
    }


});