<?php 
include "includes/session.php";

?>
<!DOCTYPE html>
<html lang="en">


<!-- Mirrored from themes.pixelstrap.net/pwa/mpay/saving-plans.html by HTTrack Website Copier/3.x [XR&CO'2014], Mon, 25 Aug 2025 22:32:43 GMT -->
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta name="description" content="mpay" />
  <meta name="keywords" content="mpay" />
  <meta name="author" content="mpay" />
  <link rel="manifest" href="manifest.json" />
  <link rel="icon" href="assets/images/logo/favicon.png" type="image/x-icon" />
  <title>mPay App</title>
  <link rel="apple-touch-icon" href="assets/images/logo/favicon.png" />
  <meta name="theme-color" content="#122636" />
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black" />
  <meta name="apple-mobile-web-app-title" content="mpay" />
  <meta name="msapplication-TileImage" content="assets/images/logo/favicon.png" />
  <meta name="msapplication-TileColor" content="#FFFFFF" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />

  <!--Google font-->
  <link rel="preconnect" href="https://fonts.googleapis.com/" />
  <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin />
  <link href="https://fonts.googleapis.com/css2?family=Lato:wght@100;300;400;700;900&amp;display=swap" rel="stylesheet" />

  <!-- bootstrap css -->
  <link rel="stylesheet" id="rtl-link" type="text/css" href="assets/css/vendors/bootstrap.min.css" />

  <!-- swiper css -->
  <link rel="stylesheet" type="text/css" href="assets/css/vendors/swiper-bundle.min.css" />

  <!-- Theme css -->
  <link rel="stylesheet" id="change-link" type="text/css" href="assets/css/style.css" />
</head>

<body>
  <!-- header start -->
  <header class="section-t-space">
    <div class="custom-container">
      <div class="header-panel">
        <a href="dashboard" class="back-btn">
          <i class="icon" data-feather="arrow-left"></i>
        </a>
        <h2>My Running Plan</h2>

        <a href="bill" class="back-btn" >
          <i class="icon" data-feather="plus"></i>
        </a>
      </div>
    </div>
  </header>
  <!-- header end -->

  <!-- total saving section starts -->
  <section>
    <div class="custom-container">
      <div class="statistics-banner">
        <div class="d-flex justify-content-between align-items-center">
          <div class="total-amount">
            <h3>Total Balance</h3>
            <h2>
            <?php echo $site['currency']." ".($userbalance['balance'] + $userbalance['withdrawable_balance']);?></h2>
          </div>
        </div>
        <div class="saving-slider">
          <input id="range-slider__range" type="range" value="100" />

          <!-- <span id="range-slider__value">40</span> -->
        </div>

        <div class="left-amount">
          <h5>Withdrawable</h5>
          <h5 class="text-white fw-semibold"><?php echo $site['currency']." ".( $userbalance['withdrawable_balance']);?></h5>
        </div>
      </div>
    </div>
  </section>
  <!-- total saving section end -->

  <!-- saving plans section starts -->
  <section class="section-b-space">
    <div class="custom-container">
          <div class="row">
        <?php
        // Get user's owned plans and their power activations
        $userId = $_SESSION['user_id']; 
        $ownedPlans = getUserOwnedPlans($userId);
        $activePowers = getUserPowerActivations($userId, 'active');
        
        if (!empty($ownedPlans)):
          foreach ($ownedPlans as $plan):
            // Get plan powers
            $planPowers = getPlanPowers($plan['plan_id']);
            
            // Check if this plan has any active power runs
            $planActivePowers = array_filter($activePowers, function($power) use ($plan) {
                return isset($power['plan_id']) && $power['plan_id'] == $plan['plan_id'];
            });
            
            // Calculate progress
            $progressPercentage = 0;
            $timeLeft = '';
            $statusText = 'Ready to Use';
            $amountEarned = 0;
            $activePower = null;
            
            if (!empty($planActivePowers)) {
                $activePower = reset($planActivePowers);
                
                if (isset($activePower['started_at']) && isset($activePower['end_time'])) {
                    $startTime = strtotime($activePower['started_at']);
                    $endTime = strtotime($activePower['end_time']);
                    $currentTime = time();
                    
                    if ($currentTime < $endTime) {
                        // Still running
                        $totalDuration = $endTime - $startTime;
                        $elapsed = $currentTime - $startTime;
                        $progressPercentage = max(0, min(100, ($elapsed / $totalDuration) * 100));
                        
                        $secondsLeft = $endTime - $currentTime;
                        $hoursLeft = floor($secondsLeft / 3600);
                        $minutesLeft = floor(($secondsLeft % 3600) / 60);
                        $timeLeft = $hoursLeft . 'h ' . $minutesLeft . 'm left';
                        $statusText = 'Running';
                        $amountEarned = $activePower['reward'] ?? 0;
                    } else {
                        // Completed
                        $progressPercentage = 100;
                        $statusText = 'Completed - Ready to Claim';
                        $amountEarned = $activePower['reward'] ?? 0;
                    }
                }
            }
            
            // Progress bar colors
            $progressClass = 'bar1';
            if ($progressPercentage >= 75) $progressClass = 'bar6';
            elseif ($progressPercentage >= 50) $progressClass = 'bar4';
            elseif ($progressPercentage >= 25) $progressClass = 'bar3';
        ?>
        
        <div class="col-lg-4 col-md-6 col-12 mb-3">
          <div class="saving-plan-box">
            <div class="saving-plan-icon">
              <img class="img-fluid" src="assets/images/svg/success-chart.svg" alt="<?php echo htmlspecialchars($plan['name']); ?>" />
            </div>
            <h3><?php echo htmlspecialchars($plan['name']); ?></h3>
            <h6 class="status-text <?php echo $statusText === 'Running' ? 'text-warning' : ($statusText === 'Completed - Ready to Claim' ? 'text-success' : 'text-muted'); ?>">
                <?php echo $statusText; ?>
            </h6>
            
            <?php if (!empty($planActivePowers) && $activePower): ?>
            <!-- Active power run -->
            <div class="progress mb-2" role="progressbar">
              <div class="progress-bar <?php echo $progressClass; ?>" 
                   style="width: <?php echo $progressPercentage; ?>%"></div>
            </div>
            
            <div class="d-flex justify-content-between align-items-center mb-2">
              <h5 class="theme-color">
                <?php echo $site['currency'] . ' ' . number_format($amountEarned, 2); ?>
              </h5>
              <small class="text-muted"><?php echo $timeLeft; ?></small>
            </div>
            
            <?php if ($statusText === 'Completed - Ready to Claim'): ?>
            <button class="btn btn-success btn-sm claim-btn w-100" 
                    data-activation-id="<?php echo $activePower['id']; ?>">
                <span class="btn-text">Claim Reward</span>
                <span class="btn-spinner d-none">
                  <span class="spinner-border spinner-border-sm me-1"></span>
                  Claiming...
                </span>
            </button>
            <?php endif; ?>
            
            <?php else: ?>
            <!-- Available powers -->
            <div class="available-powers mb-2">
              <small class="text-muted">Available Powers:</small>
              <?php if (!empty($planPowers)): ?>
                <?php foreach ($planPowers as $power): ?>
                <div class="power-item d-flex justify-content-between align-items-center p-2 border rounded mt-1">
                  <div>
                    <strong><?php echo htmlspecialchars($power['power_name']); ?></strong>
                    <br><small>Reward: <?php echo $site['currency'] . ' ' . number_format($power['reward'], 2); ?></small>
                    <br><small>Min Value: <?php echo $power['min_value']; ?></small>
                  </div>
                  <button class="btn btn-primary btn-sm activate-power-btn" 
                          data-power-id="<?php echo $power['id']; ?>"
                          data-power-name="<?php echo htmlspecialchars($power['power_name']); ?>">
                      <span class="btn-text">Activate</span>
                      <span class="btn-spinner d-none">
                        <span class="spinner-border spinner-border-sm me-1"></span>
                        Activating...
                      </span>
                  </button>
                </div>
                <?php endforeach; ?>
              <?php else: ?>
                <p class="text-muted">No powers available for this plan.</p>
              <?php endif; ?>
            </div>
            <?php endif; ?>
            
            <div class="d-flex justify-content-between align-items-center mt-2">
              <small class="text-muted">Owned since: <?php echo date('M d, Y', strtotime($plan['purchased_at'])); ?></small>
              <img class="img-fluid arrow" src="assets/images/svg/arrow.svg" alt="arrow" />
            </div>
          </div>
        </div>
        
        <?php 
          endforeach;
        else:
        ?>
        
        <div class="col-12">
          <div class="text-center p-4">
            <img src="assets/images/svg/alert.svg" alt="No Plans" class="mb-3" style="max-width: 150px;">
            <h4 class="text-muted">No Running Plans</h4>
            <p class="text-muted mb-3">You don't have any active plans yet. Purchase a plan to start earning!</p>
            <a href="bill" class="btn btn-primary">Browse Plans</a>
          </div>
        </div>
        
        <?php endif; ?>
      </div>


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


  
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Handle power activation
    document.querySelectorAll('.activate-power-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const powerId = this.getAttribute('data-power-id');
            const powerName = this.getAttribute('data-power-name');
            
            // Show loading state
            const btnText = this.querySelector('.btn-text');
            const btnSpinner = this.querySelector('.btn-spinner');
            
            this.disabled = true;
            btnText.classList.add('d-none');
            btnSpinner.classList.remove('d-none');
            
            fetch('process/activate-power.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ power_id: powerId })
            })
            .then(res => res.json())
            .then(data => {
                if (data.status === 'success') {
                    showToast('Power activated successfully!', 'success');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showToast(data.message || 'Failed to activate power', 'danger');
                    // Reset button
                    this.disabled = false;
                    btnText.classList.remove('d-none');
                    btnSpinner.classList.add('d-none');
                }
            })
            .catch(() => {
                showToast('Network error occurred', 'danger');
                // Reset button
                this.disabled = false;
                btnText.classList.remove('d-none');
                btnSpinner.classList.add('d-none');
            });
        });
    });
    
    // Handle reward claiming
    document.querySelectorAll('.claim-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const activationId = this.getAttribute('data-activation-id');
            
            // Show loading state
            const btnText = this.querySelector('.btn-text');
            const btnSpinner = this.querySelector('.btn-spinner');
            
            this.disabled = true;
            btnText.classList.add('d-none');
            btnSpinner.classList.remove('d-none');
            
            fetch('process/claim-reward.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ activation_id: activationId })
            })
            .then(res => res.json())
            .then(data => {
                if (data.status === 'success') {
                    showToast('Reward claimed successfully!', 'success');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showToast(data.message || 'Failed to claim reward', 'danger');
                    // Reset button
                    this.disabled = false;
                    btnText.classList.remove('d-none');
                    btnSpinner.classList.add('d-none');
                }
            })
            .catch(() => {
                showToast('Network error occurred', 'danger');
                // Reset button
                this.disabled = false;
                btnText.classList.remove('d-none');
                btnSpinner.classList.add('d-none');
            });
        });
    });
    
    // Auto-refresh every 30 seconds if there are active powers
    setInterval(function() {
        const activeProgressBars = document.querySelectorAll('.progress-bar');
        if (activeProgressBars.length > 0) {
            location.reload();
        }
    }, 19000000);
});

function showToast(message, type) {
    const toastEl = document.getElementById('actionToast');
    const toastMsg = document.getElementById('actionToastMsg');
    
    toastMsg.innerHTML = message;
    toastEl.className = `toast align-items-center text-bg-${type} border-0`;
    
    const toast = new bootstrap.Toast(toastEl);
    toast.show();
}
</script>

  <!-- swiper js -->
  <script src="assets/js/swiper-bundle.min.js"></script>
  <script src="assets/js/custom-swiper.js"></script>

  <!-- feather js -->
  <script src="assets/js/feather.min.js"></script>
  <script src="assets/js/custom-feather.js"></script>

  <!-- bootstrap js -->
  <script src="assets/js/bootstrap.bundle.min.js"></script>

  <!-- script js -->
  <script src="assets/js/script.js"></script>
</body>


<!-- Mirrored from themes.pixelstrap.net/pwa/mpay/saving-plans.html by HTTrack Website Copier/3.x [XR&CO'2014], Mon, 25 Aug 2025 22:32:45 GMT -->
</html>