<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <link href="/assets/style.css" rel="stylesheet"/>
    <link rel="preconnect" href="https://fonts.googleapis.com"/>
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@600;700&display=swap"
        rel="stylesheet"
    />
    <link rel="preconnect" href="https://fonts.googleapis.com"/>
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
    <link
        href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap"
        rel="stylesheet"
    />
    <link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    <title>Application Form</title>
</head>

<body>
<section>
    <br>

    <form action="{{route('submit-form')}}" method="POST" id="myForm" enctype="multipart/form-data">
        @csrf
    <div class="header_container">
        <div class="header_wrapper">
            <img
                src="/assets/images/logo.png"
                alt="logo"
                class="img-responsive"
            />
            <p>Serial No: <span class="red">{{$generatedNumber}}</span></p>
            <input type="hidden" name="generated_number" value="{{$generatedNumber}}">

        </div>
        @if (Session::has('success'))
            <div class="alert alert-success alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert">
                    <i class="fa fa-times"></i>
                </button>
                <strong>Success !</strong> {{ session('success') }}
            </div>
        @endif
        <div class="profile_pic">
            <label for="passport1" class="file-upload-button">
                <div class="image-preview" id="output1">
                    <p>
                        Upload Passport <br />
                        Personal
                    </p>
                </div>
                <input type="file" id="passport1" name="passport1" style="display: none;" class="my-input">
            </label>
            <label for="passport2" class="file-upload-button">
                <div class="image-preview" id="output2">
                    <p>
                        Upload Passport <br />
                        Next of kin
                    </p>
                </div>
                <input
                    type="file"
                    id="passport2"
                    name="passport2"
                    style="display: none"
                    accept="image/jpeg, image/png, image/jpg"
                />
            </label>
        </div>
        <script>
            // Function to handle the file selection and display the image
            function handleFileSelect(event, outputElement) {
                const file = event.target.files[0];
                const reader = new FileReader();

                reader.onload = function() {
                    const dataURL = reader.result;
                    outputElement.innerHTML = `<img src="${dataURL}" alt="Passport Image" width="150" height="150">`;
                };

                if (file) {
                    reader.readAsDataURL(file);
                }
            }

            // Add event listeners to the file inputs
            document.getElementById('passport1').addEventListener('change', function(event) {
                handleFileSelect(event, document.getElementById('output1'));
            });

            document.getElementById('passport2').addEventListener('change', function(event) {
                handleFileSelect(event, document.getElementById('output2'));
            });


            // Function to center the text inside the image-preview divs
            function centerText() {
                const imagePreviews = document.querySelectorAll('.image-preview');

                imagePreviews.forEach((preview) => {
                    const textElement = preview.querySelector('p');
                    const heightDiff = preview.clientHeight - textElement.clientHeight;
                    const widthDiff = preview.clientWidth - textElement.clientWidth;

                    // Adjust the top and left margin to center the text
                    textElement.style.marginTop = heightDiff / 2 + 'px';
                    textElement.style.marginLeft = widthDiff / 2 + 'px';
                });
            }

            // Call the centerText function initially and on window resize
            centerText();
            window.addEventListener('resize', centerText);

        </script>
    </div>
    <div class="info-container">
        <div class="apdc-title">
            <p>APDC HOMES</p>
            <p>APPLICATION FORM</p>
        </div>
        <div class="info">personal information</div>
        <div class="form">
            <div class="form-group">
                <div class="input-group">
                    <div class="placeholder">Name</div>
                    <input type="text" id="name" name="name" required>
                </div>
                <div class="error-container">
                    <div class="error-message" id="name-error"></div>
                </div>
            </div>
            <div class="form-group">
                <div class="input-group">
                    <div class="placeholder">
                        Permanent Address<span> Type in your Address please</span>
                    </div>
                    <input type="text" name="permanent_address" id="permanent_address" required/>
                </div>
                <div class="error-container">
                    <div class="error-message" id="permanent_address-error"></div>
                </div>
            </div>
            <div class="form-group">
                <div class="input-group">
                    <div class="placeholder">Occupation</div>
                    <input type="text" name="occupation" required/>
                </div>
                <div class="error-container">
                    <div class="error-message" id="occupation-error"></div>
                </div>
            </div>
            <div class="form-group">
                <div class="input-group">
                    <div class="placeholder">Office/Business</div>
                    <input type="text" name="office_address" required/>
                </div>
                <div class="error-container">
                    <div class="error-message" id="office_address-error"></div>
                </div>
            </div>
            <div class="form-group">
                <div class="input-group">
                    <div class="placeholder">Telephone Number(s)</div>
                    <input type="text" name="phone" required/>
                </div>
                <div class="error-container">
                    <div class="error-message" id="telephone-error"></div>
                </div>
                @if (Session::has('phone-error'))
                    <div class="phone-error">
                        <p style="color: red">Error !!! - Phone Number is not exactly 11 digits</p>
                    </div>
                @endif
            </div>
            <div class="form-group">
                    <div class="input-group">
                        <div class="placeholder">Email</div>
                        <input type="text" name="email" required/>
                        <div class="error-messages" id="email-error"></div>
                    </div>
            </div>
            <div class="form-group">
                <div class="input-group">
                    <div class="placeholder">Valid Means of Identification</div>
                    <select name="identification" required>
                        <option value="select">Choose Valid Means of Identification</option>
                        <option value="National ID Card">National ID Card</option>
                        <option value="National Driver's License">National Driver's License</option>
                        <option value="International Passport">International Passport</option>
                        <option value="Permanent Voter's Card">Permanent Voter's Card</option>
                    </select>
                </div>
                <div class="error-container">
                    <div class="error-message" id="identification-error"></div>
                </div>
            </div>
            <div class="form-group">
                <div class="input-group">
                    <input type="checkbox" id="value1" name="value1" onchange="toggleInputGroups(this)" />
                    <label>Apply with company</label>
                </div>
                <div class="input-group hidden" id="group2">
                    <div class="placeholder">
                        Copy of CAC Certificate of Incorporation
                    </div>
                    <input type="file" name="coi" />
                </div>
                <div class="input-group hidden" id="group3">
                    <div class="placeholder">Form C02 & C07</div>
                    <input type="file" name="form_co2" />
                    <input type="file" name="form_co7" />
                </div>

                <style>
                    .hidden {
                        display: none;
                    }
                </style>

                <script>
                    function toggleInputGroups(checkbox) {
                        var group2 = document.getElementById('group2');
                        var group3 = document.getElementById('group3');

                        if (checkbox.checked) {
                            group2.style.display = 'block';
                            group3.style.display = 'block';
                        } else {
                            group2.style.display = 'none';
                            group3.style.display = 'none';
                        }
                    }
                </script>
            <div class="form-group">
                <div class="input-group">
                    <div class="placeholder">Next of Kin</div>
                    <input type="text" name="nok_name" required/>
                </div>
                <div class="error-container">
                    <div class="error-message" id="nok_name-error"></div>
                </div>
            </div>
            <div class="form-group">
                    <div class="input-group">
                        <div class="placeholder">Address <span>(Next of kin)</span></div>
                        <input type="text" name="nok_address" required/>
                    </div>
                    <div class="error-container">
                        <div class="error-message" id="nok_address-error"></div>
                    </div>
                </div>
            <div class="form-group">
                <div class="input-group">
                    <div style="display: flex; width: 100%; margin-bottom: 20px">
                        <div class="placeholder">Phone Number</div>
                        <input type="text" name="nok_phone" style="width: 50%"/>
                        <div class="placeholder">Email</div>
                        <input type="text" name="nok_phone" style="width: 50%"/>
                    </div>
                </div>
                <div class="error-container">
                    <div class="error-message" id="email-error"></div>
                </div>
            </div>
            <div class="info">property details</div>
            <div id="projectFormsContainer">
                <div class="projectFormContainer">
                    <!-- Initial project form -->
                    <div class="projectForm">
                        <div class='input-group'>
                            <div class='placeholder'>Project</div>
                            <select name="project" style="width: 100%" id="project" required>
                                <option value="">Choose Project</option>
                               @foreach ($newProject as $project)
                                   <option value="{{ $project->id }}">{{ $project->name }} - {{ $project->size }}</option>
                               @endforeach
                            </select>
                        </div>
                        <br>
                        <div class="input-group">
                            <div style="display: flex; width: 100%; margin-bottom: 20px">
                                <div class="placeholder">House Type Required</div>
                                <select name="house_type" style="width: 50%" id="house_name" required>
                                    <option value="">Choose House Type</option>
                                    <!-- House type options will be added dynamically using AJAX -->
                                </select>
                                <div class="placeholder">Amount</div>
                                <input type="text" name="amount" style="width: 50%" id="amount" oninput="formatAmountInput(this)"/>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="add_project">
                <button onclick="addNewProjectForm()">+ Add Project</button>
            </div>
            <div class="input-group">
                    <div class="placeholder">
                        Preferred Mode of Payment
                        <span>(Strictly to be adhered to)</span>
                    </div>
                    <input type="text" name="mode_of_payment"/>
                </div>
            <div>
                    <p>a &#41; Installment Payment</p>
                    <ul>
                        <li>Discount available for one-off payment</li>
                        <li>
                            Installment payment (Subject to payment options on price list)
                        </li>
                    </ul>
                </div>
            <div class="input-group">
                    <div class="placeholder">Source of Payment</div>
                    <select>
                        <option value="select">Select</option>
                    </select>
                </div>
            <div class="info">Agent's information</div>
            <div class="input-group">
                    <div class="placeholder">Agent's Name</div>
                    <input type="text" name="agent_name"/>
            </div>
            <div class="input-group">
              <div class="placeholder">Agent's TIN Number</div>
              <input type="text" name="tin"/>
      </div>
            <div class="input-group">
                    <div class="placeholder">Agent's Bank</div>
                    <select name="agent_bank">
                        <option value="select">Select Bank</option>
                        @foreach($banks as $bank)
                            <option value="select">{{$bank['name']}}</option>
                        @endforeach
                    </select>
                </div>
            <div class="input-group">
                    <div class="placeholder">Agent's Account Name</div>
                    <input type="text" name="agent_account_name"/>
                </div>
            <div class="input-group">
                    <div class="placeholder">Agent's Account Number</div>
                    <input type="text" name="agent_account_number"/>
                </div>
            <div class="btn-group">
                    <button type="submit">Submit</button>
                    <button id="shareButton" class="shareButtonModal">Share</button>
                </div>
            <div id="myModal" class="modal">
                    <div class="modal-content">
                        <span class="close">&times;</span>
                        <p>Share via</p>
                        <div style="display: flex">
                            <div style="text-align: center">
                                <a href="#" onclick="shareViaWhatsApp(event);">
                                    <img src="/assets/images/whatsApp.png" />
                                </a>
                                <p>Whatsapp</p>
                            </div>
                            <div style="margin-left: 3%; text-align: center">
                                <a href="#" onclick="shareViaEmail(event);">
                                    <img src="/assets/images/mail.png" />
                                </a>
                                <p>Mail</p>
                            </div>
                        </div>
                    </div>
                </div>
        </div>
    </div>
    </form>
</section>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>


<script>
    $(document).ready(function() {
        $("#myForm").validate({
            errorContainer: ".error-messages",
            errorLabelContainer: ".error-messages ul",
            wrapper: "li",
            submitHandler: function(form) {
                form.submit();
            },
            errorPlacement: function(error, element) {
                error.appendTo(element.closest('.form-group').find('.error-container'));
            }
        });
    });
</script>

<script>
    var modal = document.getElementById("myModal");

    // Get the button that opens the modal
    var btn = document.getElementById("shareButton");

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks the button, open the modal
    btn.onclick = function() {
        modal.style.display = "block";
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        modal.style.display = "none";
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
</script>
<script defer>
    // Function to format the amount as a number with the appropriate locale
    function formatAmount(amount) {
        const formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'NGN', // Change this to the appropriate currency code if needed
            minimumFractionDigits: 2,
        });
        return formatter.format(amount);
    }


    function formatAmountInput(input) {
        const value = parseFloat(input.value.replace(/[^0-9.-]+/g, ""));
        input.value = formatAmount(value);
    }

    function updateHouseTypeOptionsAndAmount(projectSelect, houseTypeSelect, amountInput) {
        if (!projectSelect) return; // Check if projectSelect is null before proceeding

        const selectedProjectType = projectSelect.options[projectSelect.selectedIndex].getAttribute('data-type');

        // Make an AJAX request to fetch house types and amounts
        fetch('/sales/get-house-types-and-amounts', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            },
            body: JSON.stringify({ selected_project_type: selectedProjectType }),
        })
            .then(response => response.json())
            .then(data => {
                houseTypeSelect.innerHTML = '<option value="">Choose House Type</option>';
                if (data && data.length > 0) {
                    data.forEach(item => {
                        const option = document.createElement('option');
                        option.value = item.id;
                        option.textContent = item.name;
                        houseTypeSelect.appendChild(option);
                    });

                    // Update amount input when a house type is selected
                    houseTypeSelect.addEventListener('change', function () {
                        const selectedHouseTypeId = houseTypeSelect.value;
                        const selectedHouseType = data.find(item => item.id == selectedHouseTypeId);
                        if (selectedHouseType) {
                            amountInput.value = formatAmount(selectedHouseType.list_price);
                        } else {
                            amountInput.value = '';
                        }
                    });

                } else {
                    amountInput.value = '';
                }
            })
            .catch(error => {
                console.error('Error fetching house types and amounts:', error);
                amountInput.value = '';
            });
    }

    function addNewProjectForm() {
        const projectFormsContainer = document.getElementById('projectFormsContainer');
        const firstProjectFormContainer = document.querySelector('.projectFormContainer');
        const newProjectFormContainer = firstProjectFormContainer.cloneNode(true);

        // Clear selected project and house type values in the cloned form
        const projectSelect = newProjectFormContainer.querySelector('select[name="project"]');
        const houseTypeSelect = newProjectFormContainer.querySelector('select[name="house_type"]');
        const amountInput = newProjectFormContainer.querySelector('input[name="amount"]');
        projectSelect.selectedIndex = 0;
        houseTypeSelect.innerHTML = '<option value="">Choose House Type</option>';
        amountInput.value = '';

        // Add event listener to update house types and amounts in the cloned form
        projectSelect.addEventListener('change', function () {
            updateHouseTypeOptionsAndAmount(projectSelect, houseTypeSelect, amountInput);
        });

        projectFormsContainer.appendChild(newProjectFormContainer);
    }

    document.addEventListener('DOMContentLoaded', function() {
        // Initial project form setup
        const projectSelect = document.querySelector('select[name="project"]');
        const houseTypeSelect = document.querySelector('select[name="house_type"]');
        const amountInput = document.querySelector('input[name="amount"]');
        projectSelect.addEventListener('change', function () {
            updateHouseTypeOptionsAndAmount(projectSelect, houseTypeSelect, amountInput);
        });

        if (projectSelect) {
            updateHouseTypeOptionsAndAmount(projectSelect, houseTypeSelect, amountInput);
        }

        // Add event listener to format amount input as number
        amountInput.addEventListener('input', function () {
            formatAmountInput(this);
        });
    });
</script>
<script>
    function shareViaWhatsApp(event) {
        // Prevent form submission
        event.preventDefault();

        // Implementation for sharing via WhatsApp
        var formUrl = window.location.href;
        var message = encodeURIComponent(formUrl);
        var whatsappLink = "https://api.whatsapp.com/send?text=" + message;
        window.open(whatsappLink);
    }

    function shareViaEmail(event) {
        // Prevent form submission
        event.preventDefault();

        // Implementation for sharing via Email
        var formUrl = window.location.href;
        var subject = encodeURIComponent("Check out this form");
        var body = encodeURIComponent("Here is the link to the form: " + formUrl);
        var emailLink = "mailto:?subject=" + subject + "&body=" + body;
        window.location.href = emailLink;
    }
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<script>
    @if(Session::has('message'))
    toastr.options =
    {
        "closeButton" : true,
        "progressBar" : true
    }
            toastr.success("{{ session('message') }}");
    @endif

    @if(Session::has('error'))
    toastr.options =
    {
        "closeButton" : true,
        "progressBar" : true
    }
            toastr.error("{{ session('error') }}");
    @endif

    @if(Session::has('info'))
    toastr.options =
    {
        "closeButton" : true,
        "progressBar" : true
    }
            toastr.info("{{ session('info') }}");
    @endif

    @if(Session::has('warning'))
    toastr.options =
    {
        "closeButton" : true,
        "progressBar" : true
    }
            toastr.warning("{{ session('warning') }}");
    @endif
  </script>



  <script>
    $(document).ready(function() {
        $('#project').change(function() {
            var project_id = $(this).val();
            $('#house_name').html(' <option value="">Choose House Type</option>');
            if (project_id) {
                $.ajax({
                    url: '/sales/get-product-details',
                    type: 'GET',
                    data: {
                        project_id: project_id
                    },
                    success: function(data) {
                        console.log(data);
                        $.each(data, function (index, houseType) {
                        $('#house_name').append('<option value="' + houseType.id + '">' + houseType.name + '</option>');
                        $('#amount').val(houseType.list_price);
                    });
                        $('#house_name').prop('disabled', false);
                    },
                    error: function() {
                        alert('Error occurred while fetching departments.');
                    }
                });
            } else {
                $('#house_name').prop('disabled', true);
            }
        });
    });
</script>


<script src="/assets/script.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

</body>
</html>
