<%layout('./layouts/boilerplate')%>
<style>
    .buyerprintingdetails .table a {
        color: #007bff; /* Link color */
        text-decoration: underline; /* Underline the link */
        font-weight: bold; /* Make the link bold */
        padding: 5px; /* Optional: add some padding */
        border-radius: 3px; /* Optional: rounded corners */
    }

    .buyerprintingdetails .table a:hover {
        color: #0056b3; /* Darker color on hover */
        background-color: #e0e0e0; /* Optional: add a background color on hover */
    }
</style>
<body>
    <div style="height: 110px;">  </div>
    <section class="mainbuyer py-5" >
        <div class="container py-5">
            <span class="usercircle">
                <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5OjcBCgoKDQwNGg8PGjclHyU3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3N//AABEIAI8A4QMBIgACEQEDEQH/xAAaAAEBAQEBAQEAAAAAAAAAAAAAAwQCBQEH/8QALxABAAECAggFAwUBAAAAAAAAAAIBAwQSISIxMkFCUXERUmGBoRMUM5GxwdHwI//EABUBAQEAAAAAAAAAAAAAAAAAAAAB/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8A/cQAAAAAEpzzaI7H25Lh+qYAAAAAAAAAAAAOoSy9lmd3blygqAAAAAAAAAAAA5lXLF0ldrreAOAAAAAQxF7Lqx28fQHdy9C3vbelEa4qXLGnvpZwGimKlzRj80Vt34XPSvSrEA9IZsPe5Je1f4aQAAAAWhLNF0jbr4SWAAAAAAAAAAAZ61Wnu1RAAAAB8lXLGUuml58q5pSlLi23/wAE+zCAAqAAD0LcvqW4yee2YX8fvVFWAAAAXpXVQVt7oOwAAAAAAAAAcXN1JW5upAAAAAnf/DLswvRlTNGUetPB58qZZZZcAfAFQAAbML+P3qxvQtR+nbjH/eKK6AAAAUtbtU1LXEFAAAAAAAAAAcz3aotDOAAAAAhiLObXjt406rgPNG65Zhc9K9aI1wsuWUffQDOL0ws+aUfmq1uxCOttr6gnhrPPL2p/LSAAAAACtrdSWjTLEHQAAAAAAAAACVymt3VczjmiCIAAIYi9l1Le3jXoCk7sLe9LT04oyxXlj+tWYBf7qflj8n3U/LH5QAX+6n5Y/J91Pyx+UAGimKlzRp7LW70LnpXpVhAekM1i/wAlz2q0gAA6hTNJZxbjlj3dgAAAAAAAAAAAAlcjzOGhGccvYErs/p25S47Kd2Bpxld2PerMAAqAAAAAADbh5/Ut+tNDEvhK/wDSUetEVrdQjm7PkY5lqU8AfQAAAAAAAAAAAAAAAYsZYnLXhTxpSmmnFie0z3sPC7p2S60B5ovdwt2HLnp1p/SAACoAAAtbw12e7Hwp1roRUWrCWZylSddEf3aLWEhDTLWl67GgHylPB9AAAAAAAAAAAAAAAAAAABxO3Ce9Gle9HYDNLCWZcJU7Vc1wMPPJrAZPsoeeT7HB2o+averUAnC1CG7ClPVQAAAAAAAAAAAAAf/Z" alt="">
            </span>
        </div>
    </section>
    <section class="buyerprintingdetails">
        <div class="row">
            <h2 class="ms-5 mb-3">Land requested for registration:</h2>
            <section class="linebyline">
                <table class="table" style="margin-left: 60px ;width:90%; border-radius: 10px; border: 1px solid gray; border-collapse: separate; ">
                    <thead>
                        <tr>
                            <th scope="col"> Land id</th>
                            <th scope="col">Property ID</th>
                            <th scope="col">Land Survey No</th>
                            <th scope="col">Land address</th>
                            <th scope="col">Land area</th>
                            <th scope="col">Land Price</th>
                            <th scope="col">Land Document URL</th>
                            <th scope="col">Land owner ID</th>
                            <th scope="col">Approve</th>
                        </tr>
                    </thead>
                    <tbody id="landRegistrationBody">
                        <!-- Dynamic content will be inserted here -->
                    </tbody>
                </table>
            </section>
        </div>
    </section>
    <section class="buyerprintingdetails">
        <div class="row">
            <h2 class="ms-5 mb-3 mt-3">User requests for verification:</h2>
            <section class="linebyline mt-2">
                <table class="table" id="buyerRegistrationTable" style="margin-left: 60px ;width:90%; border-radius: 10px; border: 1px solid gray; border-collapse: separate; ">
                    <thead>
                        <tr>
                            <th scope="col">Buyer Name</th>
                            <th scope="col">Aadhar No</th>
                            <th scope="col">Pan No</th>
                            <th scope="col">Phone Number</th>
                            <th scope="col">Email</th>
                            <th scope="col">Approve</th>
                        </tr>
                    </thead>
                    <tbody id="buyerRegistrationBody">
                        <!-- Dynamic content will be inserted here -->
                    </tbody>
                </table>
            </section>
        </div>
    </section>
    <section class="buyerprintingdetails">
        <div class="row ms-5">
            <h2 class="ms-4 mb-3 mt-3">Approved Sale Requests:</h2>
            <div class="card col-lg-4 mb-3 offset-1 mt-2">
                <div class="card-body">
                    <h5 class="card-title" style="margin-top: 30px;">Land ID: </h5>
                    <p class="card-text" style="margin-top: 10px;">Owner Address:</p>
                    <p class="card-text" style="margin-top: 10px;">Owner ID:</p>
                    <p class="card-text" style="margin-top: 10px;">Buyer Address:</p>
                    <p class="card-text" style="margin-top: 10px;">Buyer ID:</p>
                    <p class="card-text"style="margin-top: 10px;">Proof URL:</p>
                    <button id="approveBtn" class="button btn-dark mt-3">Approve Sale</button>
                </div>
            </div>
        </div>
        <div style="height: 220px;">  </div>
    </section>

    <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 contractABI = JSON.parse('<%- JSON.stringify(contractABI) %>');
        const contractABI2 = JSON.parse('<%- JSON.stringify(contractABI2) %>');
        const contractAddress = "0xf7dB55e79E0cbb4E8E016bB22c25DbA13901DCca"; // contract address
        const contractAddress2="0x51b43aA56ec9DDaE2A46683413b87e4bb5332E90"//NFT-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 users = await contract.getRegisteredUserIds();
                console.log(users)
                const userIdsLength = users.length;
                const userIds = users.map(user => parseInt(user, 16));
                console.log('User IDs Length:', userIdsLength);
                console.log('User IDs:', userIds);
                
                for (let i = 0; i < userIdsLength; i++) {
                    const userId = userIds[i];
                    const userDetails = await contract.getUserDetails(userId);
                    console.log(`Details for User ID ${userId}:`, userDetails);
                    
                    if (!userDetails.isUserVerified) {
                        const hash=userDetails.details;
                        db.get('userDetails').get(hash).once((data) => {
                            if (data) {
                                ({ aadharNo, panNo } = data);
                                console.log('Aadhaar Number:', aadharNo);
                                console.log('PAN Number:', panNo);
                                const tableBody = document.getElementById('buyerRegistrationBody');
                                const row = document.createElement('tr');
                                row.innerHTML = `
                                    <td>${userDetails.name}</td>
                                    <td>${aadharNo}</td>
                                    <td>${panNo}</td>
                                    <td>${userDetails.phoneNumber}</td>
                                    <td>${userDetails.email}</td>
                                    <td>
                                        <button class="btn btn-dark approve-button" data-userid="${userId}">
                                                <i class="bi bi-check"></i> Approve
                                        </button>
                                    </td>
                                `;
                                tableBody.appendChild(row);
                                    } else {
                                        console.log('No user details found for the given hash.');
                                    }
                                });
                    }
                }
            } catch (error) {
                console.error('Error fetching user details:', error);
            }
        }

        async function approveUser(userId) {
            try {
                await window.ethereum.request({ method: 'eth_requestAccounts' });
                const provider = new ethers.providers.Web3Provider(window.ethereum);
                const signer = provider.getSigner();
                const contract = new ethers.Contract(contractAddress, contractABI, signer);
    
                // Call your smart contract's verifyUser function with userId
                const tx = await contract.verifyUser(userId);
                const receipt = await tx.wait(); // Wait for the transaction to be mined and get receipt
                
                console.log(`User with ID ${userId} verified successfully.`);
                console.log('Transaction Receipt:', receipt);
                getUserDetails();
                // Optionally, update UI or perform other actions after verification
                window.location.reload(true);
            } catch (error) {
                console.error('Error approving user:', error);
            }
        }

        getUserDetails();
        document.addEventListener('click', function(event) {
            if (event.target.classList.contains('approve-button')) {
                const userId = event.target.dataset.userid; // Get userId from data attribute
                approveUser(userId); 
            }
        });

        async function getLandDetails() {
            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 lands = await contract.getRegisteredLandIds();
                console.log(lands);
                const landIdsLength = lands.length;
                const landIds = lands.map(land => parseInt(land, 16));
                console.log('Land IDs Length:', landIdsLength);
                console.log('Land IDs:', landIds);
        
                for (let i = 0; i < landIdsLength; i++) {
                    const landId = landIds[i];
                    const lands = await contract.getLandDetails(landId);
                    console.log(`Details for Land ID ${landId}:`, lands);
        
                    if (!lands.isLandVerified) {
                        const hash=lands.landDetails;
                        db.get('userDetails').get(hash).once((data) => {
                            if (data) {
                                ({ propertyID, surveyNo, fileUrl } = data);
                                console.log('Property ID:', propertyID);
                                console.log('Survey No:', surveyNo);
                                console.log('File URL:', fileUrl);
                                const tableBody = document.getElementById('landRegistrationBody');
                                const row = document.createElement('tr');
                                row.innerHTML = `
                                    <td>${landId}</td>
                                    <td>${propertyID}</td>
                                    <td>${surveyNo}</td>
                                    <td>${lands.landAddress}</td>
                                    <td>${lands.area}</td>
                                    <td>${lands.landPrice}</td>
                                    <td><a href=${fileUrl} target="_blank">View Document</a></td>
                                    <td>${lands.ownerId}</td>
                                    <td>
                                        <button class="btn btn-dark approve-land-button " data-userid="${landId}">
                                                <i class="bi bi-check"></i> Approve
                                        </button>
                                    </td>
                                `;
                                tableBody.appendChild(row);
                                    } else {
                                        console.log('No user details found for the given hash.');
                                    }
                        });
                    }
                }
                displayApprovedSaleRequest();       
            } catch (error) {
                console.error('Error fetching land details:', error);
            }
        }
        
        async function approveLand(landId) {
            try {
                await window.ethereum.request({ method: 'eth_requestAccounts' });
                const provider = new ethers.providers.Web3Provider(window.ethereum);
                const signer = provider.getSigner();
                const contract = new ethers.Contract(contractAddress, contractABI, signer);             
                const lands= await contract.getLandDetails(landId);
                ownerId=lands.ownerId;
                const hash=lands.landDetails;
                const ownerDetails= await contract.getUserDetails(ownerId);
                const ownerAddress=ownerDetails.accountAddress; 
                db.get('userDetails').get(hash).once((data) => {
                    if (data) {
                        const { NFT_token_uri } = data;
                        console.log('Token URI', NFT_token_uri);
                        mintNFTWithTokenURI(landId, ownerAddress, NFT_token_uri);
                    } else {
                        console.log('No user details found for the given hash.');
                    }
                });
                const tx = await contract.verifyLand(landId);
                const receipt = await tx.wait(); 
                console.log(`Land with ID ${landId} verified successfully.`);
                console.log('Transaction Receipt:', receipt);
                getLandDetails();
            } catch (error) {
                console.error('Error approving land:', error);
            }
        }
        async function mintNFTWithTokenURI(landId, ownerAddress, NFT_token_uri) {
            try {
                await window.ethereum.request({ method: 'eth_requestAccounts' });
                const provider = new ethers.providers.Web3Provider(window.ethereum);
                const signer = provider.getSigner();
                const contract2 = new ethers.Contract(contractAddress2, contractABI2, signer);
                const tokenURI=NFT_token_uri
                const tx = await contract2.mintNFT( ownerAddress, landId, tokenURI);
                const receipt = await tx.wait(); 
                console.log(`NFT minted successfully for land ID ${landId}.`);
                console.log('Transaction Receipt:', receipt);
                getLandDetails();
                window.location.reload(true);
            } catch (error) {
                console.error('Error minting NFT:', error);
            }
        }
        
        getLandDetails();
        
        document.addEventListener('click', function(event) {
            if (event.target.classList.contains('approve-land-button')) {
                const row = event.target.closest('tr');
                if (row) {
                    const landIdCell = row.querySelector('td:first-child'); // Assuming landId is the first column
                    if (landIdCell) {
                        const landId = landIdCell.textContent.trim();
                        console.log('Land ID:', landId);
                        approveLand(landId); 
                    }
                }
            }
        });

        async function displayApprovedSaleRequest() {
            await window.ethereum.request({ method: 'eth_requestAccounts' });
            const provider = new ethers.providers.Web3Provider(window.ethereum);
            const signer = provider.getSigner();
            const contract = new ethers.Contract(contractAddress, contractABI, signer);
            try {
                const { saleTokenId, landId } = await contract.getLatestSaleAndLandId();
                console.log('Sale ID:', saleTokenId, landId);
                const saleId = parseInt(saleTokenId, 16)
                const landId2 = parseInt(landId, 16)
                console.log('User ID (Integer):', saleId, landId2)
                if (saleTokenId !== landId && buyerId !== 0) {
                    const saleDetails = await contract.getSaleDetailsForApproval(landId2);
                    console.log('Sale Details:', saleDetails);
                    document.querySelector('.card-title').textContent = `Land ID: ${landId2}`;
                    document.querySelector('.card-text:nth-of-type(1)').textContent = `Owner Address: ${saleDetails.ownerAddress}`;
                    document.querySelector('.card-text:nth-of-type(2)').textContent = `Owner ID: ${saleDetails.ownerId}`;
                    document.querySelector('.card-text:nth-of-type(3)').textContent = `Buyer Address: ${saleDetails.buyer}`;
                    document.querySelector('.card-text:nth-of-type(4)').textContent = `Buyer ID: ${saleDetails.buyerId}`;
                    document.querySelector('.card-text:nth-of-type(5)').textContent = `Proof URL: ${saleDetails.proofUrl}`;

                    const approveButton = document.getElementById('approveBtn');
                    approveButton.addEventListener('click', () => approveSaleByAuthority(landId2));
                }
            } catch (error) {
                console.error('Error fetching sale details:', error);
            }
        }

        async function approveSaleByAuthority(landId) {
            try {
                await window.ethereum.request({ method: 'eth_requestAccounts' });
                const provider = new ethers.providers.Web3Provider(window.ethereum);
                const signer = provider.getSigner();
                const contract = new ethers.Contract(contractAddress, contractABI, signer);
                const contract2 = new ethers.Contract(contractAddress2, contractABI2, signer);
                const saleDetails = await contract.getSaleDetailsForApproval(landId);
                const from = saleDetails.ownerAddress;
                const to = saleDetails.buyer;
                console.log(from, to, landId)
                const tokenId=landId;
                const transferTx = await contract2.transferNFT(from, to, tokenId);
                const transferReceipt = await transferTx.wait();
                console.log('NFT transferred:', transferReceipt);
                const approveTx = await contract.approveSaleByAuthority(landId);
                const approveReceipt = await approveTx.wait();
                console.log('Sale approved by authority:', approveReceipt);
                alert('Sale approved successfully by authority!');
                window.location.reload(true);
            } catch (error) {
                console.error('Error approving sale by authority:', error);
            }
        }

         
    </script>
</body>
