<?php
require_once __DIR__ . '/includes/functions.php';
startSecureSession();

if (isLoggedIn()) { header('Location: dashboard.php'); exit; }
if (isAdminLoggedIn()) { header('Location: admin/dashboard.php'); exit; }

$error = '';
if (isset($_GET['error'])) {
    $error = trim($_GET['error']);
} elseif (isset($_GET['expired'])) {
    $error = 'Your session expired after 24 hours of inactivity. Please sign in again.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrfVerify();
    $email    = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $turnstileResponse = $_POST['cf-turnstile-response'] ?? '';

    if (!verifyTurnstile($turnstileResponse)) {
        $error = 'Please complete the security check.';
    }

    if (!$error) {
        $ip       = md5($_SERVER['REMOTE_ADDR'] ?? 'unknown');
        $rateFile = __DIR__ . '/data/fam_login_rate_' . $ip;
        $hits     = file_exists($rateFile) ? (json_decode(file_get_contents($rateFile), true) ?: []) : [];
        $now      = time();
        $hits     = array_filter($hits, fn($t) => ($now - $t) < 60);
        if (count($hits) >= 5) {
        $error = 'Too many login attempts. Please wait a minute and try again.';
    } else {
        $hits[] = $now;
        file_put_contents($rateFile, json_encode(array_values($hits)));

        if ($email === ADMIN_USERNAME && $password === ADMIN_PASSWORD) {
            session_regenerate_id(true);
            $_SESSION['is_admin'] = true;
            if (!empty($_POST['remember'])) {
                $token = encryptData(json_encode(['admin' => true, 'time' => time()]));
                setcookie('remember_token', $token, time() + (7 * 24 * 60 * 60), '/', '', isset($_SERVER['HTTPS']), true);
            }
            if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) {
                echo json_encode(['status'=>'success', 'redirect'=>'admin/dashboard.php']); exit;
            }
            header('Location: admin/dashboard.php');
            exit;
        }

        $sysSettings = getAdminSettings();
        if (empty($sysSettings['allow_login'])) {
            $error = 'Merchant logins are currently disabled by the site administrator.';
        } else {
            $user = getUserByEmail($email);
            if (!$user || !password_verify($password, $user['password_hash'])) {
                $error = 'Invalid email or password.';
            } elseif ($user['status'] === 'banned') {
                $error = 'This account has been suspended. Contact support.';
            } else {
                session_regenerate_id(true);
                $_SESSION['user_id'] = $user['id'];
                if (!empty($_POST['remember'])) {
                    $token = encryptData(json_encode(['id' => $user['id'], 'time' => time()]));
                    setcookie('remember_token', $token, time() + (7 * 24 * 60 * 60), '/', '', isset($_SERVER['HTTPS']), true);
                }
                if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) {
                    echo json_encode(['status'=>'success', 'redirect'=>'dashboard.php']); exit;
                }
                header('Location: dashboard.php');
                exit;
            }
            }
        }
    }

    if ($error && isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) {
        echo json_encode(['status'=>'error', 'message'=>$error]);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php $pageTitle = "Sign In — FamGateway"; include 'includes/header.php'; ?>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { display: flex; min-height: 100vh; background: #f6f8fb; color: #0f172a; font-family: 'Poppins', sans-serif; }

  .auth-left {
    display: none;
    flex: 0 0 460px;
    background: linear-gradient(160deg, #0f172a 0%, #1e3a8a 60%, #1d4ed8 100%);
    position: relative; overflow: hidden;
    padding: 48px 52px;
    flex-direction: column; justify-content: space-between;
  }
  @media (min-width: 900px) { .auth-left { display: flex; } }
  .auth-left-bg {
    position: absolute; inset: 0;
    background: radial-gradient(ellipse at 30% 20%, rgba(59,130,246,0.25) 0%, transparent 55%),
                radial-gradient(ellipse at 80% 80%, rgba(16,185,129,0.15) 0%, transparent 50%);
  }
  .auth-left-grid {
    position: absolute; inset: 0;
    background-image: linear-gradient(rgba(255,255,255,0.03) 1px, transparent 1px),
                      linear-gradient(90deg, rgba(255,255,255,0.03) 1px, transparent 1px);
    background-size: 40px 40px;
  }
  .auth-left-content { position: relative; z-index: 1; }
  .auth-left-brand { display: flex; align-items: center; gap: 12px; margin-bottom: 52px; }
  .auth-left-brand-icon {
    width: 38px; height: 38px; border-radius: 11px;
    background: rgba(255,255,255,0.12); border: 1px solid rgba(255,255,255,0.15);
    display: flex; align-items: center; justify-content: center;
  }
  .auth-left-brand-name { font-size: 16px; font-weight: 700; color: #f8fafc; }
  .auth-left-heading { font-size: 36px; font-weight: 800; line-height: 1.2; letter-spacing: -1px; color: #fff; margin-bottom: 18px; }
  .auth-left-heading span { background: linear-gradient(90deg, #60a5fa, #34d399); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; }
  .auth-left-desc { font-size: 15px; color: #94a3b8; line-height: 1.65; margin-bottom: 40px; }
  .auth-features { display: flex; flex-direction: column; gap: 14px; }
  .auth-feature { display: flex; align-items: center; gap: 14px; font-size: 14px; color: #e2e8f0; }
  .auth-feature-dot {
    width: 28px; height: 28px; border-radius: 50%;
    background: rgba(52,211,153,0.15); border: 1px solid rgba(52,211,153,0.3);
    display: flex; align-items: center; justify-content: center; flex-shrink: 0; color: #34d399;
  }
  .auth-left-footer { position: relative; z-index: 1; font-size: 12px; color: #475569; }

  .auth-right {
    flex: 1; display: flex; flex-direction: column;
    justify-content: center; align-items: center;
    padding: 40px 24px; background: #f6f8fb; position: relative; overflow-y: auto;
  }
  .auth-back {
    position: absolute; top: 24px; left: 24px;
    display: flex; align-items: center; gap: 6px;
    font-size: 13px; font-weight: 500; color: #64748b;
    text-decoration: none; transition: color 0.15s;
    padding: 7px 12px; border-radius: 9px;
    border: 1px solid #e2e8f0; background: #ffffff;
    box-shadow: 0 1px 2px rgba(0,0,0,0.04);
  }
  .auth-back:hover { color: #0f172a; background: #f1f5f9; }
  .auth-form-card {
    width: 100%; max-width: 420px;
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 20px;
    padding: 38px 34px;
    box-shadow: 0 12px 32px -4px rgba(15, 23, 42, 0.08), 0 4px 12px -2px rgba(15, 23, 42, 0.04);
  }
  @media (max-width: 600px) {
    .auth-back { position: relative; top: auto; left: auto; align-self: flex-start; margin-bottom: 16px; }
    .auth-form-card { padding: 28px 20px; border-radius: 16px; margin-top: 0; }
  }
  .auth-form-header { margin-bottom: 28px; text-align: center; }
  .auth-form-logo {
    width: 42px; height: 42px; border-radius: 12px;
    background: linear-gradient(135deg, #2563eb, #1e40af);
    display: flex; align-items: center; justify-content: center;
    margin: 0 auto 20px auto; box-shadow: 0 4px 14px rgba(37,99,235,0.35);
  }
  .auth-form-title { font-size: 24px; font-weight: 800; letter-spacing: -0.6px; color: #0f172a; margin-bottom: 6px; }
  .auth-form-subtitle { font-size: 14px; color: #64748b; }
  .form-group { margin-bottom: 16px; }
  .form-label { display: block; font-size: 13px; font-weight: 500; color: #334155; margin-bottom: 6px; }
  .form-input {
    width: 100%; padding: 11px 14px;
    border: 1px solid #e2e8f0; border-radius: 10px;
    font-size: 14px; color: #0f172a; background: #f8fafc;
    transition: all 0.15s; outline: none; font-family: 'Poppins', sans-serif;
  }
  .form-input:focus { border-color: #2563eb; background: #fff; box-shadow: 0 0 0 3px rgba(37,99,235,0.12); }
  .form-input::placeholder { color: #94a3b8; }
  .btn-auth {
    width: 100%; padding: 13px; background: #2563eb; color: #fff;
    border: none; border-radius: 12px; font-size: 15px; font-weight: 600;
    cursor: pointer; transition: all 0.15s; box-shadow: 0 2px 8px rgba(37,99,235,0.3);
    margin-top: 6px; font-family: 'Poppins', sans-serif;
  }
  .btn-auth:hover { background: #1d4ed8; transform: translateY(-1px); box-shadow: 0 4px 16px rgba(37,99,235,0.4); }
  .btn-auth:active { transform: none; box-shadow: none; }
  .auth-switch { text-align: center; margin-top: 24px; font-size: 14px; color: #64748b; }
  .auth-switch a { color: #2563eb; font-weight: 600; text-decoration: none; }
  .auth-switch a:hover { text-decoration: underline; }
  .alert-error {
    background: #fee2e2; border: 1px solid #fca5a5; color: #dc2626;
    padding: 12px 14px; border-radius: 10px; font-size: 13px; margin-bottom: 20px;
    display: flex; align-items: center; gap: 8px;
  }
</style>
</head>
<body>

<div class="auth-left">
  <div class="auth-left-bg"></div>
  <div class="auth-left-grid"></div>
  <div class="auth-left-content dash-anim-in" style="opacity:1; animation: dashFadeIn 0.8s ease forwards;">
    <div class="auth-left-brand">
      <img src="assets/img/logo-navbar-bright.png" alt="FamGateway" style="height:30px;width:auto;display:block;object-fit:contain;">
    </div>
    <h1 class="auth-left-heading">UPI payments,<br><span>automated.</span></h1>
    <p class="auth-left-desc">The most reliable UPI payment gateway built for developers. Accept payments in seconds with a simple API call.</p>
    <div class="auth-features">
      <div class="auth-feature"><div class="auth-feature-dot"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></div>Real-time FamPay transaction matching</div>
      <div class="auth-feature"><div class="auth-feature-dot"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></div>Instant webhook callbacks on payment</div>
      <div class="auth-feature"><div class="auth-feature-dot"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></div>No commission — zero platform fees</div>
    </div>
  </div>
  <div class="auth-left-footer">© <?= date('Y') ?> Aryanispe FamGateway</div>
</div>

<div class="auth-right">
  <a href="index.php" class="auth-back">
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
    Home
  </a>
  <div class="auth-form-card dash-anim-up" style="opacity:1; animation: dashFadeUp 0.6s cubic-bezier(.22,1,.36,1) forwards;">
    <div class="auth-form-header">
      <div class="auth-form-logo" style="background:none;box-shadow:none;width:auto;height:auto;">
        <img src="assets/img/logo-navbar-bright.png" alt="FamGateway" style="height:28px;width:auto;display:block;object-fit:contain;filter:invert(1) hue-rotate(180deg);">
      </div>
      <h2 class="auth-form-title">Welcome back</h2>
      <p class="auth-form-subtitle">Sign in to your FamGateway account</p>
    </div>

    <a href="auth-google.php" class="btn-auth" style="background: #fff; color: #334155; border: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: center; gap: 10px; margin-bottom: 20px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); text-decoration: none;">
      <svg width="20" height="20" viewBox="0 0 48 48">
        <path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/>
        <path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/>
        <path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/>
        <path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/>
      </svg>
      Continue with Google
    </a>

    <div style="display: flex; align-items: center; margin-bottom: 20px;">
      <div style="flex-grow: 1; height: 1px; background: #e2e8f0;"></div>
      <span style="padding: 0 12px; font-size: 13px; color: #64748b;">or sign in with email</span>
      <div style="flex-grow: 1; height: 1px; background: #e2e8f0;"></div>
    </div>

    <?php if ($error): ?>
    <div class="alert-error">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
      <?= htmlspecialchars($error) ?>
    </div>
    <?php endif; ?>

    <form method="POST" action="login.php" id="loginForm">
      <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
      <div class="form-group">
        <label class="form-label">Email address</label>
        <input type="email" name="email" class="form-input" placeholder="you@example.com" required autofocus autocomplete="email">
      </div>
      <div class="form-group">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px;">
            <label class="form-label" style="margin-bottom:0;">Password</label>
            <a href="forgot-password.php" style="font-size:12px; font-weight:500; color:#2563eb; text-decoration:none;">Forgot password?</a>
        </div>
        <div style="position: relative;">
          <input type="password" name="password" class="form-input" placeholder="••••••••" required autocomplete="current-password" style="padding-right: 40px;">
          <button type="button" onclick="togglePassword(this)" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); background: none; border: none; cursor: pointer; color: #64748b; padding: 4px; display: flex;">
            <svg class="eye-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
            <svg class="eye-off-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:none;"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line></svg>
          </button>
        </div>
      </div>
      <div class="form-group" style="margin-bottom: 20px;">
        <label style="display:flex; align-items:center; gap:8px; font-size:13px; color:#334155; cursor:pointer;">
          <input type="checkbox" name="remember" value="1" style="width:16px; height:16px; cursor:pointer; accent-color:#2563eb;">
          Keep me signed in for 7 days
        </label>
      </div>
      <?php if (defined('TURNSTILE_SITE_KEY') && TURNSTILE_SITE_KEY): ?>
      <div class="cf-turnstile" data-sitekey="<?= TURNSTILE_SITE_KEY ?>" style="margin-bottom: 14px; display: flex; justify-content: center;"></div>
      <?php endif; ?>
      <button type="submit" class="btn-auth" id="loginBtn">Sign In →</button>
    </form>
    <p class="auth-switch">Don't have an account? <a href="register.php">Create one free</a></p>
  </div>
</div>

<script>
function togglePassword(btn) {
    const input = btn.previousElementSibling;
    const eye = btn.querySelector('.eye-icon');
    const eyeOff = btn.querySelector('.eye-off-icon');
    if (input.type === 'password') {
        input.type = 'text';
        eye.style.display = 'none';
        eyeOff.style.display = 'block';
    } else {
        input.type = 'password';
        eye.style.display = 'block';
        eyeOff.style.display = 'none';
    }
}

if (window.lucide) { lucide.createIcons(); }

document.getElementById('loginForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const form = this;
    const btn = document.getElementById('loginBtn');
    const originalText = btn.innerHTML;
    
    btn.innerHTML = '<svg class="spin-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg> Signing In...';
    btn.style.opacity = '0.8';
    btn.disabled = true;

    try {
        const formData = new FormData(form);
        const [res] = await Promise.all([
            fetch(form.action, {
                method: 'POST',
                body: formData,
                headers: { 'Accept': 'application/json' }
            }),
            new Promise(r => setTimeout(r, 800)) // Artificial delay for premium feel
        ]);
        
        const data = await res.json();

        if (data.status === 'success') {
            btn.innerHTML = originalText;
            
            const successDiv = document.createElement('div');
            successDiv.className = 'callout callout-success dash-anim-up';
            successDiv.style.animation = 'dashFadeUp 0.4s ease forwards';
            successDiv.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg> <div style="display:flex; flex-direction:column; gap:2px;"><b style="font-size:14px;color:#166534;">Sign In Successful!</b><span style="color:#15803d;font-size:12.5px;">Redirecting to your dashboard...</span></div>';
            
            const oldErr = form.parentElement.querySelector('.alert-error');
            if (oldErr) oldErr.remove();
            
            form.parentNode.insertBefore(successDiv, form);
            
            // Dim the form
            form.style.transition = 'opacity 0.4s';
            form.style.opacity = '0.3';
            form.style.pointerEvents = 'none';

            setTimeout(() => window.location.href = data.redirect, 2500);
        } else {
            const errDiv = document.createElement('div');
            errDiv.className = 'alert-error';
            errDiv.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg> ' + (data.message || 'Error occurred');
            
            const oldErr = form.parentElement.querySelector('.alert-error');
            if (oldErr) oldErr.remove();
            
            form.parentNode.insertBefore(errDiv, form);
            if (typeof turnstile !== 'undefined') turnstile.reset();
            btn.innerHTML = originalText;
            btn.disabled = false;
            btn.style.opacity = '1';
        }
    } catch(err) {
        alert("Network Error. Please try again.");
        if (typeof turnstile !== 'undefined') turnstile.reset();
        btn.innerHTML = originalText;
        btn.disabled = false;
        btn.style.opacity = '1';
    }
});
</script>
</body>
</html>
