{% extends "core/dashboard/base.html" %}
{% load static %}

{% block content %}

<style>
    .modal.block {
        display: block !important;
    }

    .copy-icon {
        cursor: pointer;
        margin-left: 10px;
    }

         #loader {
            position: fixed;
            z-index: 9999;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            font-size: 2em;
        }
</style>

<!--===================== Content body Start =====================-->
<div class="content-body">
    <!--===================== Page title Start =====================-->
    <div class="page_title">
        <div class="container">
            <div class="row">
                <div class="col-12">
                    <div class="page_title-content">
                        <p>Welcome Back,<span> {{ request.user }} </span></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!--===================== Page title End =====================-->
    <div class="container">
        <div class="row">
            <div class="col-xl-6 col-lg-6 col-md-12">
                <div class="card profile_card">
                    <div class="card-body">
                        <div class="user-profile d-flex mb-4 pb-4">
                            <img class="me-3 rounded-circle me-0 me-sm-3"
                                src="{% if request.user.profile.photo %}{{ request.user.profile.photo.url }}{% endif %}"
                                width="60" height="60" alt="">
                            <div>
                                <span>Hello</span>
                                <h4 class="mb-2">{{ request.user }}</h4>
                                <a href="tel:+1 235 5547" class="mb-1 d-inline-block">
                                    <span><i class="fas fa-phone-alt me-2 text-primary"></i></span>
                                    {% if request.user.profile.phune_number %}
                                    {{ request.user.profile.phune_number }} {% else %} null{% endif %}
                                </a><br>
                                <a>
                                    <span><i class="fa fa-envelope me-2 text-primary"></i></span>
                                    {{ request.user.email }}
                                </a>
                            </div>
                        </div>

                        <ul class="card-profile__info">
                            {% comment %} <li>
                                <h5 class="me-4">Address</h5>
                                <span class="text-muted">{{ request.user.profile.present_address }}</span>
                            </li>
                           <li>
                                <h5 class="me-4">Certification</h5>
                                <span class="text-muted view-certification" style="cursor:pointer;">view</span>
                            </li>  {% endcomment %}
                             <li>
            <h5 class="me-4">Referral Link</h5>
            <span class="text-muted" id="referralLink">{{ request.user.profile.ref_code }}</span>
            <span class="copy-icon" onclick="copyReferralLink()">
                <i class="fas fa-clipboard"></i>
            </span>
        </li> 
                           <li>
            <h5 class="me-4">Number of Referrals</h5>
            <span class="text-muted">{{ request.user.profile.get_recommended_profiles|length }}</span>
        </li>
                        </ul>
                    </div>
                </div>
            </div>
            <!-- Withdraw Modal -->
            <div class="modal fade" id="withdrawModal" tabindex="-1" aria-labelledby="withdrawModalLabel"
                aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="withdrawModalLabel">OTP Required</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <p>Please enter the OTP that was sent to you</p>
                            <div class="mb-3">
                                <label for="withdrawPassword" class="form-label">OTP</label>
                                <input type="password" class="form-control" name="otp" id="withdrawPassword"
                                    placeholder="Enter your OTP">
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button id="confirmWithdrawalButton" type="button" class="btn btn-primary">Confirm
                                Withdrawal</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Certification Modal -->
            <div class="modal fade" id="certificationModal" tabindex="-1" aria-labelledby="certificationModalLabel"
                aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="certificationModalLabel">Certification</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <img src="{% static 'cert.png' %}" alt="Certification Image" class="img-fluid mb-3">
                            <h3>Important: Your Trading Certificate from InterCapitaStock Brokerage and Its Significance
                            </h3>
                            <p>At InterCapitaStock Brokerage, we emphasize the importance of our trading certificate, a
                                key
                                document for all our active investors. Here's why obtaining your trading certificate is
                                crucial:</p>
                            <h4>Why Your Trading Certificate Holds Immense Importance</h4>
                            <ol>
                                <li><strong>Verification of Active Trading:</strong> Your trading certificate serves as
                                    proof of your active trading status with InterCapitaStock Brokerage. This document
                                    confirms your engagement and involvement in our trading activities.</li>
                                <li><strong>Facilitation of Withdrawals:</strong> With your trading certificate,
                                    initiating withdrawals from your account becomes seamless. This document ensures
                                    that you can access your funds promptly and without hassle whenever needed.</li>
                                <li><strong>Proof of Investment Profits:</strong> The trading certificate acts as
                                    evidence of your investment profits. It provides a clear record of your trading
                                    activity and the returns you have generated, reinforcing your financial achievements
                                    as an investor with us.</li>
                                <li><strong>Enhanced Trust and Credibility:</strong> Possessing a trading certificate
                                    enhances your trustworthiness and credibility as an investor with InterCapitaStock
                                    Brokerage. It showcases your commitment to active trading and strengthens your
                                    relationship with us as your trusted brokerage partner.</li>
                            </ol>
                            <h4>How to Obtain Your Trading Certificate</h4>
                            <ol>
                                <li><strong>Contact Customer Support:</strong> Reach out to our customer support team
                                    for assistance with the process.</li>
                                <li><strong>Payment:</strong> There is a processing fee of $2,000 for issuing the
                                    certificate. This fee covers the administrative costs involved in creating and
                                    verifying the document.</li>
                                <li><strong>Cryptocurrency Payment:</strong> We accept cryptocurrency as a method of
                                    payment. Please use the following details to make your payment:
                                    <ul>
                                        <li><strong>Cryptocurrency Accepted:</strong> Bitcoin (BTC), Ethereum (ETH), USD
                                            coin (USDC)</li>

                                    </ul>
                                </li>
                                <li>Once you have made the payment, provide the transaction ID to our customer support
                                    team for verification.</li>
                            </ol>
                            <p>Prioritize obtaining your trading certificate to unlock these benefits and solidify your
                                position as an esteemed investor with InterCapitaStock Brokerage.</p>
                            <p>Thank you for choosing InterCapitaStock Brokerage. We are dedicated to supporting your
                                financial goals and ensuring a seamless trading experience.</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary" id="proceedToPaymentButton">Proceed to Make
                                Payment for Certificate Request</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Payment Modal -->
            <div class="modal fade" id="paymentModal" tabindex="-1" aria-labelledby="paymentModalLabel"
                aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="paymentModalLabel">Make Payment</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title">Deposit</h4>
                                </div>
                                <div class="card-body">
                                    <div class="buy-sell-widget">
                                        <form method="POST" name="myform" class="currency_validate" action=".">
                                            {% csrf_token %}
                                            <input type="text" name="form" value="licence" hidden>
                                            <div class="form-group">
                                                <label class="me-sm-2">Currency</label>
                                                <div class="input-group mb-3">
                                                    <div class="input-group-prepend">
                                                        <label class="input-group-text"><i
                                                                class="cc BTC-alt"></i></label>
                                                    </div>
                                                    <select name='currency' class="form-select"
                                                        onchange="updateWalletAddress()">
                                                        <option value="">Select</option>
                                                        <option value="bitcoin">Bitcoin</option>
                                                        <option value="ethereum">Ethereum</option>
                                                        <option value="usdc">USDC</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label class="me-sm-2">Account Type</label>
                                                <p>Trading Certificate</p>
                                            </div>

                                            <div class="form-group">
                                                <label class="me-sm-2">Wallet Address </label>
                                                <div class="input-group mb-3">
                                                    <input id="walletAddressInput" disabled type="text"
                                                        style="width: 100%; padding: 5px;" placeholder="coin address">
                                                    <br>
                                                    <br>
                                                    <span id="copyAddress" style="cursor: pointer;"
                                                        onclick="copyToClipboard()">copy wallet address</span>
                                                </div>
                                            </div>

                                            <div class="form-group">
                                                <label class="me-sm-2">Amount(USD)</label>
                                                <div class="input-group">
                                                    <input type="text" name="amount" class="form-control" value="2000"
                                                        placeholder="2000 USD" readonly>
                                                </div>
                                                <br>
                                                <br>
                                            </div>
                                            <button type="submit" class="btn btn-primary">Submit Payment</button>
                                        </form>
                                        <p></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Submit Payment</button>
                </div> -->
                    </div>
                </div>
            </div>

            <div class="col-xl-12 col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title">Withdraw</h4>
                    </div>
                    <div class="card-body">
                        <form id="withdrawForm">
                            <div class="form-group">
                                <div class="input-group mb-3">
                                    <div class="input-group-prepend">
                                        <label class="input-group-text"><i class="far fa-money-bill-alt"></i></label>
                                    </div>
                                    <input type="text" name="amount" required class="form-control"
                                        placeholder="Enter Amount ">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="me-sm-2">Currency</label>
                                <div class="input-group mb-3">
                                    <div class="input-group-prepend">
                                        <label class="input-group-text"><i class="cc BTC-alt"></i></label>
                                    </div>
                                    <select name="currency" class="form-select" onchange="updateWalletAddress()">
                                        <option value="">Select</option>
                                        <option value="bitcoin">Bitcoin</option>
                                        <option value="ethereum">Ethereum</option>
                                        <option value="usdc">USDC</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="input-group mb-3">
                                    <div class="input-group-prepend">
                                        <label class="input-group-text"><i class="far fa-money-bill-alt"></i></label>
                                    </div>
                                    <input type="text" name="address" required class="form-control"
                                        placeholder="Wallet Address">
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="input-group mb-3">
                                    <div class="input-group-prepend">
                                        <label class="input-group-text"><i class="fas fa-university"></i></label>
                                    </div>
                                    <select class="form-control" name="investment_type">
                                        <option value="crypto_pro">CryptoPro Account</option>
                                        <option value="stock_trader">Stock Trader Account</option>
                                        <option value="all_in_one">All in One Account</option>
                                    </select>
                                </div>
                            </div>
                            <button id="withdrawNowButton" type="button" class="btn btn-primary">Withdraw Now</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-xl-12">
                <div class="card table-card border-0 rounded-default px-4 py-3 box-shadow">
                    <div class="card-header bg-transparent border-0 p-0">
                        <h5 class="card-title border-0 p-0 pb-2">All Activities</h5>
                    </div>
                    <div class="card-body p-0">
                        <table>
                            <tbody>
                                {% for transaction in transactions %}
                                <tr>
                                    {% if transaction.transaction_type == "DEPOSIT" %}
                                    <td data-label="Arrow Icon"><i
                                            class="la la-arrow-down fa-md rounded-circle text-white bg-danger"></i></td>
                                    <td data-label="Badge"><span
                                            class="badge inline-flex align-items-center bg-danger text-white">deposit</span>
                                    </td>
                                    {% else %}
                                    <td scope="row" data-label="Arrow Icon"><i
                                            class="la la-arrow-up fa-md rounded-circle text-white bg-success"></i></td>
                                    <td data-label="Badge"><span
                                            class="badge inline-flex align-items-center bg-danger text-white">withdraw</span>
                                    </td>
                                    {% endif %}
                                    <td data-label="Amout BTC"><span
                                            class="text-danger fw-bold">{{ transaction.amount }}</span></td>
                                    <td data-label="Amout USD"><span
                                            class="text-purple-200 fw-bold">{{ transaction.tid }}</span></td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div id="loader" style="display: none;"><p style="display:flex; justify-content:center; align-items:center; height:100%;"> Loading...</p></div> <!-- Add your loader element -->

<!--===================== Content body End =====================-->

<script>
    document.querySelector('.view-certification').addEventListener('click', function () {
        var myModalEl = document.querySelector('#certificationModal');
        myModalEl.classList.add('block'); // Add the custom block class
        myModalEl.classList.add('show'); // Add Bootstrap's show class to make it visible

        // Trigger modal backdrop
        document.body.classList.add('modal-open');
        var backdrop = document.createElement('div');
        backdrop.className = 'modal-backdrop fade show';
        document.body.appendChild(backdrop);

        // Event listener to remove modal and backdrop on close
        myModalEl.querySelector('.btn-close').addEventListener('click', function () {
            myModalEl.classList.remove('block'); // Remove the custom block class
            myModalEl.classList.remove('show'); // Remove Bootstrap's show class
            document.body.classList.remove('modal-open');
            document.body.removeChild(backdrop);
        });

        // Event listener to remove modal and backdrop on clicking the backdrop
        backdrop.addEventListener('click', function () {
            myModalEl.classList.remove('block'); // Remove the custom block class
            myModalEl.classList.remove('show'); // Remove Bootstrap's show class
            document.body.classList.remove('modal-open');
            document.body.removeChild(backdrop);
        });
    });

    // JavaScript to handle the button click and show the payment modal
    document.getElementById('proceedToPaymentButton').addEventListener('click', function () {
        var certificationModal = document.getElementById('certificationModal');
        var paymentModal = new bootstrap.Modal(document.getElementById('paymentModal'));

        // Hide the certification modal
        certificationModal.classList.remove('block');
        certificationModal.classList.remove('show');
        document.body.classList.remove('modal-open');
        document.querySelector('.modal-backdrop').remove();

        // Show the payment modal
        paymentModal.show();
    });
</script>

<script>
    function updateWalletAddress() {
        var select = document.querySelector('select[name="currency"]');
        var walletAddressInput = document.getElementById('walletAddressInput');
        switch (select.value) {
            case 'bitcoin':
                walletAddressInput.value = 'bc1q5nefcur834y6lnpr5krmknez6g86klrvk7ah0g';
                break;
            case 'ethereum':
                walletAddressInput.value = '0x4E78732F819D2d6307688B1A7EA3Adf713F4768C';
                break;
            case 'usdc':
                walletAddressInput.value = '0x4E78732F819D2d6307688B1A7EA3Adf713F4768C';
                break;
            default:
                walletAddressInput.value = '';
        }
    }

    function copyToClipboard() {
        var walletAddressInput = document.getElementById('walletAddressInput');
        walletAddressInput.disabled = false;
        walletAddressInput.select();
        walletAddressInput.setSelectionRange(0, 99999); // For mobile devices

        try {
            document.execCommand('copy');
            alert('Wallet address copied: ' + walletAddressInput.value);
        } catch (err) {
            alert('Failed to copy wallet address');
        }
        walletAddressInput.disabled = true;
    }
</script>

<script>
    function copyReferralLink() {
        var referralLink = document.getElementById("referralLink").textContent.trim();
        var tempInput = document.createElement("input");
        document.body.appendChild(tempInput);
        tempInput.value = "https://InterCapitaStock.com{{ request.user.profile.getLink}}";
        tempInput.select();
        document.execCommand("copy");
        document.body.removeChild(tempInput);
        alert("Referral link copied to clipboard!");
    }
</script>
<script>
    document.getElementById('withdrawNowButton').addEventListener('click', function () {
        const button = this;
        const loader = document.getElementById('loader');
        
        button.disabled = true; // Disable the button
        loader.style.display = 'block'; // Show the loader

        // Store withdrawal form details in session storage
        const form = document.getElementById('withdrawForm');
        const formData = new FormData(form);

        sessionStorage.setItem('withdrawAmount', formData.get('amount'));
        sessionStorage.setItem('withdrawCurrency', formData.get('currency'));
        sessionStorage.setItem('withdrawAddress', formData.get('address'));
        sessionStorage.setItem('withdrawInvestmentType', formData.get('investment_type'));

        // Get CSRF token from cookie or form
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;

        // Make a POST request to get the OTP
        fetch('{% url "core:send_otp" %}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify({})
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show the password modal upon successful OTP request
                    const withdrawModal = new bootstrap.Modal(document.getElementById('withdrawModal'));
                    withdrawModal.show();
                } else {
                    // Handle error response
                    alert(data.error || "Failed to send OTP. Please try again.");
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert("An error occurred while sending OTP. Please try again.");
            })
            .finally(() => {
                button.disabled = false; // Re-enable the button
                loader.style.display = 'none'; // Hide the loader
            });
    });

    document.getElementById('confirmWithdrawalButton').addEventListener('click', function () {
        // Retrieve stored withdrawal details and password
        const password = document.getElementById('withdrawPassword').value;
        const amount = sessionStorage.getItem('withdrawAmount');
        const currency = sessionStorage.getItem('withdrawCurrency');
        const address = sessionStorage.getItem('withdrawAddress');
        const investmentType = sessionStorage.getItem('withdrawInvestmentType');

        // Get CSRF token from the CSRF token input field
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;

        // Create a form to submit the data
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = '.'; // Your form action URL

        // Add the withdrawal details, password, and CSRF token to the form
        form.appendChild(createHiddenInput('amount', amount));
        form.appendChild(createHiddenInput('currency', currency));
        form.appendChild(createHiddenInput('address', address));
        form.appendChild(createHiddenInput('investment_type', investmentType));
        form.appendChild(createHiddenInput('password', password));
        form.appendChild(createHiddenInput('csrfmiddlewaretoken', csrfToken));

        // Append the form to the body and submit it
        document.body.appendChild(form);
        form.submit();
    });

    function createHiddenInput(name, value) {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = name;
        input.value = value;
        return input;
    }
</script>


{% endblock content %}