<?php $__env->startSection('title', 'Account Statement - The LaLiT Loyalty'); ?>

<?php $__env->startSection('content'); ?>
  <div class="container px-4 py-5">
    <div class="row justify-content-center">
      <div class="col-lg-12">
        <!-- Page Header -->
        <div class="d-flex justify-content-between align-items-center mb-5">
          <div class="flex-grow-1 text-center">
            <h2 class="mb-2 statement-title">LaLit Loyalty Account Statement</h2>
          </div>
          <div>
            <a href="<?php echo e(route('membership.dashboard')); ?>" class="btn back-to-dashboard-btn">
              <i class="fas fa-arrow-left me-2"></i>BACK TO DASHBOARD
            </a>
          </div>
        </div>

        <!-- My Points Section -->

        <div class="row">
          <div class="col-8">
            <div class="card border-0 shadow-sm mb-5" style="background-color: #f5f0eb;">
              <div class="card-body p-5">
                <div class="text-center mb-4">
                  <h4 style="color: #333; font-weight: 400;">My Points</h4>
                </div>

                <div class="row justify-content-center">
                  <!-- LaLit Loyalty Balance -->
                  

                  <!-- Tier Points -->
                  <div class="col-md-4 mb-4">
                    <div class="text-center">
                      <p class="text-muted text-uppercase mb-3"
                        style="font-size: 0.8rem; letter-spacing: 1px; color: #8b7355 !important;">TIER POINTS</p>
                      <div class="border-0 rounded p-4" style="background-color: white; position: relative;">
                        <h2 class="mb-0" style="color: #333; font-weight: 300; font-size: 3rem;"><?php echo e(number_format($tierPoints ?? 0)); ?></h2>
                        <i class="fas fa-info-circle position-absolute"
                          style="top: 12px; right: 12px; color: #ccc; font-size: 1.1rem;"></i>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- Points Information -->
                <div class="row justify-content-center mt-4">
                  <div class="col-md-10">
                    <div class="text-center">
                      <p class="text-muted" style="font-size: 0.9rem; line-height: 1.6; color: #666 !important;">
                        All LaLiT Loyalty Members will earn two (2) LaLiT Loyalty Points and two (2) Tier Points for every
                        eligible 100 INR spent. For further information, please visit our
                        <a href="#" class="text-decoration-none" style="color: #8b7355;">FAQs</a>.
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="col-4">
            <div class="card border-0 shadow-sm mb-4" style="background-color: #f5f0eb;">
              <div class="card-body p-5">
                <!-- Right side stats -->
                <div class="row d-flex justify-content-center">

                  <!-- Points Due to Expire -->
                  <div class="text-center mb-4">
                    <p class="text-muted text-uppercase mb-2"
                      style="font-size: 0.75rem; letter-spacing: 1px; color: #8b7355 !important;">POINTS DUE TO</p>
                    <p class="text-muted text-uppercase mb-3"
                      style="font-size: 0.75rem; letter-spacing: 1px; color: #8b7355 !important; margin-top: -8px;">
                      EXPIRE BY</p>
                    <h3 class="mb-0" style="color: #333; font-weight: 300; font-size: 2rem;"><?php echo e(number_format($pointsDueToExpire ?? 0)); ?></h3>
                    
                    <?php if(!empty($pointsExpirationDetails) && count($pointsExpirationDetails) > 0): ?>
                      <div class="mt-3">
                        <table class="table table-sm table-borderless" style="font-size: 0.85rem;">
                          <thead>
                            <tr style="border-bottom: 1px solid #dee2e6;">
                              <th class="text-center" style="color: #8b7355; font-weight: 600; font-size: 0.75rem;">POINTS</th>
                              <th class="text-center" style="color: #8b7355; font-weight: 600; font-size: 0.75rem;">EXPIRY DATE</th>
                            </tr>
                          </thead>
                          <tbody>
                            <?php $__currentLoopData = $pointsExpirationDetails; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $expiration): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                              <tr>
                                <td class="text-center fw-bold" style="color: #333;"><?php echo e(number_format($expiration['points'])); ?></td>
                                <td class="text-center" style="color: #8b7355;">
                                  <?php if($expiration['expiration_date']): ?>
                                    <?php echo e(\Carbon\Carbon::parse($expiration['expiration_date'])->format('d M Y')); ?>

                                  <?php else: ?>
                                    -
                                  <?php endif; ?>
                                </td>
                              </tr>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                          </tbody>
                        </table>
                      </div>
                    <?php endif; ?>
                  </div>

                </div>
              </div>
            </div>

            <div class="card border-0 shadow-sm mb-5" style="background-color: #f5f0eb;">
              <div class="card-body p-5">
                <!-- Total Points Expired -->
                <div class="row d-flex justify-content-center">
                  <div class="text-center">
                    <p class="text-muted text-uppercase mb-2"
                      style="font-size: 0.75rem; letter-spacing: 1px; color: #8b7355 !important;">TOTAL POINTS</p>
                    <p class="text-muted text-uppercase mb-3"
                      style="font-size: 0.75rem; letter-spacing: 1px; color: #8b7355 !important; margin-top: -8px;">
                      EXPIRED</p>
                    <h3 class="mb-0" style="color: #333; font-weight: 300; font-size: 2rem;"><?php echo e(number_format($totalPointsExpired ?? 0)); ?></h3>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="row justify-content-center">
      <div class="col-lg-12">
        <!-- Transaction History Section -->
        <div class="card border-0 shadow-sm" style="background-color: #f5f0eb;">
          <div class="card-body p-5">
            <div class="d-flex justify-content-between align-items-center mb-4">
              <h4 style="color: #333; font-weight: 400;">Transaction History</h4>

              <div class="d-flex align-items-center gap-3">
                <!-- Download Button -->
                <button class="btn btn-link text-decoration-none p-0 border-0" style="color: #666;">
                  <i class="fas fa-download me-2"></i>
                  <span class="text-uppercase" style="font-size: 0.8rem; letter-spacing: 1px;">DOWNLOAD</span>
                </button>

                <!-- Fast 30 Days Dropdown -->
                <div class="dropdown">
                  <button class="btn btn-link text-decoration-none p-0 dropdown-toggle border-0" type="button"
                    data-bs-toggle="dropdown" style="color: #666;">
                    <i class="fas fa-calendar-alt me-2"></i>
                    <span class="text-uppercase" style="font-size: 0.8rem; letter-spacing: 1px;">LAST 30 DAYS</span>
                  </button>
                  <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="#">Last 30 Days</a></li>
                    <li><a class="dropdown-item" href="#">Last 60 Days</a></li>
                    <li><a class="dropdown-item" href="#">Last 90 Days</a></li>
                    <li><a class="dropdown-item" href="#">This Year</a></li>
                    <li><a class="dropdown-item" href="#">All Time</a></li>
                  </ul>
                </div>
              </div>
            </div>

            <!-- No Data State -->
            <div id="noDataState" class="text-center py-5" style="display: none;">
              <div class="mb-4">
                <i class="fas fa-receipt" style="font-size: 3rem; color: #ddd;"></i>
              </div>
              <h5 class="mb-3" style="color: #666; font-weight: 400;">NO DATA FOUND</h5>
            </div>

            <!-- Loading State -->
            <div id="loadingState" class="text-center py-5">
              <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
              </div>
              <p class="mt-3 text-muted">Loading transactions...</p>
            </div>

            <!-- Transaction Table -->
            <div id="transactionTable" style="display: none;">
              <div class="table-responsive">
                <table class="table table-hover">
                  <thead>
                    <tr style="border-bottom: 2px solid #dee2e6;">
                      <th class="text-uppercase" style="font-size: 0.75rem; color: #8b7355; font-weight: 600;">Date</th>
                      <th class="text-uppercase" style="font-size: 0.75rem; color: #8b7355; font-weight: 600;">Type</th>
                      <th class="text-uppercase" style="font-size: 0.75rem; color: #8b7355; font-weight: 600;">Sponsor</th>
                      <th class="text-uppercase" style="font-size: 0.75rem; color: #8b7355; font-weight: 600;">Points</th>
                      <th class="text-uppercase" style="font-size: 0.75rem; color: #8b7355; font-weight: 600;">Status</th>
                      <th class="text-uppercase text-end" style="font-size: 0.75rem; color: #8b7355; font-weight: 600;">Reference</th>
                    </tr>
                  </thead>
                  <tbody id="transactionTableBody">
                    <!-- Transactions will be loaded here via JavaScript -->
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <?php $__env->startPush('scripts'); ?>
    <script>
      document.addEventListener('DOMContentLoaded', function () {
        // Load transaction history on page load
        loadTransactionHistory();

        // Download button functionality
        const downloadBtn = document.querySelector('button[style*="color: #666"]');
        if (downloadBtn) {
          downloadBtn.addEventListener('click', function () {
            exportToCSV();
          });
        }

        // Dropdown functionality for date ranges
        const dropdownItems = document.querySelectorAll('.dropdown-item');
        dropdownItems.forEach(item => {
          item.addEventListener('click', function (e) {
            e.preventDefault();
            const selectedRange = this.textContent;
            console.log('Selected range:', selectedRange);
            // Add filtering logic here based on date range
          });
        });

        // Claim missing points link
        const claimLinks = document.querySelectorAll('a[href="#"]');
        claimLinks.forEach(link => {
          link.addEventListener('click', function (e) {
            e.preventDefault();
            console.log('Claim missing points clicked');
          });
        });
      });

      function loadTransactionHistory() {
        const loadingState = document.getElementById('loadingState');
        const noDataState = document.getElementById('noDataState');
        const transactionTable = document.getElementById('transactionTable');
        const tableBody = document.getElementById('transactionTableBody');

        // Show loading state
        loadingState.style.display = 'block';
        noDataState.style.display = 'none';
        transactionTable.style.display = 'none';

        // Fetch transaction history from API
        fetch('<?php echo e(route("membership.transaction-history")); ?>', {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
          }
        })
        .then(response => response.json())
        .then(data => {
          loadingState.style.display = 'none';

          if (data.success && data.transactions && data.transactions.length > 0) {
            // Display transactions
            displayTransactions(data.transactions);
            transactionTable.style.display = 'block';
          } else {
            // Show no data state
            noDataState.style.display = 'block';
          }
        })
        .catch(error => {
          console.error('Error fetching transactions:', error);
          loadingState.style.display = 'none';
          noDataState.style.display = 'block';
        });
      }

      function displayTransactions(transactions) {
        const tableBody = document.getElementById('transactionTableBody');
        tableBody.innerHTML = '';

        // Filter transactions to only show those with loyalty_account_id = 2
        const filteredTransactions = transactions.filter(transaction => {
          if (transaction.loyalty_balances && Array.isArray(transaction.loyalty_balances)) {
            return transaction.loyalty_balances.some(balance => balance.loyalty_account_id === "2" || balance.loyalty_account_id === 2);
          }
          return false;
        });

        // Show only latest 5 records
        const latestTransactions = filteredTransactions.slice(0, 5);

        latestTransactions.forEach(transaction => {
          createTransactionRow(transaction, tableBody);
        });
      }
      
      function createTransactionRow(transaction, tableBody) {
        const row = document.createElement('tr');
        row.style.borderBottom = '1px solid #f0f0f0';
        
        // Format date (DD/MM/YYYY format)
        const date = new Date(transaction.h_bit_date);
        const formattedDate = date.toLocaleDateString('en-GB', { 
          day: '2-digit', 
          month: '2-digit', 
          year: 'numeric' 
        });

        // Get transaction details
        const bitType = transaction.header?.h_bit_type_name || 'N/A';
        const sponsorName = transaction.sponsor_name || 'N/A';
        const sponsorLogo = transaction.sponsor_logo || '';
        const status = transaction.status || 'N/A';
        const reference = transaction.bit_reference || 'N/A';
        
        // Check for points in different locations
        let pointsValue = 'N/A';
        let pointsLabel = '';
        let pointsBadgeClass = 'bg-secondary';
        
        // Check loyalty_balances for rewarded/redeemed points
        if (transaction.loyalty_balances && transaction.loyalty_balances.length > 0) {
          const loyaltyBalance = transaction.loyalty_balances[0];
          if (loyaltyBalance.rewarded > 0) {
            pointsValue = Math.abs(loyaltyBalance.rewarded);
            pointsLabel = 'Earned';
            pointsBadgeClass = 'bg-success';
          } else if (loyaltyBalance.redeemed > 0) {
            pointsValue = Math.abs(loyaltyBalance.redeemed);
            pointsLabel = 'Redeemed';
            pointsBadgeClass = 'bg-primary';
          }
        }
        
        // Check offer_actions for REWARD_POINTS
        if (pointsValue === 'N/A' && transaction.offer_actions && transaction.offer_actions.length > 0) {
          const rewardAction = transaction.offer_actions.find(action => action.type === 'REWARD_POINTS');
          if (rewardAction && rewardAction.value_n) {
            pointsValue = Math.abs(rewardAction.value_n);
            pointsLabel = 'Earned';
            pointsBadgeClass = 'bg-success';
          }
        }

        // Status badge color
        let statusClass = 'secondary';
        if (status === 'SUCCESS') {
          statusClass = 'success';
        } else if (status === 'FAILED') {
          statusClass = 'danger';
        } else if (status === 'PENDING') {
          statusClass = 'warning';
        }
        
        // Format points display
        const pointsDisplay = pointsValue === 'N/A' ? 'N/A' : `${pointsValue} Points ${pointsLabel}`;

        row.innerHTML = `
          <td class="py-3">
            <span style="color: #333;">${formattedDate}</span>
          </td>
          <td class="py-3">
            <span style="color: #333;">${bitType}</span>
          </td>
          <td class="py-3">
            <div class="d-flex align-items-center">
              ${sponsorLogo ? `<img src="${sponsorLogo}" alt="${sponsorName}" style="width: 30px; height: 30px; object-fit: contain; margin-right: 8px; border-radius: 4px;">` : ''}
              <span style="color: #333;">${sponsorName}</span>
            </div>
          </td>
          <td class="py-3">
            <span class="badge ${pointsBadgeClass}" style="font-size: 0.85rem;">${pointsDisplay}</span>
          </td>
          <td class="py-3">
            <span class="badge bg-${statusClass}">${status}</span>
          </td>
          <td class="py-3 text-end">
            <small class="text-muted" style="font-size: 0.75rem;">${reference}</small>
          </td>
        `;

        tableBody.appendChild(row);
      }

      function exportToCSV() {
        const transactions = Array.from(document.querySelectorAll('#transactionTableBody tr'));
        
        if (transactions.length === 0) {
          alert('No transactions to export');
          return;
        }

        let csv = 'Date,Type,Sponsor,Points,Status,Reference\n';
        
        transactions.forEach(row => {
          const cells = row.querySelectorAll('td');
          const rowData = Array.from(cells).map(cell => {
            const text = cell.textContent.trim().replace(/\s+/g, ' ');
            return '"' + text.replace(/"/g, '""') + '"';
          });
          csv += rowData.join(',') + '\n';
        });

        // Download CSV
        const blob = new Blob([csv], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'lalit-loyalty-transactions-' + new Date().toISOString().split('T')[0] + '.csv';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      }
    </script>
  <?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.membership', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/tlshs/public_html/thelalitloyalty.com/resources/views/membership/statement.blade.php ENDPATH**/ ?>