<% layout('./layouts/boilerplate') %>
<style>
    body {
        overflow-x: hidden;
    }

    #qrcodeContainer {
        border: 2px solid #000;
        border-radius: 15px;
        padding: 10px;
        display: none;
        width: fit-content;
    }

    #qrcode {
        margin: 0 auto;
    }

    .verificationStatus {
        color: green;
        font-weight: bold;
    }
</style>
<body>
    <div style="height: 200px;">  </div>
    <div class="row mt-3" style="overflow: hidden !important;">
        <h2 class="col-6 offset-1 mb-4">User Details:</h2>
        <div class="col-6 offset-3">
            <form id="registerForm" class="needs-validation" novalidate style="overflow: hidden !important;">
                <div class="mb-3">
                    <label for="name" class="form-label">Name</label>
                    <input type="text" name="name" placeholder="Enter your name" class="form-control" id="name" required>
                    <div class="invalid-feedback">
                        Enter a valid Name
                    </div>
                </div>
                <div class="mb-3">
                    <label for="aadharNo" class="form-label">Aadhar Number</label>
                    <input type="text" name="aadharNo" placeholder="Enter Aadhar no." class="form-control" id="aadharNo" required>
                    <div class="invalid-feedback">
                        Enter a valid Aadhar No
                    </div>
                </div>
                <button type="button" class="btn btn-dark mb-2" id="verifyButton">Verify Aadhaar Details</button>
                <span id="verificationStatus" class="verificationStatus"></span>
                <div id="qrcodeContainer" class="mt-4 mb-4">
                    <div id="qrcode"></div>
                </div>
                <div class="mb-3">
                    <label for="panNo" class="form-label">Pan Number</label>
                    <input type="text" name="panNo" placeholder="Enter Pan no." class="form-control" id="panNo" required>
                    <div class="invalid-feedback">
                        Enter a valid Pan No
                    </div>
                </div>
                <div class="mb-3">
                    <label for="phoneNumber" class="form-label">Phone Number</label>
                    <input type="text" name="phoneNumber" placeholder="Enter your phone no" class="form-control" id="phoneNumber" required>
                    <div class="invalid-feedback">
                        Enter your phone number
                    </div>
                </div>
                <div class="mb-3">
                    <label for="email" class="form-label">Email Id</label>
                    <input type="email" name="email" placeholder="Enter your email" class="form-control" id="email" required>
                    <div class="invalid-feedback">
                        Enter an email id
                    </div>
                </div>
                <div class="mb-3">
                    <label for="walletAddress" class="form-label">Your Wallet Address: </label>
                    <input type="text" class="form-control" id="walletAddress" disabled>
                </div>
                <div class="mb-3">
                <button type="submit" class="btn btn-dark" id="registerButton">Register</button>
               </div>
            </form>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        document.getElementById('verifyButton').addEventListener('click', async function() {
            try {
                const formData = new FormData(document.getElementById('registerForm'));
                name = formData.get('name');
                aadharNo=formData.get('aadharNo');
                const response = await axios.post('/submitProof', {
                    params: {
                        name,
                        aadharNo
                    }
                });

                const { requestUrl, statusUrl } = response.data;
                const qrcodeContainer = document.getElementById('qrcodeContainer');
                qrcodeContainer.style.display = 'block'; 

                new QRCode(document.getElementById("qrcode"), {
                    text: requestUrl,
                    width: 256,
                    height: 256
                });

                let intervalId = setInterval(async function() {
                    try {
                        const statusResponse = await axios.get(statusUrl);
                        console.log(statusResponse)
                        console.log(statusResponse.data.session.status)
                        if (statusResponse.data.session.status === "MOBILE_SUBMITTED") {
                            clearInterval(intervalId);
                            document.getElementById('verificationStatus').innerText = "Submitted, Wait for Verification!";
                            qrcodeContainer.style.display = 'none';
                            const verifyResponse = await axios.post('/verifyProof', {
                                name,
                                statusResponse: statusResponse.data
                            });

                            if (verifyResponse.data.success) {
                                document.getElementById('verificationStatus').innerText = "Verified !";
                                //document.getElementById('registerButton').disabled = false;
                            } else {
                                document.getElementById('verificationStatus').innerText = "Verification failed, please try again";
                            }
                            document.getElementById('verifyButton').disabled = true;
                        }
                    } catch (error) {
                        console.error("Error checking status:", error);
                    }
                }, 3000);
            } catch (error) {
                console.error("Error generating proof request:", error);
            }
        });
    </script>


    <script src="https://unpkg.com/web3modal"></script>
    <script src="https://unpkg.com/@walletconnect/web3-provider/dist/umd/index.min.js"></script>
    <script src="https://cdn.ethers.io/lib/ethers-5.0.umd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/gun/gun.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>

    <script>
        let provider;
        let signer;
        let contract;
        let useId;

        const contractABI = JSON.parse('<%- JSON.stringify(contractABI) %>');
        const contractAddress = "0xf7dB55e79E0cbb4E8E016bB22c25DbA13901DCca"; // Your contract address
        const db = Gun(['http://localhost:8765/gun'])
        
        async function initialize() {
            if (typeof window.ethereum !== 'undefined') {
                try {
                    await window.ethereum.request({ method: 'eth_requestAccounts' });
                    provider = new ethers.providers.Web3Provider(window.ethereum);
                    signer = provider.getSigner();
                    const address = await signer.getAddress();
                    const storedAddress = sessionStorage.getItem('walletAddress');
                    const storedUserType = sessionStorage.getItem('userType');
                    if (storedAddress === address && storedUserType === 'user') {
                        window.location.href = '/user';
                    }
                    contract = new ethers.Contract(contractAddress, contractABI, signer);
                    document.getElementById('walletAddress').value = address;
                    sessionStorage.setItem('walletAddress', walletAddress);
                    sessionStorage.setItem('userType', 'user');
                    console.log('Contract initialized', address);

                } catch (error) {
                    console.error('Error initializing contract:', error);
                }

                window.ethereum.on('accountsChanged', async (accounts) => {
                    const address = accounts[0];
                    document.getElementById('walletAddress').value = address;
                    signer = provider.getSigner(address);
                    contract = new ethers.Contract(contractAddress, contractABI, signer);
                });
            } else {
                alert('MetaMask is not installed. Please install MetaMask and try again.');
            }
        }

        document.getElementById('registerForm').onsubmit = async (e) => {
            e.preventDefault();
            if (contract) {
                const name = document.getElementById('name').value;
                const aadharNo = document.getElementById('aadharNo').value;
                const panNo = document.getElementById('panNo').value;
                const phoneNumber = document.getElementById('phoneNumber').value;
                const email = document.getElementById('email').value;
                const userDetails = {
                    aadharNo: aadharNo,
                    panNo: panNo
                };
                const userDetailsString = JSON.stringify(userDetails);
                const userHash = CryptoJS.SHA256(userDetailsString).toString();
                db.get('userDetails').get(userHash).put(userDetails, (ack) => {
                    if (ack.err) {
                      console.error('Error storing data:', ack.err)
                    } else {
                      console.log('Data stored successfully')
                    }
                  })
                console.log("User Details Stored successfully! Hash: ", userHash);
                try {
                    const details=userHash
                    const tx = await contract.registerUser(name, details, phoneNumber, email);
                    console.log('Transaction hash:', tx.hash);
                    const receipt = await tx.wait();
                    console.log('Transaction confirmed:', receipt);
                    contract.on('UserRegistered', (registeredUserId, userAddress) => {
                        userId = registeredUserId.toString(); 
                    });

                    fetch('/registerUser', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            txHash: tx.hash,
                            txReceipt: receipt
                        }),
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('Registration successful!');
                            if (userId) {
                                window.location.href = `/user?userId=${userId}`;
                            } else {
                                console.log(userId)
                            }
                        } else {
                            alert('Registration failed.');
                        }
                    })
                    .catch(error => {
                        console.error('Error sending transaction data to server:', error);
                        alert('Registered user.');
                        window.location.href = `/user`;
                    });
                } catch (error) {
                    console.error('Registered user:', error);
                    window.location.href = `/user`;
                }
            } else {
                alert('Contract is not initialized');
            }
        };

        window.addEventListener('load', initialize);
    </script>
</body>
