<% layout('./layouts/boilerplate') %>
<body>
    <div style="height: 110px;">  </div>
    <section class="mt-3 pb-5">
        <div class="col-8 offset-1 mt-2 mb-2">
            <h2>Land Details:</h2>
        </div>
        <div class="col-6 offset-4 mt-2 show-card">
            <img src="https://media.istockphoto.com/id/909423306/photo/modern-multilevel-house-exterior-with-pool.webp?b=1&s=170667a&w=0&k=20&c=lVkUVRVlGBio7oMSYkx_tQuydlhJnBkpnVSuBBHtRMM="
                class="card-img-top show-image" alt="show-image">
            <div class="showcard-body">
                <p class="card-text"><b>Land Id: </b><span id="landid"></span></p>
                <p class="card-text"><b>Owned by </b> <span id="owner"></span></p>
                <p class="card-text"><b>Unit area: </b><span id="area"></span></p>
                <p class="card-text"><b>Land address: </b><span id="address"></span></p>
                <p class="card-text"><b>Price: </b><span id="price"></span></p>
                <p class="card-text"><b>Phone Number: </b><span id="phno"></span></p>
                <p class="card-text"><b>Email: </b><span id="email"></span></p>
            </div>
            <button id="buyButton" class="mt-3 button btn-dark">Request For Buy</button>
        </div>
        <script>
        </script>
    
        <div style="height: 200px;">  </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>
        const contractABI = JSON.parse('<%- JSON.stringify(contractABI) %>');
        const contractAddress = "0xf7dB55e79E0cbb4E8E016bB22c25DbA13901DCca"; // Your contract address

        async function fetchLandDetails(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 landDetails = await contract.getLandDetailsUser(landId);
                console.log('Land Details:', landDetails);

                // Fetch current user details
                const myDetails = await contract.getMyDetails();
                console.log('My Details:', myDetails);


                // Update DOM with fetched data
                document.getElementById('owner').innerText = landDetails.ownerName;
                document.getElementById('landid').innerText = landId;
                document.getElementById('area').innerText = landDetails.area;
                document.getElementById('address').innerText = landDetails.landAddress;
                document.getElementById('price').innerText = landDetails.landPrice;
                document.getElementById('phno').innerText = landDetails.ownerPhoneNumber;
                document.getElementById('email').innerText = landDetails.ownerEmail;
                const isLandOwner = (myDetails.phoneNumber === landDetails.ownerPhoneNumber &&
                myDetails.email === landDetails.ownerEmail);
                
                const buyButton = document.getElementById('buyButton');
                if (isLandOwner) {
                    buyButton.disabled = true;
                } else {
                    buyButton.addEventListener('click', () => requestToBuyLand(contract, landId, buyButton));
                }
            } catch (error) {
                console.error('Error fetching land details:', error);
            }
        }

        // Extract landId from URL
        const urlParams = new URLSearchParams(window.location.search);
        const landId = urlParams.get('landId');
        async function requestToBuyLand(contract, landId, buttonElement) {
            try {
                const tx = await contract.requestToBuyLand(landId);
                tx.wait();
                console.log(tx.receipt);
                buttonElement.innerText = 'Buy Request Done';
                buttonElement.disabled = true;
            } catch (error) {
                console.error('Error requesting to buy land:', error);
                alert("Land Not Listed For Sale !")
            }
        }
        if (landId) {
            fetchLandDetails(landId);
        } else {
            console.error('Land ID not found in URL parameters.');
        }
    </script>
</body>
</html>
