<!-- Updated Plan Section -->
<section>
    <div class="custom-container">
      <div class="title">
        <h2>Active Power Plans </h2>
        <a href="bill">See all</a>
      </div>
      <div class="row g-3">
        <?php
        $plans = getAllPlans();
        ?>

      <div class="row">
  <?php if (!empty($plans)): ?>
    <?php foreach ($plans as $plan): ?>
      <?php 
        // get powers for this plan
        $powers = getPlanPowers($plan['id']); 
      ?>
      
      <div class="col-md-3 col-6">
        <div class="bill-box">
          <div class="d-flex gap-3">
            <div class="bill-icon">
              <!-- You can make icons dynamic if needed -->
              <img class="img-fluid icon" src="assets/images/svg/9.svg" alt="<?php echo $plan['name']; ?>" />
            </div>
            <div class="bill-details">
              <h5 class="dark-text"><?php echo $plan['name']; ?></h5>
              <h6 class="light-text mt-2">
                <?php echo $plan['description']; ?>
              </h6>
            </div>
          </div>
          <div class="bill-price">
            <h5><?php echo $site['currency']." ".number_format($plan['price'], 2); ?></h5>
            <a href="#pay<?php echo $plan['id']; ?>" data-bs-toggle="modal" class="btn bill-pay bill-paid ">Buy</a>
          </div>
        </div>
      </div>

      
                    <!-- Transaction Detail Modal -->
                    <div class="modal successful-modal transfer-details fade" id="pay<?php echo $plan['id'];?>" tabindex="-1">
                      <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                          <div class="modal-header">
                            <h2 class="modal-title">Plan Details</h2>
                          </div>
                          <div class="modal-body">
                            <ul class="details-list">
                              <li>
                                <h3 class="fw-normal dark-text">Plan</h3>
                                <h3 class="fw-normal light-text"><?php echo ucfirst($plan['name']); ?></h3>
                              </li>
                              <li>
                                <h3 class="fw-normal dark-text">Daily Earnings</h3>
                                <h3 class="fw-normal light-text"><?php echo ucfirst($powers[0]['reward']); ?></h3>
                              </li>
                              <li>
                                <h3 class="fw-normal dark-text">Referal Bonus</h3>
                                <h3 class="fw-normal light-text"><?php echo $plan['referral_bonus']; ?></h3>
                              </li>
                              <li>
                                <h3 class="fw-normal dark-text">Power</h3>
                                <h3 class="fw-normal light-text"><?php echo ($powers[0]['min_value']); ?></h3>
                              </li>
                              <li class="amount">
                                <h3 class="fw-normal dark-text">Amount</h3>
                                <h3 class="fw-semibold text-success">
                                  <?php echo $site['currency']." ".number_format($plan['price'], 2); ?>
                                </h3>
                              </li>
                              <li class="d-flex">
                             <button type="button" class="btn btn-primary buy-btn ms-auto" 
                data-id="<?php echo $plan['id']; ?>"
        data-price="<?php echo $plan['price']; ?>"
        data-name="<?php echo $plan['name']; ?>">
          <span class="btn-text">Buy Plan</span>
          <span class="btn-spinner d-none">
            <span class="spinner-border spinner-border-sm" role="status"></span>
            Processing...
          </span>
        </button>  
                            </li>
                            </ul>
                          </div>
                          <button type="button" class="btn close-btn" data-bs-dismiss="modal">
                            <i class="icon" data-feather="x"></i>
                          </button>
                        </div>
                      </div>
                    </div>
                    <!-- End Transaction Detail Modal -->
    <?php endforeach; ?>
  <?php else: ?>
    <p>No plans found.</p>
  <?php endif; ?>
</div>

      </div>
    </div>
    
    <!-- Fixed Toast -->
    <div class="position-fixed top-0 end-0 p-3" style="z-index: 9999">
      <div id="toastBox" class="toast align-items-center border-0" role="alert">
        <div class="d-flex">
          <div class="toast-body" id="toastMsg">Loading...</div>
          <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
      </div>
    </div>

</section>

<script>
document.querySelectorAll(".buy-btn").forEach(btn => {
  btn.addEventListener("click", function () {
    let planId = this.getAttribute("data-id");
    let planName = this.getAttribute("data-name");
    let toastEl = document.getElementById("toastBox");
    let toastMsg = document.getElementById("toastMsg");
    let toast = new bootstrap.Toast(toastEl);
    
    // Get button elements
    let btnText = this.querySelector('.btn-text');
    let btnSpinner = this.querySelector('.btn-spinner');

    // Disable button and show processing state
    this.disabled = true;
    btnText.classList.add('d-none');
    btnSpinner.classList.remove('d-none');

    // Show processing toast
    toastMsg.innerHTML = `Processing purchase of ${planName}...`;
    toastEl.className = "toast align-items-center text-bg-primary border-0";
    toast.show();

    // Send request
    fetch("process/buy-plan.php", {
      method: "POST",
      headers: {"Content-Type": "application/x-www-form-urlencoded"},
      body: "plan_id=" + planId
    })
    .then(res => {
      if (!res.ok) {
        throw new Error(`HTTP error! status: ${res.status}`);
      }
      return res.json();
    })
    .then(data => {
      console.log('Response:', data); // Debug log
      
      // Reset button state
      this.disabled = false;
      btnText.classList.remove('d-none');
      btnSpinner.classList.add('d-none');
      
      // Check for success using the correct property
      if (data.status === 'success') {
        toastMsg.innerHTML = `✅ ${data.message}`;
        toastEl.className = "toast align-items-center text-bg-success border-0";
        
        // Auto-close modal on success
        let modal = bootstrap.Modal.getInstance(this.closest('.modal'));
        if (modal) {
          setTimeout(() => modal.hide(), 1500);
        }
        
        // Optionally reload balance or update UI
        setTimeout(() => {
          window.location.reload(); // or update balance dynamically
        }, 2000);
        
      } else {
        toastMsg.innerHTML = `❌ ${data.message || 'Purchase failed'}`;
        toastEl.className = "toast align-items-center text-bg-danger border-0";
      }
      
      // Ensure toast stays visible
      toast.show();
    })
    .catch(error => {
      console.error('Error:', error); // Debug log
      
      // Reset button state
      this.disabled = false;
      btnText.classList.remove('d-none');
      btnSpinner.classList.add('d-none');
      
      toastMsg.innerHTML = "⚠️ Network error! Please try again.";
      toastEl.className = "toast align-items-center text-bg-danger border-0";
      toast.show();
    });
  });
});

// Ensure toast positioning is always correct
document.addEventListener('DOMContentLoaded', function() {
  const toastEl = document.getElementById('toastBox');
  if (toastEl) {
    toastEl.addEventListener('shown.bs.toast', function() {
      this.style.position = 'fixed';
      this.style.top = '20px';
      this.style.right = '20px';
      this.style.zIndex = '9999';
    });
  }
});
</script>

<style>
/* Additional styles for better UX */
.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.btn-spinner {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.spinner-border-sm {
  width: 1rem;
  height: 1rem;
}

.toast {
  min-width: 300px;
  max-width: 400px;
}

.toast-body {
  font-weight: 500;
}

/* Success state styling */
.text-bg-success .btn-close {
  filter: invert(1);
}

.text-bg-danger .btn-close {
  filter: invert(1);
}

.text-bg-primary .btn-close {
  filter: invert(1);
}
</style>