<?php
$page_title = 'Sign In | Herbal Wellness Care';
$page_description = 'Access your wellness journey with secure login';
$page_content = function () { ?>

<div class="login-hero">
  <div class="login-container">
    <!-- Header Section -->
    <div class="login-header">
      <div class="login-icon" style="background: transparent; box-shadow: none; padding: 0; width: auto; height: auto;">
        <img src="/atasteofafricanmarketplace/assets/images/logo.png" alt="Herbal Wellness Care" style="width: 120px; height: auto; object-fit: contain;">
      </div>
      <p id="role-badge" class="role-badge"></p>
      <h1 id="login-heading">Sign In</h1>
      <p class="subtitle">Continue your wellness journey</p>
    </div>

    <!-- Login Form Card -->
    <div class="login-form-card">
      <form id="login-form" class="login-form">
        <!-- Email Field -->
        <div class="form-group">
          <label for="email" class="form-label">Email Address</label>
          <div class="form-input-wrapper">
            <i class="fas fa-envelope form-icon"></i>
            <input 
              id="email" 
              name="email" 
              type="email" 
              required 
              class="form-input" 
              placeholder="Enter your email">
          </div>
        </div>

        <!-- Password Field -->
        <div class="form-group">
          <label for="password" class="form-label">Password</label>
          <div class="form-input-wrapper">
            <i class="fas fa-lock form-icon"></i>
            <input 
              id="password" 
              name="password" 
              type="password" 
              required 
              class="form-input" 
              placeholder="Enter your password">
            <button 
              type="button" 
              onclick="togglePassword()" 
              class="password-toggle">
              <i id="password-toggle" class="fas fa-eye"></i>
            </button>
          </div>
        </div>

        <!-- Remember & Forgot Password -->
        <div style="display: flex; align-items: center; justify-content: space-between;">
          <div class="checkbox-group">
            <input 
              id="remember-me" 
              name="remember-me" 
              type="checkbox" 
              class="checkbox">
            <label for="remember-me" class="checkbox-label">Remember me</label>
          </div>
          <a href="/atasteofafricanmarketplace/reset.php" class="forgot-password-link">Forgot password?</a>
        </div>

        <!-- Submit Button -->
        <button type="submit" class="submit-button">
          <span id="login-text">Sign In</span>
          <i id="login-spinner" class="fas fa-spinner spinner hidden" style="display: none;"></i>
        </button>

        <!-- Divider -->
        <div class="form-divider">
          <span class="form-divider-text">Quick Demo Access</span>
        </div>

        <!-- Demo Button -->
        <button type="button" onclick="demoLogin()" class="demo-button">
          <i class="fas fa-play"></i>
          Try Demo Account
        </button>
      </form>

      <!-- Footer Links -->
      <div class="login-footer">
        <p>
          Don't have an account?
          <a href="/atasteofafricanmarketplace/register.php" class="signup-link">Sign up for free</a>
        </p>
      </div>

      <!-- Trust Indicators -->
      <div class="trust-indicators">
        <div class="trust-badge">
          <i class="fas fa-shield-alt"></i>
          <span>HIPAA Secure</span>
        </div>
        <div class="trust-badge">
          <i class="fas fa-lock"></i>
          <span>256-bit SSL</span>
        </div>
        <div class="trust-badge">
          <i class="fas fa-certificate"></i>
          <span>Certified</span>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Message Container -->
<div id="message-container" class="message-container"></div>

<script>
// Toggle password visibility
function togglePassword() {
  const passwordInput = document.getElementById('password');
  const toggleIcon = document.getElementById('password-toggle');
  
  if (passwordInput.type === 'password') {
    passwordInput.type = 'text';
    toggleIcon.classList.remove('fa-eye');
    toggleIcon.classList.add('fa-eye-slash');
  } else {
    passwordInput.type = 'password';
    toggleIcon.classList.remove('fa-eye-slash');
    toggleIcon.classList.add('fa-eye');
  }
}

// Demo login
function demoLogin() {
  document.getElementById('password').value = 'demo123';
  document.getElementById('login-form').dispatchEvent(new Event('submit'));
}

// Show message
function showMessage(message, type = 'success') {
  const container = document.getElementById('message-container');
  const messageDiv = document.createElement('div');
  
  messageDiv.className = `message ${type}`;
  messageDiv.innerHTML = `
    <div style="display: flex; align-items: center; gap: 0.75rem; flex: 1;">
      <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i>
      <span>${message}</span>
    </div>
    <button onclick="this.parentElement.remove()" class="message-close">
      <i class="fas fa-times"></i>
    </button>
  `;
  
  container.appendChild(messageDiv);
  
  // Auto remove after 5 seconds
  setTimeout(() => {
    if (messageDiv.parentElement) {
      messageDiv.remove();
    }
  }, 5000);
}

// Handle form submission
document.getElementById('login-form').addEventListener('submit', async function(e) {
  e.preventDefault();
  
  const submitBtn = e.target.querySelector('button[type="submit"]');
  const loginText = document.getElementById('login-text');
  const loginSpinner = document.getElementById('login-spinner');
  
  // Show loading state
  submitBtn.disabled = true;
  loginText.textContent = 'Signing In...';
  loginSpinner.style.display = 'inline-block';
  
  const formData = new FormData(e.target);
  const data = {
    email: formData.get('email'),
    password: formData.get('password'),
    remember: formData.get('remember-me') ? true : false,
    role_hint: new URLSearchParams(window.location.search).get('role') || ''
  };
  
  try {
    const response = await fetch('/atasteofafricanmarketplace/api/auth/login.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data)
    });
    
    const result = await response.json();
    
    if (result.success) {
      showMessage('Login successful! Redirecting...', 'success');
      
      setTimeout(() => {
        const redirect = result.redirect || 'enhanced-dashboard.php';
        const finalUrl = '/atasteofafricanmarketplace/' + redirect;
        console.log('Redirecting to:', finalUrl);
        console.log('API returned redirect:', redirect);
        window.location.href = finalUrl;
      }, 1500);
    } else {
      showMessage(result.message || result.error || 'Login failed. Please try again.', 'error');
    }
  } catch (error) {
    showMessage('Network error. Please check your connection.', 'error');
  } finally {
    // Reset button state
    submitBtn.disabled = false;
    loginText.textContent = 'Sign In';
    loginSpinner.style.display = 'none';
  }
});

// Role hint display
(function showRoleHint() {
  const params = new URLSearchParams(window.location.search);
  const role = params.get('role');
  if (!role) return;
  const map = {
    admin: 'Admin Portal',
    coach: 'Coach Portal',
    client: 'Client Portal'
  };
  const badge = document.getElementById('role-badge');
  if (map[role]) {
    badge.textContent = map[role];
  }
})();
</script>

<?php };
include __DIR__ . '/partials/layout.php';
?>