<% layout('./layouts/boilerplate') %>
<style>
    body {
        overflow-x: hidden;
    }
</style>
<body>
    <div style="height: 110px;">  </div>
    <h2 style="margin-left: 50px;" class="mb-3">User Details:</h2>
    <div id="userDetails" class="row mt-3 offset-2" style="overflow: hidden !important;">
        
        <p><strong>User ID:</strong> <span id="userId"></span></p>
        <p><strong>Address:</strong> <span id="userAddress"></span></p>
        <p><strong>Name:</strong> <span id="userName"></span></p>
        <p><strong>Aadhar No:</strong> <span id="userAadhar"></span></p>
        <p><strong>PAN No:</strong> <span id="userPan"></span></p>
        <p><strong>Phone Number:</strong> <span id="userPhone"></span></p>
        <p><strong>Email:</strong> <span id="userEmail"></span></p>
        <p><strong>Verified:</strong> <span id="userVerified"></span></p>
        <button id="registerLandButton" class="btn btn-dark mt-3" style="width: 266px;">Register a Land</button>
    </div>
    <h2 style="margin-left: 70px; margin-top:50px;" class="mb-4">Owned Lands</h2>
    <div id="ownedLands" class="row offset-1">
        <!-- Land cards will be dynamically inserted here -->
    </div>

    <h2 style="margin-left: 70px;  margin-top:50px">Available Lands for Sale</h2>
    <div id="availableLands" class="row offset-1">
        <!-- Available land cards will be dynamically inserted here -->
    </div>
    <div style="height: 110px;">  </div>
    
    <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>
        const urlParams = new URLSearchParams(window.location.search);
        const userId = urlParams.get('userIdInt');
        document.getElementById('userId').innerText = userId;
        const contractABI = JSON.parse('<%- JSON.stringify(contractABI) %>');
        const contractAddress = "0xf7dB55e79E0cbb4E8E016bB22c25DbA13901DCca"; // Your contract address
        const db = Gun(['http://localhost:8765/gun'])

        async function getUserDetails() {
            await window.ethereum.request({ method: 'eth_requestAccounts' });
            const provider = new ethers.providers.Web3Provider(window.ethereum);
            const signer = provider.getSigner();
            const address = await signer.getAddress();
            const contract = new ethers.Contract(contractAddress, contractABI, signer);
     
            try {
                const user = await contract.getMyDetails();
                console.log(user)
                const hash=user.details;
                let aadharNo, panNo; 
                db.get('userDetails').get(hash).once((data) => {
                    if (data) {
                        ({ aadharNo, panNo } = data);
                        console.log('Aadhaar Number:', aadharNo);
                        console.log('PAN Number:', panNo);
                        document.getElementById('userAadhar').innerText = aadharNo;
                        document.getElementById('userPan').innerText = panNo;
                    } else {
                        console.log('No user details found for the given hash.');
                    }
                });
                const userIdHex = user.id
                const userIdInt = parseInt(userIdHex, 16)
                console.log(userIdInt)
                document.getElementById('userId').innerText = userIdInt;
                document.getElementById('userName').innerText = user.name;
                document.getElementById('userPhone').innerText = user.phoneNumber;
                document.getElementById('userEmail').innerText = user.email;
                document.getElementById('userVerified').innerText = user.isUserVerified ? 'Yes' : 'Not Yet';
                document.getElementById('userAddress').innerText = user.accountAddress;

                if (user.isUserVerified) {
                    document.getElementById('registerLandButton').disabled = false;
                    document.getElementById('registerLandButton').addEventListener('click', () => {
                        window.location.href = '/registerLand'; // Redirect to registerLand page
                    });
                } else {
                    document.getElementById('registerLandButton').disabled = true;
                }

                getOwnedLands() 
            } catch (error) {
                console.error('Error fetching user details:', error);
            }
        }

        async function getOwnedLands() {
            const provider = new ethers.providers.Web3Provider(window.ethereum);
            const signer = provider.getSigner();
            const contract = new ethers.Contract(contractAddress, contractABI, signer);

            try {
                const landIds = await contract.getLandIds();
                console.log('Land IDs:', landIds);

                for (let i = 0; i < landIds.length; i++) {
                    const landId = parseInt(landIds[i], 16);

                    try {
                        const landDetails = await contract.getLandDetails(landId);
                        console.log(`Details for Land ID ${landId}:`, landDetails);

                        const ownedLandsContainer = document.getElementById('ownedLands');
                        const card = document.createElement('div');
                        card.className = 'card col-lg-4 mb-3';
                        card.innerHTML = `
                            <div class="card-body">
                                <h5 class="card-title">Land ID: ${landId}</h5>
                                <p class="card-text">Land Address: ${landDetails.landAddress}</p>
                                <p class="card-text">Land Price: ${landDetails.landPrice}</p>
                                 <p class="card-text">Land Area: ${landDetails.area}</p>
                                <p class="card-text">Verified: ${landDetails.isLandVerified ? 'Yes' : 'Not Yet'}</p>
                            </div>
                        `;
                        card.addEventListener('click', () => {
                            window.location.href = `/landowned?landId=${landId}`;
                        });
                        ownedLandsContainer.appendChild(card);
                    } catch (error) {
                        continue;
                    }
                }

                getAvailableLandsForSale()
            } catch (error) {
                console.error('Error fetching land IDs:', error);
            }
        }

        async function getAvailableLandsForSale() {
            const provider = new ethers.providers.Web3Provider(window.ethereum);
            const signer = provider.getSigner();
            const contract = new ethers.Contract(contractAddress, contractABI, signer);
        
            // Fetch current user's details to compare ownership
            const currentUser = await contract.getMyDetails();
            const currentUserName = currentUser.name;
            console.log('Current User:', currentUser);
        
            try {
                const landIds = await contract.getLandIds();
                console.log('Land IDs:', landIds);
        
                for (let i = 0; i < landIds.length; i++) {
                    const landId = parseInt(landIds[i], 16);
        
                    try {
                        const landDetails = await contract.getLandDetailsUser(landId);
                        if (landDetails.ownerName === currentUserName) {
                            // Skip if the current user is the owner
                            continue;
                        }
                        console.log(`Details for Land ID ${landId}:`, landDetails);
        
                        const availableLandsContainer = document.getElementById('availableLands');
                        const card = document.createElement('div');
                        card.className = 'card col-lg-4 mb-3';
                        card.innerHTML = `
                            <div class="card-body">
                                <h5 class="card-title">Land ID: ${landId}</h5>
                                <p class="card-text">Land Area: ${landDetails.area}</p>
                                <p class="card-text">Land Address: ${landDetails.landAddress}</p>
                                <p class="card-text">Land Price: ${landDetails.landPrice}</p>
                                <p class="card-text">Owner Name: ${landDetails.ownerName}</p>
                                <p class="card-text">Owner Phone: ${landDetails.ownerPhoneNumber}</p>
                                <p class="card-text">Owner Email: ${landDetails.ownerEmail}</p>
                            </div>
                        `;
                        card.addEventListener('click', () => {
                            window.location.href = `/land?landId=${landId}`;
                        });
                        availableLandsContainer.appendChild(card);
                    } catch (error) {
                        // Ignore the error and move to the next land ID
                        continue;
                    }
                }
            } catch (error) {
                console.error('Error fetching land IDs:', error);
            }
        }
        
        getUserDetails();
    </script>
</body>
