<?php
declare(strict_types=1);

/**
 * Simple server-side login for Bellwether ERP
 * - Verifies username & password on the server (NO passwords in the browser)
 * - On success: creates a PHP session + an 'erp_user' cookie for the SPA bridge
 * - Add / change users by editing the $USERS array below.
 * - For proper security, replace plaintext 'plain' with 'hash' created by make_hash.php, then delete make_hash.php.
 */

$https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443);
ini_set('session.use_strict_mode', '1');
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_secure', $https ? '1' : '0');
session_set_cookie_params([
  'lifetime' => 0,
  'path' => '/erp',
  'domain' => '',
  'secure' => $https,
  'httponly' => true,
  'samesite' => 'Strict',
]);
session_start();

if (!empty($_SESSION['erp_user'])) {
  header("Location: /erp/");
  exit;
}

/**
 * USER STORE
 * username => [
 *    'display' => value placed in the SPA cookie (must match names your SPA maps, e.g. 'Tax', 'Audit', 'Accounts', 'Corporate', 'Admin & HR', 'Management', 'Aizaz', 'Arshad', 'CEO'),
 *    'plain'   => TEMPORARY plaintext (works until you move to hashes),
 *    'hash'    => password_hash() string (preferred). If provided, 'plain' is ignored.
 * ]
 *
 * For speed, this ships with the same temporary passwords you had in the SPA.
 * IMPORTANT: Change these immediately and move to 'hash' using make_hash.php.
 */
$USERS = [
  'Tax'        => ['display'=>'Tax',        'plain'=>'',       'hash'=>'$2y$10$4cl/4alF6ruxkmtxUlosseLjmzdF0R8xSBTHsKNVwSDHHZIri3k3W'],
  'Audit'      => ['display'=>'Audit',      'plain'=>'Audit1001!',     'hash'=>'$2y$10$kuWgqwLbmuSZeed3Llson.uLVXWLgujt1ZDz3ak3SE4Jw/ZlDAtKO'],
  'Accounts'   => ['display'=>'Accounts',   'plain'=>'',  'hash'=>'$2y$10$FN19F7BdCzBZXGsn.00.eOwxzm3oWaFMYkM4mN6dtKo0z.l9EpCRG'],
  'Corporate'  => ['display'=>'Corporate',  'plain'=>'', 'hash'=>'$2y$10$xV6qTk4nSkPX.P.gAy4G9ulusYscKmlqw0Xr4dFKXyclwQSxfhI7m'],
  'Admin & HR' => ['display'=>'Admin & HR', 'plain'=>'',   'hash'=>'$2y$10$HqFkJO8g3TV3TSij/M/TZ.achoJ9JvCZ2vab1Z7iZJ.HbuTpgV2wy'],
  'Management' => ['display'=>'Management', 'plain'=>'',      'hash'=>'$2y$10$Vo41Mttc8OFGuXehYiMQp.pVI3zvlwLVNiMUkwEI6OTcTc4P5hcEu'],
  'Aizaz'      => ['display'=>'Aizaz',      'plain'=>'',     'hash'=>'$2y$10$Opr/ci5mZA8JPNOaM/fxy.EhHKiP56D61d3qepdxay1YF8Av1Ln0m'],
  'Arshad'     => ['display'=>'Arshad',     'plain'=>'',       'hash'=>'$2y$10$Fjs.H7WG6mtSoS/4.UAR/eE3ZGjSlXvYBssaTE0yjMLlmQldcx7YO'],
  'CEO'        => ['display'=>'CEO',        'plain'=>'',       'hash'=>'$2y$10$1WkgXD4vLoMLxkjKsqwU3em2WJJu41AW2.K1voV8fBlfKqWP15EeW'],
];

function verify_user(string $username, string $password): bool {
  global $USERS;
  if (!isset($USERS[$username])) return false;
  $rec = $USERS[$username];
  if (!empty($rec['hash'])) {
    return password_verify($password, $rec['hash']);
  }
  // TEMPORARY: fallback to plaintext for quicker cut-over
  return isset($rec['plain']) && hash_equals($rec['plain'], $password);
}

$error = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $u = trim($_POST['username'] ?? '');
  $p = (string)($_POST['password'] ?? '');
  if ($u !== '' && $p !== '' && verify_user($u, $p)) {
    session_regenerate_id(true);
    $display = $USERS[$u]['display'];
    $_SESSION['erp_user'] = $display;
    // Cookie visible to JS so the SPA can map to a local user name
    setcookie('erp_user', $display, [
      'expires' => 0,
      'path' => '/erp',
      'secure' => $https,
      'httponly' => false, // readable by SPA (JS)
      'samesite' => 'Strict',
    ]);
    header("Location: /erp/");
    exit;
  } else {
    $error = "Invalid username or password.";
  }
}

?><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>ERP Login</title>
  <style>
    body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial; margin:0; background:#f7fafc; color:#1f2937; }
    .wrap { max-width:420px; margin:8vh auto; background:#fff; padding:24px; border-radius:12px; box-shadow:0 10px 25px rgba(0,0,0,.06); }
    h1 { margin:0 0 10px; font-size:22px; }
    p.muted { color:#6b7280; margin-top:0 }
    label { display:block; margin:14px 0 6px; font-weight:600; }
    input, select { width:100%; padding:10px 12px; border:1px solid #d1d5db; border-radius:8px; font:inherit; }
    button { width:100%; padding:12px; border:0; border-radius:10px; font-weight:700; cursor:pointer; background:#111827; color:#fff; margin-top:16px; }
    .error { background:#fee2e2; color:#991b1b; padding:10px 12px; border-radius:8px; margin:10px 0; }
    .hint { font-size:12px; color:#6b7280; margin-top:12px; }
  </style>
</head>
<body>
  <div class="wrap">
    <h1>Sign in</h1>
    <p class="muted">Enter your ERP username and password.</p>
    <?php if ($error): ?>
      <div class="error"><?=htmlspecialchars($error, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');?></div>
    <?php endif; ?>
    <form method="post" action="">
      <label for="username">Username</label>
<input id="username" name="username" type="text" required autocomplete="username" inputmode="text" value="<?=htmlspecialchars($_POST['username'] ?? '', ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');?>" />

      <label for="password">Password</label>
      <input id="password" name="password" type="password" required autocomplete="current-password">

      <button type="submit">Login</button>
    </form>
</div>
</body>
</html>