<?php
// /admin/login.php
// Single-domain, two-level tenancy (Organisation -> Company).
// Auth via Entra SSO (if enabled) and/or email+password.
// For email+password, we search all users with that email and match hash;
// the matched row determines org+company in the session.

session_start();

$config = require __DIR__ . '/../lib/config.php';
require __DIR__ . '/../lib/db.php';
require __DIR__ . '/../lib/sso_settings.php';

$base         = rtrim($config['base_url'] ?? '', '/');
$isDemo       = !empty($config['demo_mode']);
$basicCreds   = $config['admin_auth'] ?? null;

$authCfg        = $config['auth'] ?? [];
$allowPassword  = (bool)($authCfg['enable_password_login']    ?? true);
$allowLegacy    = (bool)($authCfg['allow_legacy_basic']       ?? true);
$minLen         = (int) ($authCfg['min_password_length']      ?? 8);
$allowEntraPw   = (bool)($authCfg['allow_fallback_for_entra'] ?? false);

$sso        = load_sso_settings($config);
$ssoEnabled = !empty($sso['enabled']);

if (!empty($_SESSION['user'])) {
  header("Location: {$base}/admin/index.php");
  exit;
}

$orgFromHost = null;
$orgLogoUrl = '';
$orgHeading = 'Admin sign in';

if ($pdo instanceof PDO) {
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  // Detect organisation from subdomain: {slug}.towlens.net / {slug}.yourdomain
  $host = $_SERVER['HTTP_HOST'] ?? '';
  $hostSlug = '';

  if ($host) {
    // e.g. client.towlens.net -> "client"
    // e.g. something.client.towlens.net -> still treat first label as slug
    $parts = explode('.', $host);
    if (count($parts) >= 3) {
      $hostSlug = strtolower($parts[0]);
    }
  }

  if ($hostSlug !== '') {
    $stmt = $pdo->prepare("
      SELECT id, name, slug, logo_url
      FROM organisations
      WHERE slug = ?
      LIMIT 1
    ");
    $stmt->execute([$hostSlug]);
    $orgFromHost = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;

    if ($orgFromHost) {
      $orgLogoUrl = trim((string)($orgFromHost['logo_url'] ?? ''));
      $orgHeading = $orgFromHost['name'] . ' — Admin sign in';
    }
  }
}

function csrf_token(): string {
  if (empty($_SESSION['csrf_login'])) {
    $_SESSION['csrf_login'] = bin2hex(random_bytes(16));
  }
  return $_SESSION['csrf_login'];
}

function csrf_ok(): bool {
  return !empty($_POST['csrf']) && hash_equals($_SESSION['csrf_login'] ?? '', $_POST['csrf']);
}

$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['login_method'] ?? '') === 'password') {
  $email = trim($_POST['email'] ?? '');
  $pass  = (string)($_POST['pass']  ?? '');

  global $pdo, $allowPassword, $allowLegacy, $basicCreds, $allowEntraPw, $base, $err;

  if (!$allowPassword) {
    $err = 'Password sign-in is disabled. Please use Microsoft SSO.';
  } elseif (!csrf_ok()) {
    $err = 'Your session expired. Please try again.';
  } elseif ($email === '' || $pass === '') {
    $err = 'Please enter your email and password.';
  } else {
    // Try DB users for this email across ALL orgs/companies; pick row whose hash matches.
    $stmt = $pdo->prepare("
      SELECT u.id, u.email, u.display_name, u.role, u.provider, u.password_hash, u.is_active,
             u.organisation_id, u.company_id,
             o.name AS org_name, o.slug AS org_slug,
             c.name AS company_name, c.slug AS company_slug
      FROM users u
      JOIN organisations o ON o.id = u.organisation_id
      JOIN companies      c ON c.id = u.company_id
      WHERE LOWER(u.email)=LOWER(?)
      ORDER BY u.organisation_id, u.company_id
    ");
    $stmt->execute([$email]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $authed = null;
    foreach ($rows as $u) {
      if (!$u['is_active'] && $u['is_active'] !== null) continue;
      $prov = strtolower($u['provider'] ?? 'local');
      $provAllowed = ($prov === 'local') || ($prov === 'entra' && $allowEntraPw);
      if ($provAllowed && !empty($u['password_hash']) && password_verify($pass, $u['password_hash'])) {
        $authed = $u;
        break;
      }
    }

    if ($authed) {
      $_SESSION['org'] = [
        'id'   => (int)$authed['organisation_id'],
        'name' => $authed['org_name'],
        'slug' => $authed['org_slug'],
      ];
      $_SESSION['company'] = [
        'id'   => (int)$authed['company_id'],
        'name' => $authed['company_name'],
        'slug' => $authed['company_slug'],
      ];
      $_SESSION['user'] = [
        'id'               => (int)$authed['id'],
        'email'            => $authed['email'],
        'name'             => $authed['display_name'] ?: $authed['email'],
        'role'             => $authed['role'] ?: 'staff',
        'provider'         => $authed['provider'],
        'organisation_id'  => (int)$authed['organisation_id'],
        'company_id'       => (int)$authed['company_id'],
        'is_org_admin'     => (int)($authed['role'] === 'org_admin' || $authed['role'] === 'admin'),
      ];
      try {
        $pdo->prepare("UPDATE users SET last_login_at=NOW() WHERE id=?")->execute([(int)$authed['id']]);
      } catch (Throwable $e) {}
      header("Location: {$base}/admin/index.php");
      exit;
    }

    // Legacy fallback (config admin) — maps to first org+company to keep pages scoped
    if ($allowLegacy && $basicCreds && $email === ($basicCreds['user'] ?? '') && $pass === ($basicCreds['pass'] ?? '')) {
      $orgRow = $pdo->query("SELECT id, name, slug FROM organisations ORDER BY id LIMIT 1")->fetch(PDO::FETCH_ASSOC)
            ?: ['id' => 0, 'name' => 'Global',  'slug' => 'global'];
      $cmpStmt = $pdo->prepare("SELECT id, name, slug FROM companies WHERE organisation_id=? ORDER BY id LIMIT 1");
      $cmpStmt->execute([(int)$orgRow['id']]);
      $cmp = $cmpStmt->fetch(PDO::FETCH_ASSOC)
            ?: ['id' => 0, 'name' => 'Default', 'slug' => 'default'];

      $_SESSION['org'] = [
        'id'   => (int)$orgRow['id'],
        'name' => $orgRow['name'],
        'slug' => $orgRow['slug'],
      ];
      $_SESSION['company'] = [
        'id'   => (int)$cmp['id'],
        'name' => $cmp['name'],
        'slug' => $cmp['slug'],
      ];
      $_SESSION['user'] = [
        'id'               => 0,
        'email'            => $email,
        'name'             => 'Admin',
        'role'             => 'admin',
        'provider'         => 'local',
        'organisation_id'  => (int)$orgRow['id'],
        'company_id'       => (int)$cmp['id'],
        'is_org_admin'     => 1,
      ];
      header("Location: {$base}/admin/index.php");
      exit;
    }

    $err = 'Invalid email or password.';
  }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title><?= htmlspecialchars($orgHeading) ?><?= $isDemo ? ' (Demo Mode)' : '' ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    :root{
      --bg:#e5e9f0;
      --bg-accent:#f3f6fb;
      --win:#ffffff;
      --ink:#1f2933;
      --muted:#6b7280;
      --line:#cfd6de;
      --brand:#2f6db2;
      --brand-soft:#e0ecfb;
      --danger-bg:#fae7e7;
      --danger-border:#e3b1b1;
      --danger-text:#7f2020;
      --radius:6px;
      --shadow-soft:0 6px 14px rgba(15,23,42,.08);
      --hdr:linear-gradient(#f9fafb,#e8edf3);
    }
    *{box-sizing:border-box;margin:0;padding:0}
    html,body{height:100%}
    body{
      margin:0;
      font:13px/1.45 "Segoe UI",Tahoma,Arial,sans-serif;
      color:var(--ink);
      background:
        radial-gradient(circle at top left,rgba(47,109,178,0.12),transparent),
        radial-gradient(circle at bottom right,rgba(148,163,253,0.1),transparent),
        var(--bg);
      -webkit-user-select:none;
      -moz-user-select:none;
      -ms-user-select:none;
      user-select:none;
    }
    .shell{
      min-height:100vh;
      display:flex;
      align-items:center;
      justify-content:center;
      padding:24px;
    }
    .window{
      width:min(760px,92vw);
      background:var(--win);
      border:1px solid var(--line);
      border-radius:var(--radius);
      box-shadow:var(--shadow-soft);
      overflow:hidden;
    }
    .ribbon{
      background:var(--hdr);
      border-bottom:1px solid var(--line);
      padding:10px 16px;
      display:flex;
      align-items:center;
      justify-content:space-between;
      gap:12px;
    }
    .ribbon-left{
      display:flex;
      align-items:center;
      gap:10px;
    }
    .ribbon-icon{
      width:16px;
      height:16px;
      border-radius:3px;
      background:linear-gradient(145deg,var(--brand),#4f8ad1);
      box-shadow:0 1px 2px rgba(0,0,0,.18) inset;
      position:relative;
    }
    .ribbon-icon::before,
    .ribbon-icon::after{
      content:"";
      position:absolute;
      inset:4px 3px;
      border-radius:2px;
      border:1px solid rgba(255,255,255,.7);
    }
.org-logo{
  height:56px;
  max-width:220px;
  object-fit:contain;
  display:block;
  -webkit-user-drag:none;
  user-select:none;
  pointer-events:none; /* stops grabbing/dragging */
}
    .ribbon-title{
      display:flex;
      flex-direction:column;
    }
    .ribbon-title h1{
      font-size:16px;
      font-weight:600;
      margin:0;
      letter-spacing:.01em;
      color:#111827;
    }
    .ribbon-sub{
      font-size:11px;
      color:var(--muted);
    }
    .chip{
      background:#fef3c7;
      border:1px solid #fde68a;
      color:#92400e;
      border-radius:999px;
      padding:2px 9px;
      font-size:11px;
      font-weight:600;
    }
    .body{
      padding:16px 18px 18px;
    }
    .muted{
      color:var(--muted);
      margin-bottom:8px;
    }
    .alert{
      padding:10px 11px;
      border-radius:4px;
      background:var(--danger-bg);
      border:1px solid var(--danger-border);
      color:var(--danger-text);
      margin:0 0 10px;
      font-size:12px;
    }
    .hr{
      border:none;
      border-top:1px solid var(--line);
      margin:12px 0;
    }
    .stack{
      display:flex;
      flex-direction:column;
      gap:6px;
      margin:0 0 4px;
    }
    label{
      font-size:11px;
      color:var(--muted);
      display:block;
      margin-bottom:1px;
    }
    input[type=email],
    input[type=password]{
      padding:8px 9px;
      border:1px solid #cfd6de;
      border-radius:4px;
      min-width:0;
      width:100%;
      font-size:13px;
      background:#f9fafb;
      transition:border-color .18s,box-shadow .18s,background-color .18s;
      -webkit-user-select:text;
      -moz-user-select:text;
      -ms-user-select:text;
      user-select:text;
    }
    input[type=email]:focus,
    input[type=password]:focus{
      outline:none;
      border-color:var(--brand);
      background:#ffffff;
      box-shadow:0 0 0 1px var(--brand-soft),0 0 0 3px rgba(47,109,178,0.14);
    }
    .btn{
      appearance:none;
      border:1px solid #bfc8d2;
      background:linear-gradient(#f9fafb,#e6ecf2);
      font-weight:600;
      padding:8px 12px;
      border-radius:4px;
      cursor:pointer;
      font-size:13px;
      display:inline-flex;
      align-items:center;
      justify-content:center;
      gap:6px;
      transition:all .16s ease-out;
      -webkit-user-select:none;
      -moz-user-select:none;
      -ms-user-select:none;
      user-select:none;
    }
    .btn span{
      display:inline-flex;
      align-items:center;
      gap:6px;
    }
    .btn:hover{
      background:linear-gradient(#ffffff,#e2e8f0);
      box-shadow:0 1px 3px rgba(15,23,42,.12);
    }
    .btn:active{
      transform:translateY(1px);
      box-shadow:none;
    }
    .btn.primary{
      border-color:#2a5f9c;
      color:#ffffff;
      background:linear-gradient(#3b79c1,#255b94);
      box-shadow:0 2px 4px rgba(37,91,148,.35);
    }
    .btn.primary:hover{
      background:linear-gradient(#4b82c7,#24558b);
    }
    .btn.block{
      width:100%;
    }
    .sso-note{
      display:flex;
      align-items:center;
      gap:6px;
      font-size:11px;
      color:var(--muted);
      margin:2px 0 8px;
    }
    .sso-dot{
      width:6px;
      height:6px;
      border-radius:50%;
      background:var(--brand);
      box-shadow:0 0 6px rgba(47,109,178,.6);
    }
    .links{
      font-size:11px;
      margin-top:4px;
    }
    .links a{
      color:var(--brand);
      text-decoration:none;
      -webkit-user-select:none;
      -moz-user-select:none;
      -ms-user-select:none;
      user-select:none;
    }
    .links a:hover{
      text-decoration:underline;
    }
    form{
      margin:0;
    }
@media (max-width:480px){
  .org-logo{
    height:42px;        /* still big, but sensible on mobile */
    max-width:180px;
  }
    button, input, select, textarea{
      -webkit-user-select:auto;
      -moz-user-select:auto;
      -ms-user-select:auto;
      user-select:auto;
    }
  </style>
</head>
<body>
  <div class="shell">
    <main class="window">
      <div class="ribbon">
        <div class="ribbon-left">
<?php if ($orgLogoUrl): ?>
  <img src="<?= htmlspecialchars($orgLogoUrl) ?>"
       alt="<?= htmlspecialchars($orgFromHost['name'] ?? 'Logo') ?>"
       class="org-logo"
       draggable="false">
<?php else: ?>
  <div class="ribbon-icon" aria-hidden="true"></div>
<?php endif; ?>
          <div class="ribbon-title">
            <h1><?= htmlspecialchars($orgFromHost['name'] ?? 'Admin sign in') ?></h1>
            <div class="ribbon-sub">Secure access to your control panel</div>
          </div>
        </div>
        <?php if ($isDemo): ?>
          <span class="chip">DEMO MODE</span>
        <?php endif; ?>
      </div>

      <div class="body">
        <p class="muted">Choose how you’d like to sign in.</p>

        <?php if ($err): ?>
          <div class="alert"><?= htmlspecialchars($err) ?></div>
        <?php endif; ?>

        <?php if ($ssoEnabled): ?>
          <p style="margin:0 0 6px;">
            <button type="button"
                    class="btn primary block"
                    id="entraBtn"
                    data-nav="<?= htmlspecialchars($base) ?>/admin/sso/start.php">
              <span>
                <span style="display:inline-grid;grid-template-columns:repeat(2,5px);gap:1px;">
                  <span style="width:5px;height:5px;background:#f35325;"></span>
                  <span style="width:5px;height:5px;background:#81bc06;"></span>
                  <span style="width:5px;height:5px;background:#05a6f0;"></span>
                  <span style="width:5px;height:5px;background:#ffba08;"></span>
                </span>
                <span>Sign in with Entra</span>
              </span>
            </button>
          </p>
          <div class="sso-note">
            <span class="sso-dot"></span>
            <span>Use your Microsoft Entra ID account.</span>
          </div>
          <div class="hr"></div>
        <?php endif; ?>

        <?php if ($allowPassword): ?>
          <form method="post" action="" autocomplete="off">
            <input type="hidden" name="login_method" value="password">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">

            <div class="stack">
              <label for="email">Work email</label>
              <input type="email" id="email" name="email" placeholder="you@company.com" required autocomplete="email">
            </div>

            <div class="stack" style="margin-top:4px;">
              <label for="pass">Password</label>
              <input type="password" id="pass" name="pass" placeholder="Password" required autocomplete="current-password" minlength="<?= (int)$minLen ?>">
            </div>

            <p style="margin:10px 0 4px;">
              <button class="btn block" type="submit">
                <span>Sign in with email &amp; password</span>
              </button>
            </p>

            <div class="links">
              <a href="<?= htmlspecialchars($base) ?>/admin/forgot">Forgot password?</a>
            </div>
          </form>
        <?php else: ?>
          <p class="muted">Password sign-in is disabled. Please use Microsoft SSO.</p>
        <?php endif; ?>
      </div>
    </main>
  </div>

  <script>
    (function(){
      var b = document.getElementById('entraBtn');
      if (b && b.dataset.nav) {
        b.addEventListener('click', function () {
          window.location.assign(b.dataset.nav);
        });
      }
    })();

    // Block right-click
    window.addEventListener('contextmenu', function(e){
      e.preventDefault();
    }, {capture:true});

    // Extra: mitigate text selection attempts via drag
    window.addEventListener('mousedown', function(e){
      var t = e.target;
      if (t.tagName === 'INPUT' || t.tagName === 'BUTTON' || t.tagName === 'SELECT' ||
          t.tagName === 'TEXTAREA' || t.tagName === 'A') {
        return;
      }
      if (window.getSelection) {
        var sel = window.getSelection();
        if (sel && sel.removeAllRanges) sel.removeAllRanges();
      }
    });
  </script>
</body>
</html>
