<?php declare(strict_types=1);

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/security.php';
require_once __DIR__ . '/../includes/login_throttle.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/brand_assets.php';

// Already logged in → go to dashboard
if (is_logged_in()) {
  header('Location: dashboard.php');
  exit;
}

$error = '';
$success = '';

$demoLoginEmails = ['admin@demo.tindaflow.com', 'cashier@demo.tindaflow.com'];
$prefillLoginEmail = strtolower(trim_str($_POST['email'] ?? ''));
$showForgotPasswordLink = $prefillLoginEmail === ''
    || !in_array($prefillLoginEmail, $demoLoginEmails, true);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!csrf_post_is_valid()) {
    $error = 'Security token expired. Please try again.';
  } else {
    $email = trim_str($_POST['email'] ?? '');
    $password = trim_str($_POST['password'] ?? '');

    if ($email === '' || $password === '') {
      $error = 'Please enter your email and password.';
    } else {
      $lock = check_login_throttle($pdo, $email);

      if ($lock['locked']) {
        $mins = (int) ceil($lock['seconds_left'] / 60);
        $error = "Too many failed attempts. Please wait {$mins} minute(s) before trying again.";
      } else {
        $fail_reason = '';
        $user = login_user($pdo, $email, $password, $fail_reason);

        if ($user) {
          clear_login_throttle($pdo, $email);
          session_regenerate_id(true);
          csrf_regenerate();

          $_SESSION['user_id']    = $user['id'];
          $_SESSION['client_id']  = $user['client_id'];
          $_SESSION['user_name']  = $user['name'];
          $_SESSION['user_email'] = $user['email'];
          $_SESSION['user_role']  = $user['role'];

          if (!empty($user['force_password_reset'])) {
            $_SESSION['must_reset_password'] = 1;
            header('Location: force_password_reset.php');
            exit;
          }

          header('Location: ' . post_login_redirect_path($pdo));
          exit;
        } else {
          record_login_failure($pdo, $email);
          // Demo-account visibility: log failed attempts for known demo users.
          $demoEmails = ['admin@demo.tindaflow.com', 'cashier@demo.tindaflow.com'];
          $emailLower = strtolower($email);
          if (in_array($emailLower, $demoEmails, true)) {
            try {
              $s = $pdo->prepare('SELECT id, client_id FROM users WHERE email = ? LIMIT 1');
              $s->execute([$emailLower]);
              $ur = $s->fetch();
              if ($ur && !empty($ur['client_id'])) {
                pos_audit_log(
                  $pdo,
                  (int) $ur['client_id'],
                  (int) ($ur['id'] ?? 0),
                  'LOGIN_FAILED',
                  'user',
                  (int) ($ur['id'] ?? 0),
                  ['reason' => $fail_reason !== '' ? $fail_reason : 'invalid_credentials']
                );
              }
            } catch (Throwable $e) {
              // best-effort
            }
          }
          $remaining = get_remaining_attempts($pdo, $email);
          $error = match ($fail_reason) {
            'pending'  => 'Your account is awaiting admin approval.',
            'disabled' => 'Your account has been disabled. Contact support.',
            default    => $remaining > 0
              ? "Incorrect email or password. {$remaining} attempt(s) remaining."
              : 'Incorrect email or password.',
          };
        }
      }
    }
  }

  csrf_regenerate();
}

// ---- Render ----
$page_title     = 'Sign In — TindaFlow';
$page_body_class = 'auth-page-body';
$auth_css       = true;
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
  <meta name="theme-color" content="<?= h(PosBrandAssets::THEME_COLOR) ?>">
  <meta name="color-scheme" content="light">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="default">
  <meta name="description" content="Multi-tenant point of sale for small businesses">
  <title><?= h($page_title) ?></title>
  <link rel="icon" type="image/png" href="<?= h(pos_brand_url(PosBrandAssets::FAVICON, '../')) ?>">
  <link rel="apple-touch-icon" href="<?= h(pos_brand_url(PosBrandAssets::APPLE_TOUCH_ICON, '../')) ?>">
  <link rel="manifest" href="../manifest.json">
  <link rel="stylesheet" href="../assets/css/style.css">
  <link rel="stylesheet" href="../assets/css/style-auth.css">
</head>
<body class="auth-page-body">
<div class="auth-shell">

  <!-- ═══════════════════════════════════════════════════
       LEFT — Brand panel
  ═══════════════════════════════════════════════════ -->
  <aside class="auth-brand">
    <div class="auth-brand-texture"></div>

    <div class="auth-brand-top">
      <a href="<?= pos_base_url() ?>index.php" class="auth-logo">
        <img src="<?= h(pos_brand_url(PosBrandAssets::LOGO_AUTH, '../')) ?>"
             alt="<?= h(PosBrandAssets::SITE_NAME) ?>"
             class="auth-logo-img">
      </a>
      <div class="auth-logo-tagline">Smart tools para sa iyong tindahan</div>
    </div>

    <div class="auth-brand-body">
      <!-- Mini POS receipt preview -->
      <div class="auth-pos-preview">
        <div class="auth-pos-preview-row">
          <span class="auth-pos-item-name">Bottled Water ×2</span>
          <span class="auth-pos-item-price">₱28.00</span>
        </div>
        <div class="auth-pos-preview-row">
          <span class="auth-pos-item-name">Coca-Cola ×1</span>
          <span class="auth-pos-item-price">₱20.00</span>
        </div>
        <div class="auth-pos-preview-row">
          <span class="auth-pos-item-name">Lucky Me ×3</span>
          <span class="auth-pos-item-price">₱45.00</span>
        </div>
        <div class="auth-pos-total">
          <span class="auth-pos-total-label">Total</span>
          <span class="auth-pos-total-value">₱93.00</span>
        </div>
      </div>

      <div class="auth-brand-headline">
        Manage your tindahan,<br><em>smarter every day.</em>
      </div>
      <div class="auth-brand-sub">
        Inventory, sales, staff, and reports — all in one place. Built for Filipino small businesses.
      </div>
    </div>

    <div class="auth-brand-bottom">
      <div class="auth-trust-list">
        <div class="auth-trust-item">
          <div class="auth-trust-dot"></div>
          Real-time inventory tracking
        </div>
        <div class="auth-trust-item">
          <div class="auth-trust-dot"></div>
          GCash + Cash payments
        </div>
        <div class="auth-trust-item">
          <div class="auth-trust-dot"></div>
          VAT-compliant receipts
        </div>
        <div class="auth-trust-item">
          <div class="auth-trust-dot"></div>
          Senior / PWD discount built-in
        </div>
      </div>
    </div>
  </aside>

  <!-- ═══════════════════════════════════════════════════
       RIGHT — Login form
  ═══════════════════════════════════════════════════ -->
  <main class="auth-form-panel">
    <div class="auth-form-card">

      <div class="auth-form-header">
        <div class="auth-form-eyebrow">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
            <path d="M15 3h4a2 2 0 012 2v14a2 2 0 01-2 2h-4M10 17l5-5-5-5M14 12H3"/>
          </svg>
          Merchant Login
        </div>
        <h1 class="auth-form-title">Welcome back</h1>
        <p class="auth-form-subtitle">Sign in to your TindaFlow account to continue.</p>
      </div>

      <?php if ($error !== ''): ?>
        <div class="auth-alert auth-alert-error" role="alert">
          <svg 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>
          <?= html_escape($error) ?>
        </div>
      <?php endif; ?>

      <?php if ($success !== ''): ?>
        <div class="auth-alert auth-alert-success" role="alert">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="20 6 9 17 4 12"/>
          </svg>
          <?= html_escape($success) ?>
        </div>
      <?php endif; ?>

      <form method="POST" action="login.php" id="login-form" novalidate>
        <input type="hidden" name="csrf_token" value="<?= html_escape(csrf_token()) ?>">

        <!-- Email -->
        <div class="auth-field">
          <div class="auth-field-label">
            <label class="auth-label" for="email">Email address</label>
          </div>
          <div class="auth-input-wrap">
            <svg class="auth-input-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>
              <polyline points="22,6 12,13 2,6"/>
            </svg>
            <input
              type="email"
              id="email"
              name="email"
              class="auth-input <?= $error !== '' ? 'is-error' : '' ?>"
              placeholder="you@example.com"
              value="<?= html_escape($_POST['email'] ?? '') ?>"
              autocomplete="email"
              required
              autofocus
              data-demo-emails="<?= html_escape(implode(',', $demoLoginEmails)) ?>"
            >
          </div>
        </div>

        <!-- Password -->
        <div class="auth-field">
          <div class="auth-field-label">
            <label class="auth-label" for="password">Password</label>
            <?php if ($showForgotPasswordLink): ?>
            <a href="forgot_password.php" class="auth-label-link" id="forgot-password-link">Forgot password?</a>
            <?php else: ?>
            <span class="auth-label-link" style="opacity:.55;cursor:default;" title="Demo accounts reset automatically">Demo — no reset</span>
            <?php endif; ?>
          </div>
          <div class="auth-input-wrap">
            <svg class="auth-input-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
              <path d="M7 11V7a5 5 0 0110 0v4"/>
            </svg>
            <input
              type="password"
              id="password"
              name="password"
              class="auth-input has-toggle <?= $error !== '' ? 'is-error' : '' ?>"
              placeholder="Your password"
              autocomplete="current-password"
              required
            >
            <button type="button" class="auth-password-toggle" aria-label="Show/hide password" data-target="password">
              <svg class="icon-eye" 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"/>
                <circle cx="12" cy="12" r="3"/>
              </svg>
              <svg class="icon-eye-off" 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 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/>
                <line x1="1" y1="1" x2="23" y2="23"/>
              </svg>
            </button>
          </div>
        </div>

        <button type="submit" class="auth-btn auth-btn-primary" id="login-btn">
          Sign In
        </button>
      </form>

      <div class="auth-switch">
        Don't have an account? <a href="signup.php">Create one free</a>
      </div>

    </div>

    <footer class="auth-footer">
      <span class="app-footer-inner">
        <span style="color:#1a5c4a;">Tinda</span><span style="color:#f59e0b;">Flow</span>
        · Secure register for small retail
      </span>
    </footer>
  </main>

</div>

<script>
(function () {
  var demoList = (document.getElementById('email').dataset.demoEmails || '').split(',').map(function (s) { return s.trim().toLowerCase(); }).filter(Boolean);
  var forgot = document.getElementById('forgot-password-link');
  var emailInput = document.getElementById('email');
  function syncForgot() {
    if (!forgot || !emailInput) return;
    var em = (emailInput.value || '').trim().toLowerCase();
    var hide = demoList.indexOf(em) !== -1;
    forgot.style.display = hide ? 'none' : '';
  }
  if (emailInput && forgot) {
    emailInput.addEventListener('input', syncForgot);
    emailInput.addEventListener('change', syncForgot);
    syncForgot();
  }

  // Password visibility toggle
  document.querySelectorAll('.auth-password-toggle').forEach(function (btn) {
    btn.setAttribute('aria-pressed', 'false');
    btn.addEventListener('click', function () {
      var input  = document.getElementById(btn.dataset.target);
      var eyeOn  = btn.querySelector('.icon-eye');
      var eyeOff = btn.querySelector('.icon-eye-off');
      if (!input) return;
      if (input.type === 'password') {
        input.type = 'text';
        eyeOn.style.display  = 'none';
        eyeOff.style.display = '';
        btn.setAttribute('aria-pressed', 'true');
        btn.setAttribute('aria-label', 'Hide password');
      } else {
        input.type = 'password';
        eyeOn.style.display  = '';
        eyeOff.style.display = 'none';
        btn.setAttribute('aria-pressed', 'false');
        btn.setAttribute('aria-label', 'Show password');
      }
    });
  });

  // Loading state on submit
  var form = document.getElementById('login-form');
  var btn  = document.getElementById('login-btn');
  form.addEventListener('submit', function () {
    btn.disabled = true;
    btn.innerHTML = '<span class="auth-spinner"></span> Signing in\u2026';
  });
})();
</script>

</body>
</html>