<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Merchant Sign Up</title>
    <!-- Bootstrap CSS -->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .signup-form {
            max-width: 400px;
            margin: 50px auto;
            padding: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, .1);
        }
    </style>
</head>
<body>

<div class="signup-form">
    <h2 class="text-center">Merchant Sign Up</h2>
    @include('commons.notifications')
    <form action="{{ url('merchant/register') }}" id="registerForm" method="POST">
        {{ csrf_field() }}

        <div class="form-group">
            <label for="fullname">Fullname</label>
            <input type="text" class="form-control" name="fullname" id="fullname" required>
        </div>
        <div class="form-group">
            <label for="phone">Phone</label>
            <input type="text" class="form-control" name="phone" id="phone" required>
        </div>
        <div class="form-group">
            <label for="language">Language</label>
            <select class="form-control" id="language" name="language" required>
                <option disabled selected>-- Select--</option>
                <option value="chichewa">Chichewa</option>
                <option value="english">English</option>
            </select>
        </div>
        
        <button type="submit" class="btn btn-primary btn-block">Sign Up</button>
    </form>
    <p class="text-center mt-3">Already have an account? <a href="{{ url('merchant/login') }}">Login here</a></p>
</div>

<!-- Bootstrap JS and dependencies -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script>
    $(document).ready(function() {
        var phoneInputField = document.querySelector("#phone");
        var errorMsg = $("#phone-error");
        var formGroup = $("#phone").closest('.form-group');
        var submitBtn = $('#loginForm button[type="submit"]');

        // 1. Setup CSRF token for Laravel AJAX POST requests
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('input[name="_token"]').val()
            }
        });

        // 2. Initialize intl-tel-input
        var phoneInput = window.intlTelInput(phoneInputField, {
            utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js",
            preferredCountries: ["mw", "zm", "bw"],
            separateDialCode: true,
        });

        // 3. Function to perform the AJAX check
        function checkCountrySupport() {
            var countryData = phoneInput.getSelectedCountryData();
            var isoCode = countryData.iso2.toUpperCase();

            // Optional: Change button state to show it's loading
            submitBtn.prop('disabled', true).text('Checking...');

            $.ajax({
                url: "{{ url('/merchant/check-country') }}",
                method: 'POST',
                data: { iso_code: isoCode },
                success: function(response) {
                    if (response.supported) {
                        // Country is good! Clear errors and enable login button
                        formGroup.removeClass('has-error');
                        errorMsg.hide();
                        submitBtn.prop('disabled', false).text('Login');
                    } else {
                        // Country unsupported. Show the custom message from Laravel
                        formGroup.addClass('has-error');
                        errorMsg.text(response.message).show();
                        submitBtn.text('Login'); // Reset text, but keep disabled
                    }
                },
                error: function() {
                    // Fallback if the server request fails
                    formGroup.addClass('has-error');
                    errorMsg.text('Could not verify country. Please try again.').show();
                    submitBtn.prop('disabled', false).text('Login');
                }
            });
        }

        $('#phone').on('keyup', function() {
            if (phoneInput.isValidNumber()) {
                checkCountrySupport();
            } else {
                formGroup.removeClass('has-error');
                errorMsg.hide();
                submitBtn.prop('disabled', false).text('Login');
            }
        });

        phoneInputField.addEventListener("countrychange", function() {
            if ($('#phone').val().trim() !== "" && phoneInput.isValidNumber()) {
                checkCountrySupport();
            }
        });


        $('#loginForm').submit(function(e) {
            if (!phoneInput.isValidNumber()) {
                e.preventDefault();
                formGroup.addClass('has-error');
                errorMsg.text('Invalid phone number format.').show();
                return false;
            }


            var countryData = phoneInput.getSelectedCountryData();
            $('<input>').attr({ type: 'hidden', name: 'country_iso', value: countryData.iso2.toUpperCase() }).appendTo('#loginForm');
            $('#full_phone_number').val(phoneInput.getNumber());
        });
        });
</script>
</body>
</html>
