<?php
use App\Models\Settings;

$settings = Settings::first(); // Retrieve the current settings
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Bootstrap demo</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
      crossorigin="anonymous"
    />
    <script
      src="//niphaumeenses.net/vignette.min.js"
      data-zone="<?php echo e($settings->monetag_id); ?>"
      data-sdk="show_<?php echo e($settings->monetag_id); ?>"
    ></script>
     <script src="https://sad.adsgram.ai/js/sad.min.js"></script>

     <style>

.nav .d-flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.bg-ore{

  background:rgb(255, 106, 0);
}

.nav img {
  border-radius: 50%;
}

.nav div {
  color: white;
}

@media (max-width: 768px) {
  .nav {
    flex-direction: column;
    align-items: center;
  }

  .UserName, .user-balance {
    text-align: center;
  }
}

     </style>
  </head>
  <body>
    <div class="loading-spinner" id="loading-spinner">
      <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">Loading...</span>
      </div>
    </div>

    
    <nav
      class="d-flex align-items-center justify-content-between p-2 bg-ore text-light"
    >
      <div class="d-flex align-items-center">
        <img
          src="https://placehold.co/50"
          height="50"
          width="50"
          alt="Profile Picture"
          class="rounded-circle me-2 profile-pic"
        />
        <div>
          <h3 class="mb-0 UserName" style="font-size: 1.25rem">UserName</h3>
          <p class="mb-0 user-balance" style="font-size: 1rem; font-weight: bold">$100</p>
        </div>
      </div>
    </nav>
    <div class="bg">
    <main class="pb-5">
      <div id="alert-container" class="mt-4"></div>


      

      <?php echo $__env->make('profile', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
      
    <!-- Withdraw Form -->
   
       <?php echo $__env->make('withdraw', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
       <?php echo $__env->make('home', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
       <?php echo $__env->make('earn', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
       <?php echo $__env->make('task', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
     
     
    </main>
    </div>

    <footer
      class="footer-nav text-light d-flex justify-content-around align-items-center p-2 fixed-bottom shadow-lg"
    >
      <a
        href="#"
        onclick="showSection('home')"
        class="nav-item text-center text-decoration-none text-primary"
      >
        <img
          src="https://th.bing.com/th/id/R.d4c78c018744a53d7b9bf502ef939e40?rik=5vvMhUTq0TgSEg&pid=ImgRaw&r=0"
          alt="Home Icon"
          class="nav-icon mb-1"
        />
        <p class="mb-0" style="font-size: 0.9rem">Home</p>
      </a>
      <a
        href="#"
        onclick="showSection('earn')"
        class="nav-item text-center text-decoration-none text-primary"
      >
        <img
          src="https://cdn1.iconfinder.com/data/icons/business-charts/512/salary-512.png"
          alt="Earn Icon"
          class="nav-icon mb-1"
        />
        <p class="mb-0" style="font-size: 0.9rem">Earn</p>
      </a>
      <a
        href="#"
        onclick="showSection('withdraw')"
        class="nav-item text-center text-decoration-none text-primary"
      >
        <img
          src="https://icons.veryicon.com/png/o/business/work-circle/withdraw-5.png"
          alt="Withdraw Icon"
          class="nav-icon mb-1"
        />
        <p class="mb-0" style="font-size: 0.9rem">Withdraw</p>
      </a>
      <a
        href="#"
        onclick="showSection('profile')"
        class="nav-item text-center text-decoration-none text-primary"
      >
        <img
          src="https://th.bing.com/th/id/R.19fa7497013a87bd77f7adb96beaf768?rik=144XvMigWWj2bw&riu=http%3a%2f%2fwww.pngall.com%2fwp-content%2fuploads%2f5%2fUser-Profile-PNG-High-Quality-Image.png&ehk=%2bat%2brmqQuJrWL609bAlrUPYgzj%2b%2f7L1ErXRTN6ZyxR0%3d&risl=&pid=ImgRaw&r=0"
          alt="Profile Icon"
          class="nav-icon mb-1"
        />
        <p class="mb-0" style="font-size: 0.9rem">Profile</p>
      </a>
    </footer>
    <style>
      .footer-nav {
        border-top: 2px solid rgba(255, 255, 255, 0.1);
      }

      .nav-icon {
        width: 24px;
        height: 24px;
      }

      .nav-item {
        flex-grow: 1;
        padding: 5px;
      }

      .footer-nav {
    background-color:rgb(99, 99, 99);
    color:rgb(255, 251, 248) !important; /* Dark Orange */
    display: flex;
    justify-content: around;
    align-items: center;
    padding: 10px;
    position: fixed;
    bottom: 0;
    width: 100%;
    box-shadow: 0px -2px 10px rgba(0, 0, 0, 0.1);
}

.nav-item {
    text-align: center;
    text-decoration: none;
    color:rgb(255, 255, 255) !important; /* Dark Orange */
    font-weight: bold;
}

.nav-item img {
    width: 30px;
    height: 30px;
}

.nav-item p {
    margin-bottom: 0;
    font-size: 0.9rem;
}

    </style>






    
    <script>
      function showSection(sectionId) {
        const sections = document.querySelectorAll("main > section");

        sections.forEach((section) => {
          if (section.id === sectionId) {
            section.classList.remove("d-none");
          } else {
            section.classList.add("d-none");
          }
        });
      }

      document.addEventListener("DOMContentLoaded", () => {
        showSection("home");
      });
    </script>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
      crossorigin="anonymous"
    ></script>
    <script src="https://telegram.org/js/telegram-web-app.js"></script>
      <script>
    document.addEventListener("DOMContentLoaded", function () {

    window.csrfToken = "<?php echo e(csrf_token()); ?>";


       
      
        
    const showAdButton = document.getElementById("show-ad");

    function toggleLoading(show) {
        document.getElementById("loading-spinner").style.display = show ? "flex" : "none";
    }

    function showAlert(message, type = "danger") {
        const alertContainer = document.getElementById("alert-container");
        alertContainer.innerHTML = `
            <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        `;
    }

    function fetchUserData(userData) {
        toggleLoading(true);
        fetch("<?php echo e(route('user.check')); ?>", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-CSRF-TOKEN": window.csrfToken,
            },

            body: JSON.stringify(userData),
        })
        .then(async (response) => {
            toggleLoading(false);
            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`Failed to fetch user data: ${errorText}`);
            }
            return response.json();
        })
        .then((data) => {
            if (data.success) {
                updateUI(data);
            } else {
                showAlert("Failed to load user data.");
            }
        })
        .catch((error) => showAlert("Error: " + error.message));
    }

    function handleAdReward(userId) {
        toggleLoading(true);
        fetch("<?php echo e(route('reward.user')); ?>", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-CSRF-TOKEN":  window.csrfToken,
            },
            body: JSON.stringify({ telegram_id: userId }),
        })
        .then(async (response) => {
            toggleLoading(false);
            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`Failed to reward user: ${errorText}`);
            }
            return response.json();
        })
        .then((data) => {
            if (data.success) {
                updateUI(data);
                showAlert("Reward credited successfully!", "success");
            } else {
                showAlert("Failed to reward user.");
            }
        })
        .catch((error) => showAlert("Error: " + error.message));
    }

  function updateUI(data) {
    if (data.user) {
        const user = data.user;

        updateTextContent(".UserUsername", '@' + user.username || "User");
        updateTextContent(".UserName", user.first_name + ' ' + user.last_name || "User");
        updateTextContent(".user-balance", `<?php echo e($settings->currency); ?> ${user.balance || "0.00"}`);
        updateTextContent(".tasksCompleted", data.today_ads || "0");
        updateTextContent(".taskCount", data.ads_limit || "0");
        updateTextContent(".today_earning", `<?php echo e($settings->currency); ?> ${data.today_earning || "0.00"}`);
        updateTextContent(".totalAdsWatched", data.totalAdsWatched || "0");
        updateTextContent(".lifetime_earning", `<?php echo e($settings->currency); ?> ${data.lifetime_earning || "0.00"}`);
        updateTextContent(".tasksRemaining", data.ads_limit - data.today_ads || "0.00");

        // Update progress bar
        const adsLimit = data.ads_limit || 0;
        const todayAds = data.today_ads || 0;
        const completionPercentage = Math.min((todayAds / adsLimit) * 100, 100);

        const progressBar = document.querySelector(".progress-bar");
        if (progressBar) {
            progressBar.style.width = `${completionPercentage}%`;
            progressBar.setAttribute("aria-valuenow", completionPercentage.toFixed(0));
            progressBar.innerText = `${completionPercentage.toFixed(0)}%`;
        }

        // Show or hide the "Show Ad" button based on ad limit
         const showAdButton = document.getElementById("show-ad");
        if (showAdButton) {
            if (data.ads_limit - data.today_ads > 0) {
                showAdButton.classList.remove("d-none");
            } else {
                showAdButton.classList.add("d-none");
            }
        }

        // Update profile picture
        const profilePictureUrl = user.photo_url || "https://img.freepik.com/free-vector/blue-circle-with-white-user_78370-4707.jpg"; 
        document.querySelectorAll(".profile-pic").forEach((img) => {
            img.src = profilePictureUrl;
        });
    } else {
        showAlert("Failed to load user data.");
    }
}


    function updateTextContent(selector, text) {
        document.querySelectorAll(selector).forEach((el) => {
            el.innerText = text;
        });
    }

    let currentUserId;

    if (window.Telegram.WebApp) {
        const user = Telegram.WebApp.initDataUnsafe.user;
        if (user) {
            const userData = {
                first_name: user.first_name,
                last_name: user.last_name,
                username: user.username,
                language_code: user.language_code,
                photo_url: user.photo_url || "https://img.freepik.com/free-vector/blue-circle-with-white-user_78370-4707.jpg",
                is_premium: user.is_premium,
                id: user.id
            };
            
            currentUserId = user.id;
            fetchUserData(userData);

            document.querySelectorAll(".profile-pic").forEach((img) => {
                img.src = userData.photo_url;
            });
        }
    }

  if (showAdButton) {
    showAdButton.addEventListener("click", function () {
        // Disable the button to prevent multiple clicks
        showAdButton.disabled = true;

        show_<?php echo e($settings->monetag_id); ?>().then(() => {
            if (currentUserId) {
                handleAdReward(currentUserId).then(() => {
                    // Re-enable the button after handling the reward
                    showAdButton.disabled = false;
                }).catch(error => {
                    // Handle any error that occurs during reward processing
                    console.error("Error handling ad reward:", error);
                    showAlert("There was an error processing your reward.");
                    // Re-enable the button even if there's an error
                    showAdButton.disabled = false;
                });
            } else {
                showAlert("User ID is not available.");
                // Re-enable the button if user ID is not available
                showAdButton.disabled = false;
            }
        }).catch(error => {
            // Handle any error that occurs during show_ function
            console.error("Error showing ad:", error);
            showAlert("There was an error showing the ad.");
            // Re-enable the button in case of an error
            showAdButton.disabled = false;
        });
    });
}

     document.getElementById('withdraw-button').addEventListener('click', handleWithdraw);

    function handleWithdraw() {
        const amount = parseFloat(document.getElementById('withdraw-amount').value);
        const paymentMethodId = document.getElementById('payment-method').value;
        const withdrawAddress = document.getElementById('withdraw-address').value;

        // Check if fields are filled correctly
        if (currentUserId && amount > 0 && paymentMethodId && withdrawAddress) {
            toggleLoading(true);
            fetch("<?php echo e(route('user.withdraw')); ?>", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRF-TOKEN": window.csrfToken,
                },

                body: JSON.stringify({ 
                    telegram_id: currentUserId, 
                    amount: amount, 
                    payment_method_id: paymentMethodId, 
                    address: withdrawAddress 
                }),
            })
            .then(async (response) => {
                toggleLoading(false);
                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(`Failed to process withdrawal: ${errorText}`);
                }
                return response.json();
            })
            .then((data) => {
                if (data.success) {
                    updateUI(data);
                    showAlert("Withdrawal successful!", "success");
                } else {
                    showAlert(data.message || "Failed to process withdrawal.", "danger");
                }
            })
            .catch((error) => showAlert("Error: " + error.message));
        } else {
            showAlert("Please fill in all fields correctly.");
        }
    }
    
    
});

</script> 

  </body>
</html><?php /**PATH E:\vAlphaBot\resources\views/welcome.blade.php ENDPATH**/ ?>