<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Samahan Link Natural</title>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="icon" type="image/x-icon" href="assets/logo.png">

    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/toastify-js"></script>


    <!-- Chosen Library CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css">
    <!-- jQuery Library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <!-- Chosen Library JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>

    <link rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">

    <!-- Boostrap import link -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/css/bootstrap.min.css">

    <link rel="stylesheet" href="styles/index.css">
</head>

<body>
    <div class="header">
        <a href="#">
            <img src="assets/logo.png" alt="Company Logo">
        </a>
    </div>

    <div class="banner">
        <img src="assets/sam.png" alt="Banner">
    </div>
    <div class="product-container">
        <h2>Link Samahan Scan & Win</h2>
        <form id="user-info" action="bkEnd.php" method="POST" enctype="multipart/form-data">
            <label for="name">Name *:</label>
            <input type="text" id="name" name="name" placeholder="Enter your name" required>

            <label for="idNo">ID Number *:</label>
            <input type="text" id="idNo" name="idNo" placeholder="Enter your ID number" required>

            <label for="dob">Date of Birth *:</label>
            <input type="date" id="dob" name="dob" required>

            <label for="contactNo">Contact Number *:</label>
            <input type="text" id="contactNo" name="contactNo" placeholder="Enter your contact number" required>

            <label for="province">Province *:</label>
            <select id="province" name="province" class="chosen-select" required onchange="filterDistricts()">
                <option value="">Select Province</option>
                <option value="Western">Western</option>
                <option value="Central">Central</option>
                <option value="Southern">Southern</option>
                <option value="Northern">Northern</option>
                <option value="Eastern">Eastern</option>
                <option value="North Western">North Western</option>
                <option value="North Central">North Central</option>
                <option value="Uva">Uva</option>
                <option value="Sabaragamuwa">Sabaragamuwa</option>
            </select>

            <label for="district">District *:</label>
            <select id="district" name="district" class="chosen-select" required>
                <option value="">Select District</option>
            </select>

            <div class="link">
                <a href="https://www.facebook.com/SamahanSL" target="_blank">
                    <p>Samahan facebook page </p>
                </a>
                <a href="https://www.facebook.com/SamahanSL" target="_blank">
                    <img src="assets/face.png" alt="samahan link">
                </a>
            </div>

            <label for="images">Upload screenshot after liking the Samahan Page:</label>
            <input type="file" id="imagesPage" name="imagesPage" accept="image/*">
            <img id="previewPage" alt="Image Preview">

            <label for="images">Upload screenshot of your profile:</label>
            <input type="file" id="images" name="images" accept="image/*">
            <img id="preview" alt="Image Preview">
            <br />
            <div style="display: flex; align-items: center;">
                <label for="agree" style="margin-right: 10px;">
                    By submitting this form, I consent to the collection of my information. *
                </label>
                <input
                    style="transform: scale(1.6); width: auto; height: 40px; display: flex;justify-content: center;align-items: center;"
                    type="checkbox" id="agree" name="agree" onchange="toggleSubmitButton()" required>
            </div>
            <br />
            <center>
                <button class="submit-btn" id="submit-btn" type="submit" disabled>Submit Details</button>
            </center>
            </from>
    </div>

    <script>
        function toggleSubmitButton() {
            const agree = document.getElementById("agree");
            const submitBtn = document.getElementById("submit-btn");

            submitBtn.disabled = !agree.checked;
        }
    </script>

    <script>
        // Districts mapped to their respective provinces
        const districtsByProvince = {
            Western: ["Colombo", "Gampaha", "Kalutara"],
            Central: ["Kandy", "Matale", "Nuwara Eliya"],
            Southern: ["Galle", "Matara", "Hambantota"],
            Northern: ["Jaffna", "Kilinochchi", "Mannar", "Vavuniya", "Mullaitivu"],
            Eastern: ["Batticaloa", "Ampara", "Trincomalee"],
            "North Western": ["Kurunegala", "Puttalam"],
            "North Central": ["Anuradhapura", "Polonnaruwa"],
            Uva: ["Badulla", "Monaragala"],
            Sabaragamuwa: ["Ratnapura", "Kegalle"]
        };

        function filterDistricts() {
            const province = document.getElementById("province").value;
            const districtSelect = document.getElementById("district");

            // Clear current district options
            districtSelect.innerHTML = '<option value="">Select District</option>';

            if (province && districtsByProvince[province]) {
                // Add districts related to the selected province
                districtsByProvince[province].forEach(district => {
                    const option = document.createElement("option");
                    option.value = district;
                    option.textContent = district;
                    districtSelect.appendChild(option);
                });
            }
        }
    </script>

    <script>
        const form = document.getElementById("user-info");
        form.addEventListener('submit', async function (event) {
            event.preventDefault();

            const contactNo = document.getElementById('contactNo').value;
            const image1 = document.getElementById("imagesPage").files[0];
            const image2 = document.getElementById("images").files[0];
            const date = document.getElementById("dob").value;

            // Validate phone number
            if (contactNo.length !== 10 || isNaN(contactNo)) {
                Toastify({
                    text: "Contact number must be a 10-digit number.",
                    duration: 3000,
                    gravity: "top",
                    position: "center",
                    backgroundColor: "red",
                    stopOnFocus: true,
                }).showToast();
                return;
            } else if (!image1 || !image2) {
                Toastify({
                    text: "Please upload both images.",
                    duration: 3000,
                    gravity: "top",
                    position: "center",
                    backgroundColor: "red",
                    stopOnFocus: true,
                }).showToast();
                return;
            } else {
                const formData = new FormData(form);

                try {
                    const response = await fetch(form.action, {
                        method: 'POST',
                        body: formData
                    });

                    // Check for non-JSON response
                    if (!response.headers.get('content-type')?.includes('application/json')) {
                        throw new Error('Invalid JSON response');
                    }

                    const result = await response.json();
                    console.log("result:> ", result)
                } catch (error) {
                    console.log("error::> ", error)
                }
            }
        })







        // function submitForm(event) {
        //     const contactNo = document.getElementById('contactNo').value;
        //     const image1 = document.getElementById("imagesPage").files[0];
        //     const image2 = document.getElementById("images").files[0];
        //     const date = document.getElementById("dob").value;

        //     // Validate phone number
        //     if (contactNo.length !== 10 || isNaN(contactNo)) {
        //         Toastify({
        //             text: "Contact number must be a 10-digit number.",
        //             duration: 3000,
        //             gravity: "top",
        //             position: "center",
        //             backgroundColor: "red",
        //             stopOnFocus: true,
        //         }).showToast();
        //     } else if (!image1 || !image2) {
        //         Toastify({
        //             text: "Please upload both images.",
        //             duration: 3000,
        //             gravity: "top",
        //             position: "center",
        //             backgroundColor: "red",
        //             stopOnFocus: true,
        //         }).showToast();
        //     } else {
        //         event.preventDefault();  // Prevent the default form submission

        //         // Create a FormData object to capture all form data including files
        //         const formData = new FormData(document.getElementById('user-info'));

        //         // Use fetch API to send the form data to the backend (bkEnd.php)
        //         fetch('bkEnd.php', {
        //             method: 'POST',
        //             body: formData,
        //         })
        //             .then(response => response.json())  // Assuming the backend returns a JSON response
        //             .then(data => {
        //                 // Handle success (e.g., show a success message)
        //                 if (data.status === 'success') {
        //                     // Clear image previews
        //                     document.getElementById('preview').src = '';
        //                     document.getElementById('preview').style.display = 'none';
        //                     document.getElementById('previewPage').src = '';
        //                     document.getElementById('previewPage').style.display = 'none';

        //                     // Reset the Chosen dropdowns
        //                     $('.chosen-select').val('').trigger('chosen:updated');

        //                     Toastify({
        //                         text: "Form Submission Successfull!!!",
        //                         duration: 3000,
        //                         gravity: "top",
        //                         position: "center",
        //                         backgroundColor: "green",
        //                         stopOnFocus: true,
        //                     }).showToast();
        //                 } else {
        //                     Toastify({
        //                         text: "Oops! Error Occured When Submit the form.",
        //                         duration: 3000,
        //                         gravity: "top",
        //                         position: "center",
        //                         backgroundColor: "red",
        //                         stopOnFocus: true,
        //                     }).showToast();
        //                 }
        //             })
        //             .catch(error => {
        //                 alert('There was an error submitting the form');
        //                 console.log(error);
        //             });
        //     }
        // }
    </script>

    <!-- <script>
        if (<?php echo json_encode($form_sucecss); ?>){
            // Reset the form
            document.getElementById('user-info').reset();

            // Clear image previews
            document.getElementById('preview').src = '';
            document.getElementById('preview').style.display = 'none';
            document.getElementById('previewPage').src = '';
            document.getElementById('previewPage').style.display = 'none';

            // Reset the Chosen dropdowns
            $('.chosen-select').val('').trigger('chosen:updated');

            Toastify({
                    text: "Form Submission Successfull!!!",
                    duration: 3000,
                    gravity: "top",
                    position: "center",
                    backgroundColor: "green",
                    stopOnFocus: true,
                }).showToast();
        }else{
            Toastify({
                    text: "Oops! Error Occured When Submit the form.",
                    duration: 3000,
                    gravity: "top",
                    position: "center",
                    backgroundColor: "red",
                    stopOnFocus: true,
                }).showToast();
        }
    </script> -->

    <script>
        window.addEventListener("scroll", () => {
            const header = document.querySelector(".header");
            if (window.scrollY > 20) {
                header.classList.add("shrink");
            } else {
                header.classList.remove("shrink");
            }
        });

        // Add smooth transition to header
        document.querySelector(".header").style.transition = "all 0.5s ease";
    </script>

    <script>
        const fileInput = document.getElementById('images');
        const preview = document.getElementById('preview');

        fileInput.addEventListener('change', function () {
            const file = fileInput.files[0];

            if (file) {
                const reader = new FileReader();

                reader.onload = function (e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block'; // Show the image
                };

                reader.readAsDataURL(file); // Read the file as a Data URL
            }
        });
    </script>

    <script>
        const fileInput1 = document.getElementById('imagesPage');
        const preview1 = document.getElementById('previewPage');

        fileInput1.addEventListener('change', function () {
            const file = fileInput1.files[0];

            if (file) {
                const reader = new FileReader();

                reader.onload = function (e) {
                    preview1.src = e.target.result;
                    preview1.style.display = 'block'; // Show the image
                };

                reader.readAsDataURL(file); // Read the file as a Data URL
            }
        });
    </script>

    <script>
        $(document).ready(function () {
            $('.chosen-select').chosen({
                no_results_text: "No match found!", // Message when no results are found
                width: "100%" // Adjust the dropdown width to container width
            });
        });
    </script>

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.3/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>

</body>

</html>