<?php require_once __DIR__ . '/../includes/config.php'; ?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>Welcome to SmartServe Pro | Sign In</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

  <style>
    :root{
      --qa-red: #c62828;         /* primary red (button, accents) */
      --qa-red-600:#b71c1c;
      --qa-red-200:#fce5e5;      /* input bg */
      --qa-red-300:#f7d3d3;      /* input hover/focus bg */
      --qa-red-400:#f0bcbc;      /* light borders */
      --qa-text:#2a2a2a;
    }

    /* Page */
    body{
      background:#ffffff;
      color:var(--qa-text);
      min-height:100vh;
      display:flex;
      align-items:center;
      justify-content:center;
      padding:2rem;
      font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,Arial,sans-serif;
    }

    /* Card */
    .login-card{
      width:min(92vw, 520px);
      border:1.5px solid var(--qa-red-400);
      border-radius:18px;
      box-shadow:0 10px 28px rgba(198,40,40,.15);
    }
    .login-card .card-body{ padding:2rem; }
    .login-card .card-footer{
      border-top:0;
      background:#fff;
      color:#888;
      font-size:.85rem;
      padding:1rem 2rem 1.25rem;
    }

    /* Brand */
    .brand{
      display:flex;
      flex-direction:column;
      align-items:center;
      gap:.5rem;
      margin-bottom:1rem;
    }
    .brand img{ height:200px; width:auto; }

    /* Labels & inputs */
    .form-label{ font-weight:600; color:#7a0e0e; }

    .form-control{
      background:var(--qa-red-200);
      border:1.5px solid var(--qa-red-400);
      color:var(--qa-text);
      border-radius:10px;
      height:48px;
    }
    .form-control::placeholder{ color:#a77; }
    .form-control:focus{
      background:var(--qa-red-300);
      border-color:var(--qa-red);
      box-shadow:0 0 0 .2rem rgba(198,40,40,.15);
      color:var(--qa-text);
    }

    /* Button */
    .btn-qa{
      background:var(--qa-red);
      color:#fff;
      border:none;
      border-radius:10px;
      height:48px;
      font-weight:700;
      letter-spacing:.2px;
    }
    .btn-qa:hover{ background:var(--qa-red-600); color:#fff; }
    .btn-qa:disabled{ opacity:.8; }

    /* Message */
    #message{ margin-bottom:1rem; }
  </style>
</head>
<body>
  <div class="card login-card">
    <div class="card-body">
      <div class="brand">
        <!-- Replace with your logo; hide if missing -->
        <img src="<?= WEB_BASE ?>assets/img/logo.png" alt="SERVE SMART PRO" onerror="this.style.display='none'">
      </div>

      <div id="message" class="alert d-none" role="alert"></div>

      <form id="loginForm" autocomplete="on">
        <div class="mb-3">
          <label for="email" class="form-label">Username</label>
          <input type="email" id="email" name="email" class="form-control" placeholder="you@company.co.za" required autocomplete="email">
        </div>

        <div class="mb-4">
          <label for="password" class="form-label">Password</label>
          <input type="password" id="password" name="password" class="form-control" placeholder="••••••••" required autocomplete="current-password">
        </div>

        <button id="submitBtn" type="submit" class="btn btn-qa w-100">Sign in</button>
      </form>
    </div>

    <div class="card-footer text-center">
      © <?= date('Y') ?> SERVE SMART PRO • All rights reserved • Developed by Thys Taljaard Copyright (c) 2025
    </div>
  </div>

<script>
const form = document.getElementById('loginForm');
const messageDiv = document.getElementById('message');
const submitBtn = document.getElementById('submitBtn');

form.addEventListener('submit', async (e) => {
  e.preventDefault();
  const original = submitBtn.innerHTML;
  submitBtn.disabled = true;
  submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Signing in…';
  messageDiv.className = 'alert alert-info';
  messageDiv.textContent = 'Authenticating…';
  messageDiv.classList.remove('d-none');

  try {
    console.log('Sending login request...');
    const res = await fetch('<?= WEB_BASE ?>api/process_login.php', {
      method: 'POST',
      body: new FormData(form)
    });

    console.log('Response status:', res.status);
    
    let data;
    try { 
      data = await res.json(); 
    } catch (err) { 
      console.error('JSON parse error:', err);
      throw new Error('Invalid server response: ' + err.message); 
    }

    console.log('Login Response:', data);

    if (data.success) {
      messageDiv.className = 'alert alert-success';
      messageDiv.textContent = 'Login successful! Redirecting...';
      
      console.log('Success! Redirect URL:', data.redirect_url);
      console.log('Debug info:', data.debug);
      
      // ✅ IMMEDIATE REDIRECT (removed 3-second delay)
      if (data.redirect_url) {
        console.log('Redirecting NOW to:', data.redirect_url);
        // Force immediate redirect
        window.location.assign(data.redirect_url);
      } else {
        // Fallback
        console.log('No redirect URL, using fallback');
        window.location.href = '<?= WEB_BASE ?>pages/dashboard.php';
      }
      
    } else {
      messageDiv.className = 'alert alert-danger';
      messageDiv.textContent = data.message || 'Invalid email or password';
      submitBtn.disabled = false;
      submitBtn.innerHTML = original;
      console.error('Login failed:', data);
    }
  } catch (err) {
    messageDiv.className = 'alert alert-danger';
    messageDiv.textContent = 'Network/server error. Please try again.';
    submitBtn.disabled = false;
    submitBtn.innerHTML = original;
    console.error('Login error:', err);
    
    // Show more detailed error
    if (err.message.includes('JSON')) {
      messageDiv.textContent = 'Server returned invalid response. Please check console.';
    }
  }
});

// Add enter key support
form.addEventListener('keypress', (e) => {
  if (e.key === 'Enter' && !submitBtn.disabled) {
    e.preventDefault();
    form.dispatchEvent(new Event('submit'));
  }
});
</script>
</body>
</html>