<?= $this->extend('v2/layout/auth_layout') ?>

<?= $this->section('css') ?>
<style>
.employee-edit form {
    .card-header {
        font-weight: bold;
    }
    .card-body {
        ul {
            padding: 0;
        }
    }
    .customer-reg-info {
        .card-body {
            font-size: 100%;
            input, select {
                font-size: 100%;
            }
        }
    }
    &:not(.need-password) {
        #password-section {
            display: none;
        }
    }
}
.user-order-types input.invalid {
    border: 1px solid #ff0000;
    box-shadow: 0px 0px 0px 4px #ffa3a3;
}
.user-table-on-mobile {
    display: none;
}
@media (max-width: 992px) {
    .add_user_btn_on_mobile {
        margin-left: 5px !important;
        padding: 0px !important;
        font-size: 10px;
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 74px;
        overflow: hidden;
    }
    .user-table-on-desktop {
        display: none;
    }
    .user-table-on-mobile {
        display: block;
    }
    .vertical-middle-on-mobile {
        vertical-align: middle;
    }
}
.customer-register-panel {
    /* width: 90%; */
    max-width: 1200px;
    padding-left: 40px;
    padding-right: 40px;
    button#btn-login {
        margin-top: 20px !important;
        width: 100%;
    }
}

.card-row {
    gap: 30px;
}
@media (max-width: 992px) {
    .card-row {
        gap: 0px !important;
    }
}
.flex-fill2 {
    flex: 1 1 !important
}

@keyframes shake {
	0%   { transform: translateX(0); }
	20%  { transform: translateX(-4px); }
	40%  { transform: translateX(4px); }
	60%  { transform: translateX(-4px); }
	80%  { transform: translateX(4px); }
	100% { transform: translateX(0); }
}

#recaptcha-container.shake {
	animation: shake 0.3s ease-in-out;
}

.customer-register-panel-for-email {
    .form-control, .form-select {
        font-size: 80%;
        line-height: 1;
    }
    * {
        border-radius: 0 !important;
        color: #545454;
    }
    label {
        font-size: 12px !important;
    }
    .form-check.d-flex label {
        line-height: 25px;
    }

}
</style>
<?= $this->endSection() ?>

<?= $this->section('content') ?>
<div class="customer-register-panel mx-auto">
    <h4 class="text-center mb-4 pt-4-5">Customer Registration Request</h4>
    <div class="employee-edit">
        <form id="customer_register_form" class="needs-validation" novalidate style="display: flex; flex-direction: column; gap: 10px;">
            <div class="d-flex2 justify-content-between" style="gap: 10px">
                <div class="customer-reg-info card full-width-on-mobile" style="flex: 1">
                    <div class="card-header p-2">
                        <div class='m-0'>Business</div>
                    </div>
                    <div class="card-body p-3">
                        <div class="mb-3">
                            <label class="required">Business Legal Name:</label>
                            <input type="text" maxlength="50" class="form-control"
                                id="busi_legal_nm" name="busi_legal_nm"
                                placeholder=""
                                value=""
                                required
                            />
                        </div>
                        <div class="mb-3">
                            <label class="required">Business Trading Name:</label>
                            <input type="text" maxlength="50" class="form-control"
                                id="busi_trad_nm" name="busi_trad_nm"
                                placeholder=""
                                value=""
                                required
                            />
                        </div>
                        <div class="mb-3">
                            <label class="required">Business Start Date:</label>
                            <input type="text" pattern="\d{2}/\d{2}/\d{4}" class="form-control datepicker"
                                id="busi_start_dt" name="busi_start_dt"
                                placeholder=""
                                value=""
                                required
                            />
                        </div>
                        <div class="mb-3">
                            <label for="prefered_branch" class="">Preferred Branch:</label>
                            <select class="form-select" id="prefered_branch" name="prefered_branch" required>
                                <option value="" selected></option>
                                <?php foreach ($all_branches as $branch_name) : ?>
                                    <option value="<?= esc($branch_name) ?>"><?= esc($branch_name) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <div class="invalid-feedback">Please select a branch.</div>
                        </div>
                        <div class="form-check form-switch form-check mb-3">
                            <input class="form-check-input confirm_legal_owner_director"
                                   style="position: absolute"
                                   type="checkbox" id="confirm_legal_owner_director"
                                   value="confirm_legal_owner_director" required/>
                            <label class="form-check-label ps-2 break-over-word"
                                   for="confirm_legal_owner_director"
                                   style="margin-left: 32px !important;">I confirm I am the Legal Owner or Director</label>
                            <div class="invalid-feedback">You must agree to this option setting.</div>
                        </div>
                        <div class="mb-3">
                            <label class="required">Address Line 1:</label>
                            <input type="text" maxlength="39" class="form-control"
                                id="addr_line1" name="addr_line1"
                                placeholder=""
                                value=""
                                required
                            />
                        </div>
                        <div class="mb-3">
                            <label class="">Address Line 2:</label>
                            <input type="text" maxlength="30" class="form-control"
                                id="addr_line2" name="addr_line2"
                                placeholder=""
                                value=""
                            />
                        </div>
                        <div class="mb-3">
                            <label class="required">County:</label>
                            <input type="text" maxlength="25" class="form-control"
                                id="county" name="county"
                                placeholder=""
                                value=""
                                required
                            />
                        </div>
                        <div class="mb-3">
                            <label class="required">City:</label>
                            <input type="text" maxlength="25" class="form-control"
                                id="city" name="city"
                                placeholder=""
                                value=""
                                required
                            />
                        </div>
                        <div class="mb-3">
                            <label class="required">Country:</label>
                            <select class="form-select" id="country" name="country" required>
                                <option value="" selected></option>
                                <option value="England">England</option>
                                <option value="Northern Ireland">Northern Ireland</option>
                                <option value="Scotland">Scotland</option>
                                <option value="Wales">Wales</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="required">Post Code:</label>
                            <input type="text" maxlength="8" class="form-control"
                                id="post_code" name="post_code"
                                placeholder=""
                                value=""
                                required
                            />
                        </div>
                    </div>
                </div>
                <div class="customer-reg-info card full-width-on-mobile" style="flex: 1">
                    <div class="card-header p-2">
                        <div class='m-0'>Owner/Director</div>
                    </div>
                    <div class="card-body p-3">
                        <div class="mb-3">
                            <label class="required">Contact Name:</label>
                            <input type="text" maxlength="30" class="form-control"
                                id="contact_nm" name="contact_nm"
                                placeholder=""
                                value=""
                                required
                            />
                        </div>
                        <div class="mb-3">
                            <label class="">Contact Telephone Landline:</label>
                            <input type="number" max="100000000000" class="form-control"
                                id="contact_phone_ll" name="contact_phone_ll"
                                placeholder=""
                                value=""
                            />
                            <div class="invalid-feedback">
                                Please provide a number of less than 11-digits.
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="required">Contact Telephone Mobile:</label>
                            <input type="number" max="100000000000" class="form-control"
                                id="contact_phone_mb" name="contact_phone_mb"
                                placeholder=""
                                value=""
                                required
                            />
                            <div class="invalid-feedback">
                                Please provide a number of less than 11-digits.
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="required">Contact email adresss:</label>
                            <input type="email" maxlength="60" class="form-control"
                                id="contact_email" name="contact_email"
                                placeholder=""
                                value=""
                                required
                            />
                            <div class="invalid-feedback">
                                Please provide a email type.
                            </div>
                        </div>
                        <div class="d-flex mb-3" style="gap: 10px;">
                            <div style="flex: 0 0 35%;">
                                <label class="required">House Number:</label>
                                <input type="text" maxlength="5" pattern="\d{1,5}" class="form-control"
                                    id="owner_house_no" name="owner_house_no"
                                    placeholder="" value="" required
                                />
                                <div class="invalid-feedback">Up to 5 digits.</div>
                            </div>
                            <div style="flex: 1;">
                                <label>House Name/Flat:</label>
                                <input type="text" maxlength="20" class="form-control"
                                    id="owner_house_name" name="owner_house_name"
                                    placeholder="" value=""
                                />
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="required">Street:</label>
                            <input type="text" maxlength="30" pattern="[A-Za-z0-9 ]+" class="form-control"
                                id="owner_street" name="owner_street"
                                placeholder="" value="" required
                            />
                            <div class="invalid-feedback">Up to 30 characters, letters/numbers/spaces only.</div>
                        </div>
                        <div class="mb-3">
                            <label class="required">Village/Town:</label>
                            <input type="text" maxlength="30" pattern="[A-Za-z0-9 ]+" class="form-control"
                                id="owner_village" name="owner_village"
                                placeholder="" value="" required
                            />
                            <div class="invalid-feedback">Up to 30 characters, letters/numbers/spaces only.</div>
                        </div>
                        <div class="mb-3">
                            <label class="required">City:</label>
                            <input type="text" maxlength="30" pattern="[A-Za-z0-9 ]+" class="form-control"
                                id="owner_city" name="owner_city"
                                placeholder="" value="" required
                            />
                            <div class="invalid-feedback">Up to 30 characters, letters/numbers/spaces only.</div>
                        </div>
                        <div class="mb-3">
                            <label class="required">Country:</label>
                            <select class="form-select" id="owner_country" name="owner_country" required>
                                <option value="" selected></option>
                                <option value="England">England</option>
                                <option value="Northern Ireland">Northern Ireland</option>
                                <option value="Scotland">Scotland</option>
                                <option value="Wales">Wales</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="required">Post Code:</label>
                            <input type="text" maxlength="9" pattern="[A-Za-z0-9 ]+" class="form-control"
                                id="owner_post_code" name="owner_post_code"
                                placeholder="" value="" required
                            />
                            <div class="invalid-feedback">Up to 9 characters, letters/numbers/spaces only.</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="d-flex2 justify-content-between" style="gap: 10px">
                <div class="customer-reg-info card full-width-on-mobile" style="flex: 1">
                    <div class="card-header p-2">
                        <div class='m-0'>Company</div>
                    </div>
                    <div class="card-body p-3">
                        <div class="mb-3">
                            <label class="required break-over-word">For how many years has the business been trading?</label>
                            <input type="number" max="100" class="form-control"
                                id="busi_trad_years" name="busi_trad_years"
                                placeholder=""
                                value=""
                                required
                            />
                            <div class="invalid-feedback">
                                Please provide a number of less than 2-digits.
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="">VAT Number:</label>
                            <input type="number" max="10000000000" class="form-control"
                                id="vat_number" name="vat_number"
                                placeholder=""
                                value=""
                            />
                            <div class="invalid-feedback">
                                Please provide a number of less than 10-digits.
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="">Company Number:</label>
                            <input type="text" maxlength="12" class="form-control"
                                id="company_no" name="company_no"
                                placeholder=""
                                value=""
                            />
                        </div>
                    </div>
                </div>
                <div class="customer-reg-info card full-width-on-mobile" style="flex: 1">
                    <div class="card-header p-2">
                        <div class='m-0'>Store</div>
                    </div>
                    <div class="card-body p-3">
                        <div class="mb-3">
                            <label class="required">Store size in square feet?</label>
                            <input type="number" max="100000" class="form-control"
                                id="store_sz" name="store_sz"
                                placeholder=""
                                value=""
                                required
                            />
                            <div class="invalid-feedback">
                                Please provide a number of less than 5-digits.
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="required">Store average turnover weekly?</label>
                            <input type="number" max="100000000" class="form-control"
                                id="store_avg" name="store_avg"
                                placeholder=""
                                value=""
                                required
                            />
                            <div class="invalid-feedback">
                                Please provide a number of less than 8-digits.
                            </div>
                        </div>
                        <div class="form-check form-switch mb-3 d-flex">
                            <input class="form-check-input self-service" type="checkbox" id="self_service" />
                            <label class="form-check-label ps-2 break-over-word" for="self_service">I will visit the depot to purchase goods</label>
                        </div>
                        <div class="form-check form-switch mb-3 d-flex">
                            <input class="form-check-input click-and-collect" type="checkbox" id="click_and_collect" />
                            <label class="form-check-label ps-2 break-over-word" for="click_and_collect">I will order online then come in to collect goods</label>
                        </div>
                        <div class="form-check form-switch mb-3 d-flex">
                            <input class="form-check-input delivered" type="checkbox" id="delivered" />
                            <label class="form-check-label ps-2 break-over-word" for="delivered">I will order online and require a delivery of goods</label>
                        </div>
                        <div class="form-check form-switch mb-3 d-flex">
                            <input class="form-check-input offers-and-info" type="checkbox" id="offers_and_info" />
                            <label class="form-check-label ps-2 break-over-word" for="offers_and_info">Do you wish to receive marketing offers and info?</label>
                        </div>
                        <div id="marketing-options-container" class="ps-4 mb-3" style="display: none;">
                            <div style="display: flex">
                                <div style="margin-left: 15px;padding-right: 10px">with:</div>
                                <div class="form-check mb-2" style="padding-right: 35px">
                                    <input class="form-check-input marketing-option" type="checkbox" id="marketing_post" name="marketing_post" value="1" checked />
                                    <label class="form-check-label" for="marketing_post">Post</label>
                                </div>
                                <div class="form-check mb-2" style="padding-right: 35px">
                                    <input class="form-check-input marketing-option" type="checkbox" id="marketing_email" name="marketing_email" value="1" checked />
                                    <label class="form-check-label" for="marketing_email">eMail</label>
                                </div>
                                <div class="form-check mb-2" style="padding-right: 10px">
                                    <input class="form-check-input marketing-option" type="checkbox" id="marketing_sms" name="marketing_sms" value="1" checked />
                                    <label class="form-check-label" for="marketing_sms">SMS</label>
                                </div>
                            </div>
                            <div style="display: flex">
                                <div class="form-check mb-2" style="margin-left: 60px; padding-right: 10px">
                                    <input class="form-check-input marketing-option" type="checkbox" id="marketing_messaging" name="marketing_messaging" value="1" checked />
                                    <label class="form-check-label" for="marketing_messaging">Messaging Platforms</label>
                                </div>
                                <div class="form-check mb-2">
                                    <input class="form-check-input marketing-option" type="checkbox" id="marketing_telephone" name="marketing_telephone" value="1" checked />
                                    <label class="form-check-label" for="marketing_telephone">Telephone</label>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
            <div class="d-flex2 justify-content-between" style="gap: 10px">
                <div class="customer-reg-info card full-width-on-mobile" style="flex: 1">
                    <div class="card-header p-2">
                        <div class='m-0'>Sell</div>
                    </div>
                    <div class="card-body p-3">
                        <ul style="list-style: none;">
                            <li class="form-check form-switch form-check mb-3">
                                <input class="form-check-input sell-alcohol" type="checkbox" id="alcohol" value="alcohol" />
                                <label class="form-check-label ps-2" for="alcohol">Do you sell Alcohol?</label>
                            </li>
                            <li class="mb-3" id="premises-licence-container" style="display: none;">
                                <label class="form-label" for="premises_licence">Premises Licence:</label>
                                <input type="text" class="form-control" id="premises_licence" name="premises_licence" maxlength="50" placeholder="" />
                                <div class="invalid-feedback">
                                    Please input premises licence.
                                </div>
                            </li>
                            <li class="form-check form-switch form-check mb-3">
                                <input class="form-check-input sell-tobacco" type="checkbox" id="tobacco" value="tobacco" />
                                <label class="form-check-label ps-2" for="tobacco">Do you sell Tobacco?</label>
                            </li>
                            <li class="mb-3" id="tobacco-fields-container" style="display: none;">
                                <div class="mb-3">
                                    <label class="form-label" for="eoid">Your EOID:</label>
                                    <input type="text" class="form-control" id="eoid" name="eoid" maxlength="20" placeholder="" />
                                    <div class="invalid-feedback">EOID is required and must begin with QC. Please enter it exactly as it is supplied. If you do not have one, please request one for free at <a href="https://idissuer.uk-trackandtrace-dentsutracking.com/landing/landing-menu" target="_blank" style="color: #2196F3 !important;">https://idissuer.uk-trackandtrace-dentsutracking.com/landing/landing-menu</a>. </div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="fid">Your FID:</label>
                                    <input type="text" class="form-control" id="fid" name="fid" maxlength="20" placeholder="" />
                                    <div class="invalid-feedback">FID is required and must begin with QC. Please enter it exactly as it is supplied. It is unique per address. If you do not have one, please request one for free at <a href="https://idissuer.uk-trackandtrace-dentsutracking.com/landing/landing-menu" target="_blank" style="color: #2196F3 !important;">https://idissuer.uk-trackandtrace-dentsutracking.com/landing/landing-menu</a>.</div>
                                </div>
                            </li>
                            <li class="form-check form-switch form-check mb-3">
                                <input class="form-check-input sell-vapes" type="checkbox" id="vapes" value="vapes" />
                                <label class="form-check-label ps-2" for="vapes">Do you sell Vapes?</label>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="customer-reg-info card full-width-on-mobile" style="flex: 1">
                    <div class="card-header p-2">
                        <div class='m-0'>Payment & Offer</div>
                    </div>
                    <div class="card-body p-3">
                        <div class="mb-3">
                            <label class="break-over-word">What is your prefered payment method? </label>
                            <select class="form-select" name="pref_payment_method" id="pref_payment_method" required>
                                    <option value=""></option>
                                    <option value="cash">Cash</option>
                                    <option value="bank_transfer">Bank Transfer</option>
                                    <option value="echo_pay">EchoPay</option>
                                    <option value="card">Card</option>
                                    <option value="credit_facility">Credit Facility</option>
                            </select>
                            <div class="invalid-feedback">
                                Please provide at least one item.
                            </div>
                        </div>
                        <div class="form-check form-switch mb-3 d-flex">
                            <input class="form-check-input credit-acc-facility" type="checkbox" id="credit_acc_facility" />
                            <label class="form-check-label ps-2 break-over-word" for="credit_acc_facility">Do you require a credit account facility?</label>
                        </div>
                        <div class="mb-3" id="credit_limit_row" style="display: none;">
                            <label class="required">Required Credit Limit £'s:</label>
                            <input type="number" min="0" max="9999999" maxlength="7" class="form-control"
                                id="credit_limit" name="credit_limit"
                                placeholder="" value=""
                            />
                            <div class="invalid-feedback">Up to 7 digits.</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="d-flex justify-content-center mt-4">
                <div id="recaptcha-container"></div>
            </div>
            <div class="d-flex justify-content-center mt-4 gap-10px">
                <button type="submit" class="btn btn-info" id="btn_customer_save" style="min-width: 120px" data-is-submitted="false">Submit request</button>
                <!-- <button type="button" class="btn btn-secondary" id="btn-new-action" style="min-width: 120px">PDF Send</button> -->
                <button type="button" class="btn btn-danger" id="btn-go-back" style="min-width: 120px">Go Back</button>
            </div>
        </form>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('javascript') ?>
<script>
    const emailRegex = /^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,})$/;

    (function () {
        'use strict'

        // Fetch all the forms we want to apply custom Bootstrap validation styles to
        var forms = document.querySelectorAll('.needs-validation')

        // Loop over them and prevent submission
        Array.prototype.slice.call(forms)
            .forEach(function (form) {
                form.addEventListener('submit', function (event) {
                    {// email special validator including tld or ccld

                        // If the form is valid according to browser's built-in validation,
                        // then apply custom regex validation for email.
                        const emailInput = document.getElementById('contact_email');

                        if(!emailRegex.test(emailInput.value)) {
                            emailInput.classList.add('is-invalid');
                            emailInput.setCustomValidity('Please provide a email type.'); // marks as invalid
                            // emailInput.reportValidity(); // triggers UI and updates :invalid

                            event.preventDefault();
                            // event.stopPropagation();
                        } else {
                            emailInput.classList.remove('is-invalid');
                            emailInput.setCustomValidity(''); // marks as valid
                        }
                    }
                    {// premises licence special validator including the premises licence is valid
                        const premisesLicenceInput = document.getElementById('premises_licence');
                        const alcoholCheckbox = document.getElementById('alcohol');
                        const countrySelect = document.getElementById('country');
                        const selectedCountry = countrySelect ? countrySelect.value : '';
                        const isScotland = selectedCountry && selectedCountry.toLowerCase().includes('scotland');
                        const isAlcoholChecked = alcoholCheckbox && alcoholCheckbox.checked;
                        
                        if (isScotland && isAlcoholChecked) {
                            if (!premisesLicenceInput.value.trim()) {
                                premisesLicenceInput.classList.add('is-invalid');
                                premisesLicenceInput.setCustomValidity('Premises Licence is required for Scotland.');
                                event.preventDefault();
                            } else {
                                premisesLicenceInput.classList.remove('is-invalid');
                                premisesLicenceInput.setCustomValidity('');
                            }
                        } else {
                            premisesLicenceInput.classList.remove('is-invalid');
                            premisesLicenceInput.setCustomValidity('');
                        }
                    }
                    {// eoid validator including the eoid and fid is valid
                        const tobaccoCheckbox = document.getElementById('tobacco');
                        const isTobaccoChecked = tobaccoCheckbox && tobaccoCheckbox.checked;
                        const eoidInput = document.getElementById('eoid');
                        if (isTobaccoChecked) {
                            const eoidRegex = /^(?:QCUKT|QCGDLR)[A-Za-z0-9]{5,10}$/i;

                            if (!eoidInput.value.trim()) {
                                eoidInput.classList.add('is-invalid');
                                eoidInput.setCustomValidity('EOID is required.');
                                event.preventDefault();
                            } else if (!eoidRegex.test(eoidInput.value.trim())) {
                                eoidInput.classList.add('is-invalid');
                                eoidInput.setCustomValidity('EOID is required and must begin with QC. Please enter it exactly as it is supplied. If you do not have one, please request one for free at <a href="https://idissuer.uk-trackandtrace-dentsutracking.com/landing/landing-menu" target="_blank" style="color: #2196F3 !important;">https://idissuer.uk-trackandtrace-dentsutracking.com/landing/landing-menu</a>. ');
                                event.preventDefault();
                            } else {
                                eoidInput.classList.remove('is-invalid');
                                eoidInput.setCustomValidity('');
                            }
                        } else {
                            eoidInput.classList.remove('is-invalid');
                            eoidInput.setCustomValidity('');
                        }
                    }
                    {// fid validator including the fid is valid
                        const tobaccoCheckbox = document.getElementById('tobacco');
                        const isTobaccoChecked = tobaccoCheckbox && tobaccoCheckbox.checked;
                        const fidInput = document.getElementById('fid');
                        if (isTobaccoChecked) {
                            const fidRegex = /^(?:QCUKT|QCGDLR)[A-Za-z0-9]{5,10}$/i;
                            if (!fidInput.value.trim()) {
                                fidInput.classList.add('is-invalid');
                                fidInput.setCustomValidity('FID is required.');
                                event.preventDefault();
                            } else if (!fidRegex.test(fidInput.value.trim())) {
                                fidInput.classList.add('is-invalid');
                                fidInput.setCustomValidity('FID is required and must begin with QC. Please enter it exactly as it is supplied. It is unique per address. If you do not have one, please request one for free at <a href="https://idissuer.uk-trackandtrace-dentsutracking.com/landing/landing-menu" target="_blank" style="color: #2196F3 !important;">https://idissuer.uk-trackandtrace-dentsutracking.com/landing/landing-menu</a>.');
                                event.preventDefault();
                            } else {
                                fidInput.classList.remove('is-invalid');
                                fidInput.setCustomValidity('');
                            }
                        } else {
                            fidInput.classList.remove('is-invalid');
                            fidInput.setCustomValidity('');
                        }
                    }
                    /*
                    {// datepicker special validator including the date is valid
                        // If the form is valid according to browser's built-in validation,
                        // then apply valid date for datepicker.
                        const dateInput = document.getElementById('busi_start_dt');

                        const parts = dateInput.value.split('/');
                        const day   = parseInt(parts[0], 10);
                        const month = parseInt(parts[1], 10);
                        const year  = parseInt(parts[2], 10);

                        const date = new Date(year, month - 1, day); // Month is 0-indexed
                        if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
                            dateInput.classList.add('is-invalid');
                            dateInput.setCustomValidity('Please provide a email type.'); // marks as invalid
                            // emailInput.reportValidity(); // triggers UI and updates :invalid

                            event.preventDefault();
                        } else {
                            dateInput.classList.remove('is-invalid');
                            dateInput.setCustomValidity(''); // marks as valid
                        }
                    }*/
                    if (!form.checkValidity()) {
                        event.preventDefault()
                        event.stopPropagation()
                    } 

                    form.classList.add('was-validated');

                }, false)
            })
    })()

    $(document).ready(function(e) {
        $('#busi_start_dt').datepicker({
            uiLibrary: 'bootstrap5',
            iconsLibrary: 'fontawesome',
            format: 'dd/mm/yyyy',
            autoclose: true,
            todayHighlight: true
        })

        // Credit limit only relevant when the credit-facility toggle is on.
        // Clear the value on toggle-off so a stale number isn't submitted.
        const $creditLimitRow   = $('#credit_limit_row');
        const $creditLimitInput = $('#credit_limit');
        $(document).on('change', '#credit_acc_facility', function() {
            if ($(this).is(':checked')) {
                $creditLimitRow.show();
                $creditLimitInput.prop('required', true);
            } else {
                $creditLimitRow.hide();
                $creditLimitInput.prop('required', false).val('');
            }
        });
        const $extra = $(`<div class="invalid-feedback">
                            Please enter a valid date in 'dd/mm/yyyy' format.'.
                        </div>`);
        $('.gj-datepicker-bootstrap').append($extra); // jQuery handles all matched elements

        $(document).on('keyup', '#contact_email', function(e) {
            if(!$('form#customer_register_form').hasClass('was-validated'))
                return;
            if (emailRegex.test(e.target.value)) {
                this.classList.remove('is-invalid');
                this.classList.add('is-valid');
                this.setCustomValidity(''); // marks as invalid
            } else {
                this.classList.remove('is-valid');
                this.classList.add('is-invalid');
                this.setCustomValidity('Please provide a email type.'); // marks as invalid
            }
        })

        $(document).on('keyup', '#busi_start_dt', function(e) {
            if(!$('form#customer_register_form').hasClass('was-validated'))
                return;
            const dateInput = document.getElementById('busi_start_dt');

            const parts = dateInput.value.split('/');
            const day   = parseInt(parts[0], 10);
            const month = parseInt(parts[1], 10);
            const year  = parseInt(parts[2], 10);

            const date = new Date(year, month - 1, day); // Month is 0-indexed
            if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
                dateInput.classList.add('is-invalid');
                dateInput.setCustomValidity('Please provide a email type.'); // marks as invalid
                // emailInput.reportValidity(); // triggers UI and updates :invalid

                event.preventDefault();
            } else {
                dateInput.classList.remove('is-invalid');
                dateInput.setCustomValidity(''); // marks as valid
            }
        })

        // Show/hide Premises Licence field based on alcohol checkbox and Scotland branch
        function togglePremisesLicence() {
            const isAlcoholChecked = $('#alcohol').is(':checked');
            const selectedCountry = $('#country').val();
            const isScotland = selectedCountry && selectedCountry.toLowerCase().includes('scotland');
            
            if (isAlcoholChecked && isScotland) {
                $('#premises-licence-container').show();
                // Set premises licence value to current country value
                const countryValue = $('#country').val();
                if (countryValue && !$('#premises_licence').val().trim()) {
                    // $('#premises_licence').val(countryValue);
                }
                if($('#customer_register_form').hasClass('was-validated')) {
                    if($('#premises_licence').val().trim()) {
                        $('#premises_licence').addClass('is-valid');
                        $('#premises_licence').removeClass('is-invalid');
                    } else {
                        $('#premises_licence').addClass('is-invalid');
                        $('#premises_licence').removeClass('is-valid');
                        // Trigger delete keyup event on premises licence input
                        $('#premises_licence').trigger($.Event('keyup', { keyCode: 46, which: 46, key: 'Delete' }));
                    }
                }
            } else {
                $('#premises-licence-container').hide();
                $('#premises_licence').val(''); // Clear the value when hidden
            }
        }

        // Listen for alcohol checkbox change
        $(document).on('change', '#alcohol', function() {
            togglePremisesLicence();
        });

        // Listen for branch select change
        $(document).on('change', '#country', function() {
            togglePremisesLicence();
        });

        // Listen for country select change - update premises licence if visible
        $(document).on('change', '#country', function() {
            if ($('#premises-licence-container').is(':visible')) {
                $('#premises_licence').val($(this).val());
            }
        });

        // Show/hide marketing options when offers_and_info checkbox is changed
        $(document).on('change', '#offers_and_info', function() {
            if ($(this).is(':checked')) {
                $('#marketing-options-container').show();
                // Check all 5 marketing options when toggle is turned on
                $('.marketing-option').prop('checked', true);
            } else {
                $('#marketing-options-container').hide();
            }
        });

        $(document).on('keyup', '#premises_licence', function(e) {
            if(!$('form#customer_register_form').hasClass('was-validated'))
                return;
            if (e.target.value.trim()) {
                this.classList.remove('is-invalid');
                this.classList.add('is-valid');
                this.setCustomValidity(''); // marks as invalid
            } else {
                this.classList.remove('is-valid');
                this.classList.add('is-invalid');
                this.setCustomValidity('Please provide a premises licence.'); // marks as invalid
            }
        })

        // Show/hide EOID and FID fields based on tobacco checkbox
        function toggleTobaccoFields() {
            const isTobaccoChecked = $('#tobacco').is(':checked');
            
            if (isTobaccoChecked) {
                $('#tobacco-fields-container').show();
                if($('#customer_register_form').hasClass('was-validated')) {
                    if($('#eoid').val().trim()) {
                        $('#eoid').addClass('is-valid');
                        $('#eoid').removeClass('is-invalid');
                    } else {
                        $('#eoid').addClass('is-invalid');
                        $('#eoid').removeClass('is-valid');
                        // Trigger delete keyup event on eoid input
                        $('#eoid').trigger($.Event('keyup', { keyCode: 46, which: 46, key: 'Delete' }));
                    }
                    if($('#fid').val().trim()) {
                        $('#fid').addClass('is-valid');
                        $('#fid').removeClass('is-invalid');
                    } else {
                        $('#fid').addClass('is-invalid');
                        $('#fid').removeClass('is-valid');
                        // Trigger delete keyup event on fid input
                        $('#fid').trigger($.Event('keyup', { keyCode: 46, which: 46, key: 'Delete' }));
                    }
                }
            } else {
                $('#tobacco-fields-container').hide();
                $('#eoid').val('')
                $('#fid').val('')
            }
        }

        // Listen for tobacco checkbox change
        $(document).on('change', '#tobacco', function() {
            toggleTobaccoFields();
        });

        // EOID validation - must match pattern: ^(?:QCUKTE|QCGDLRE)[A-Z0-9]{5,10}$
        function validateEOID(value) {
            if (!value || value.trim() === '') return true; // Allow empty
            const eoidRegex = /^(?:QCUKT|QCGDLR)[A-Za-z0-9]{5,10}$/i;
            return eoidRegex.test(value.trim());
        }

        // FID validation - must match pattern: ^(?:QCUKTF|QCGDLRF)[A-Z0-9]{5,10}$
        function validateFID(value) {
            if (!value || value.trim() === '') return true; // Allow empty
            const fidRegex = /^(?:QCUKT|QCGDLR)[A-Za-z0-9]{5,10}$/i;
            return fidRegex.test(value.trim());
        }

        // Validate EOID on input and convert to uppercase
        $(document).on('keyup', '#eoid', function(e) {
            // Convert to uppercase
            const upperValue = e.target.value;//.toUpperCase();
            // $(this).val(upperValue);
            
            if(!$('form#customer_register_form').hasClass('was-validated'))
                return;

            if (!upperValue.trim()) {
                this.addClass('is-invalid').removeClass('is-valid');
                this.setCustomValidity('EOID is required.');
            } else if (!validateEOID(upperValue)) {
                this.addClass('is-invalid').removeClass('is-valid');
                this.setCustomValidity('EOID is required and must begin with QC. Please enter it exactly as it is supplied. If you do not have one, please request one for free at <a href="https://idissuer.uk-trackandtrace-dentsutracking.com/landing/landing-menu" target="_blank" style="color: #2196F3 !important;">https://idissuer.uk-trackandtrace-dentsutracking.com/landing/landing-menu</a>. ');
            } else {
                this.addClass('is-valid').removeClass('is-invalid');
                this.setCustomValidity(''); // marks as valid
            }
            
        });

        // Validate FID on input and convert to uppercase
        $(document).on('keyup', '#fid', function(e) {
            // Convert to uppercase
            const upperValue = e.target.value;//.toUpperCase();
            // $(this).val(upperValue);
            
            if(!$('form#customer_register_form').hasClass('was-validated'))
                return;

            if (!upperValue.trim()) {
                this.addClass('is-invalid').removeClass('is-valid');
                this.setCustomValidity('FID is required.');
            } else if (!validateFID(upperValue)) {
                this.addClass('is-invalid').removeClass('is-valid');
                this.setCustomValidity('FID is required and must begin with QC. Please enter it exactly as it is supplied. It is unique per address. If you do not have one, please request one for free at <a href="https://idissuer.uk-trackandtrace-dentsutracking.com/landing/landing-menu" target="_blank" style="color: #2196F3 !important;">https://idissuer.uk-trackandtrace-dentsutracking.com/landing/landing-menu</a>.');
            } else {
                this.setCustomValidity(''); // marks as valid
                this.addClass('is-valid').removeClass('is-invalid');
            }
        });

        // Google reCAPTCHA setup
        var recaptchaWidgetId;
        var recaptchaSiteKey = '<?= esc($recaptcha_site_key ?? env('RECAPTCHA_SITE_KEY', '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI')) ?>';
        
        // Load reCAPTCHA script dynamically
        var recaptchaScript = document.createElement('script');
        recaptchaScript.src = 'https://www.google.com/recaptcha/api.js?onload=onRecaptchaLoad&render=explicit';
        recaptchaScript.async = true;
        recaptchaScript.defer = true;
        document.head.appendChild(recaptchaScript);
        
        // Callback when reCAPTCHA is loaded
        window.onRecaptchaLoad = function() {
            recaptchaWidgetId = grecaptcha.render('recaptcha-container', {
                'sitekey': recaptchaSiteKey,
                'callback': onRecaptchaSuccess,
                'expired-callback': onRecaptchaExpired,
                'error-callback': onRecaptchaError
            });
        };
        
        // Callback when user successfully completes reCAPTCHA
        window.onRecaptchaSuccess = function(response) {
            // no-op for button state; backend will validate
        };
        
        // Callback when reCAPTCHA expires
        window.onRecaptchaExpired = function() {
            // no-op for button state; backend will validate
        };
        
        // Callback when reCAPTCHA encounters an error
        window.onRecaptchaError = function() {
            // no-op for button state; backend will validate
        };

        $(document).on('click', '#btn-go-back', function(e) {
            // No spinner, just navigate back to login
            window.location.href = '/login';
        })

        $(document).on('submit', 'form#customer_register_form', function(e) {
            e.preventDefault();

            const $form = $(e.target);

            // 1) Let built-in and custom validators run first (see needs-validation handler above).
            // If the form is invalid at this point, do not run captcha or submit logic.
            if (!$form[0].checkValidity()) {
                return;
            }

            // Get reCAPTCHA response token
            let recaptchaResponse = '';
            if (typeof grecaptcha !== 'undefined' && recaptchaWidgetId != null) {
                recaptchaResponse = grecaptcha.getResponse(recaptchaWidgetId);
            }
            if (!recaptchaResponse) {
                var $captcha = $('#recaptcha-container');
                $captcha.addClass('shake');
                setTimeout(function () {
                    $captcha.removeClass('shake');
                }, 500);

                remove_loadingSpinner_from_button(e.target);
                return;
            }

            // 2) Now require captcha before submitting
            // Mark that submit was attempted (no disabling of buttons)
            $('#btn_customer_save').data('is-submitted', true);

            //  credit account facility
            let credit_acc_facility = "";
            if ($form.find("input.credit-acc-facility:checked").length > 0) {
                credit_acc_facility = 1
            }
            
            //  offers and info
            let offers_and_info = "";
            if ($form.find("input.offers-and-info:checked").length > 0) {
                offers_and_info = 1
            }

            //  self service
            let self_service = "";
            if ($form.find("input.self-service:checked").length > 0) {
                self_service = 1
            }

            //  click and collect
            let click_and_collect = "";
            if ($form.find("input.click-and-collect:checked").length > 0) {
                click_and_collect = 1
            }

            //  delivered
            let delivered = "";
            if ($form.find("input.delivered:checked").length > 0) {
                delivered = 1
            }

            //  confirm legal owner or director
            let confirm_legal_owner_director = "";
            if ($form.find("input.confirm_legal_owner_director:checked").length > 0) {
                confirm_legal_owner_director = 1
            }

            //  sell alcohol
            let sell_alcohol = "";
            if ($form.find("input.sell-alcohol:checked").length > 0) {
                sell_alcohol = 1
            }
            //  sell tobacco
            let sell_tobacco = "";
            if ($form.find("input.sell-tobacco:checked").length > 0) {
                sell_tobacco = 1
            }
            //  sell vapes
            let sell_vapes = "";
            if ($form.find("input.sell-vapes:checked").length > 0) {
                sell_vapes = 1
            }

            const dt = $("#customer_register_form").serialize();
            const params = new URLSearchParams(dt);
            let payload = Object.fromEntries(params.entries());
            //  premises licence
            let premises_licence = "";
            if (payload && payload.country && payload.country.toLowerCase().includes('scotland') && sell_alcohol == 1) {
                premises_licence = payload.premises_licence;
            }

            // eoid and fid
            let eoid = "";
            let fid = "";
            if (payload && sell_tobacco == 1) {
                eoid = payload.eoid;
                fid = payload.fid;
            }

            

            // marketing options
            let marketing_options = [];
            if (payload && payload.marketing_post) {
                marketing_options.push('post');
                delete payload.marketing_post;
            }
            if (payload && payload.marketing_email) {
                marketing_options.push('email');
                delete payload.marketing_email;
            }
            if (payload && payload.marketing_sms) {
                marketing_options.push('sms');
                delete payload.marketing_sms;
            }
            if (payload && payload.marketing_messaging) {
                marketing_options.push('messaging');
                delete payload.marketing_messaging;
            }
            if (payload && payload.marketing_telephone) {
                marketing_options.push('telephone');
                delete payload.marketing_telephone;
            }
            let marketing_options_str = marketing_options.join(',');

            payload = {
                ...payload,
                'g-recaptcha-response':         recaptchaResponse,
                credit_acc_facility:            credit_acc_facility,
                offers_and_info:                offers_and_info,
                marketing_options:              marketing_options_str,
                self_service:                   self_service,
                click_and_collect:              click_and_collect,
                delivered:                      delivered,
                confirm_legal_owner_director:   confirm_legal_owner_director,
                sell_alcohol:                   sell_alcohol,
                sell_tobacco:                   sell_tobacco,
                sell_vapes:                     sell_vapes,
                premises_licence:               premises_licence,
                eoid:                           eoid,
                fid:                            fid
            }
            console.log(payload);
            $.ajax({
                type: "POST"
                , async: true
                , url: "/customer-register"
                , dataType: "json"
                , timeout: 30000
                , cache: false
                , data: payload
                , error: function (xhr, status, error) {
                        remove_loadingSpinner_from_button(e.target);
                        $('#btn-go-back').prop('disabled', false);

                        // Reset reCAPTCHA and disable submit button
                        if (typeof grecaptcha !== 'undefined') {
                            grecaptcha.reset(recaptchaWidgetId);
                            $('#btn_customer_save').prop('disabled', true);
                        }

                        $alert_message = 'An error occurred in Customer Registration API call. Code 4000';
                        $alert_message += '\n' + xhr.responseJSON.message;
                        alert_message($alert_message, 'Error', 'customer-register-form-modal');

                    }
                , success: function (response, status, request) {
                    if (response.success == 1) {
                        // $alert_message = 'Application received, \nWe\'ve emailed you a secure link to complete the final step. \nPlease review and sign our Terms and Conditions and upload the documents needed to open your account.';
                        
                        // alert_message($alert_message, 'Info', 'customer-register-form-modal', function(e){
                        //     location.reload();
                        //     window.scrollTo({ top: 0, behavior: 'smooth' });
                        // });
                        window.location.href = '/customer/confirm/' + response.base64_token;
                    } else {
                        remove_loadingSpinner_from_button(e.target);
                        $('#btn-go-back').prop('disabled', false);

                        // Reset reCAPTCHA and disable submit button
                        if (typeof grecaptcha !== 'undefined') {
                            grecaptcha.reset(recaptchaWidgetId);
                            $('#btn_customer_save').prop('disabled', true);
                        }
                        alert_message(response.error, 'Error', 'customer-register-form-modal');
                    }
                }
            });
        })
    })
</script>
<?= $this->endSection() ?>
