<?php
// login.php (multiuser v7) — standalone, schema-auto-detecting
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');

header('Content-Type: text/html; charset=utf-8');
if (session_status() !== PHP_SESSION_ACTIVE) {
  @session_start();
}

function h(string $s): string { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

function load_local_env(string $path): void {
  if (!is_file($path) || !is_readable($path)) return;
  $lines = @file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  if (!is_array($lines)) return;
  foreach ($lines as $line) {
    $line = trim($line);
    if ($line === '' || $line[0] === '#') continue;
    if (stripos($line, 'export ') === 0) $line = trim(substr($line, 7));
    $pos = strpos($line, '=');
    if ($pos === false) continue;
    $k = trim(substr($line, 0, $pos));
    $v = trim(substr($line, $pos + 1));
    if ($k === '') continue;
    if ((strlen($v) >= 2) && (($v[0] === '"' && $v[strlen($v)-1] === '"') || ($v[0] === "'" && $v[strlen($v)-1] === "'"))) {
      $v = substr($v, 1, -1);
    }
    if (getenv($k) === false) { @putenv($k.'='.$v); $_ENV[$k] = $v; }
  }
}
load_local_env(__DIR__ . '/.env');

function db(): PDO {
  $dsn  = (string)(getenv('DB_DSN') ?: '');
  $user = (string)(getenv('DB_USER') ?: '');
  $pass = (string)(getenv('DB_PASS') ?: '');
  if ($dsn === '') throw new RuntimeException('Missing DB_DSN in .env');
  return new PDO($dsn, $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  ]);
}

/**
 * Detect which password column exists on users table.
 * Supports: password_hash, pass_hash, password (legacy), pass (legacy)
 */
function detect_users_password_column(PDO $pdo, string $table = 'users'): string {
  $dbName = $pdo->query('SELECT DATABASE()')->fetchColumn();
  if (!is_string($dbName) || $dbName === '') return 'password_hash';
  $st = $pdo->prepare("
    SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = :db AND TABLE_NAME = :t
  ");
  $st->execute([':db' => $dbName, ':t' => $table]);
  $cols = array_map(fn($r) => strtolower((string)$r['COLUMN_NAME']), $st->fetchAll());
  $prefs = ['password_hash','pass_hash','password','pass'];
  foreach ($prefs as $p) if (in_array($p, $cols, true)) return $p;
  foreach ($cols as $c) if (strpos($c, 'pass') !== false) return $c;
  return 'password_hash';
}

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

function verify_password(string $input, string $stored, string $colName): bool {
  $stored = (string)$stored;
  if ($stored === '') return false;

  if (in_array(strtolower($colName), ['password_hash','pass_hash'], true)) {
    return password_verify($input, $stored);
  }

  if (strlen($stored) === 32 && ctype_xdigit($stored)) {
    return hash_equals(strtolower($stored), md5($input));
  }
  return hash_equals($stored, $input);
}

$err = '';
$ok  = '';

try {
  $pdo = db();
  $pwdCol = detect_users_password_column($pdo, 'users');

  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf = (string)($_POST['csrf'] ?? '');
    if (!hash_equals((string)($_SESSION['csrf'] ?? ''), $csrf)) {
      throw new RuntimeException('Security check failed (CSRF). Refresh and try again.');
    }

    $email = trim((string)($_POST['email'] ?? ''));
    $pass  = (string)($_POST['password'] ?? '');

    if ($email === '' || $pass === '') throw new RuntimeException('Email and password are required.');

    $sql = "SELECT id, email, display_name, {$pwdCol} AS pwd FROM users WHERE email = :email LIMIT 1";
    $st = $pdo->prepare($sql);
    $st->execute([':email' => $email]);
    $u = $st->fetch();

    if (!$u || !verify_password($pass, (string)($u['pwd'] ?? ''), $pwdCol)) {
      $err = 'Invalid email or password.';
    } else {
      $_SESSION['uid'] = (int)$u['id'];
      $_SESSION['user_id'] = (int)$u['id'];
      $_SESSION['auth_user_id'] = (int)$u['id'];
      $_SESSION['user_email'] = (string)$u['email'];
      $_SESSION['display_name'] = (string)($u['display_name'] ?? '');

      $dest = 'dashboard.php';
      if (!headers_sent()) {
        header('Location: ' . $dest);
        exit;
      }
      $ok = 'Login ok. Redirecting…';
      echo '<script>location.href='.json_encode($dest).';</script>';
      exit;
    }
  }
} catch (Throwable $e) {
  error_log('[login] ' . $e->getMessage());
  $err = 'Login failed due to a server error. Check error logs.';
}

$csrf = ensure_csrf();
?><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>Studio — Sign in</title>
  <style>
    :root{
      --bg:#070a10; --text:#e8eefc; --muted:#9aa7c3; --line:rgba(255,255,255,.08);
      --accent:#2b6dff; --accent2:#17d1ff; --danger:#ff3b5c;
      --radius:18px; --shadow: 0 18px 60px rgba(0,0,0,.55);
    }
    *{box-sizing:border-box}
    body{
      margin:0; min-height:100vh;
      background:
        radial-gradient(1200px 800px at 20% 0%, rgba(43,109,255,.18), transparent 55%),
        radial-gradient(900px 700px at 100% 30%, rgba(23,209,255,.12), transparent 60%),
        linear-gradient(180deg, #05070c, var(--bg));
      color:var(--text);
      font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial;
      display:flex; align-items:center; justify-content:center;
      padding:28px;
    }
    .card{
      width:min(980px, 100%);
      display:grid;
      grid-template-columns: 1.05fr .95fr;
      gap:18px;
      background: linear-gradient(180deg, rgba(255,255,255,.06), rgba(255,255,255,.03));
      border:1px solid var(--line);
      border-radius: calc(var(--radius) + 6px);
      box-shadow: var(--shadow);
      overflow:hidden;
      backdrop-filter: blur(10px);
    }
    .hero{
      padding:34px 34px 30px;
      background:
        radial-gradient(800px 540px at 20% 10%, rgba(43,109,255,.22), transparent 60%),
        radial-gradient(760px 540px at 80% 40%, rgba(23,209,255,.16), transparent 62%),
        linear-gradient(180deg, rgba(11,18,32,.75), rgba(7,10,16,.75));
      border-right:1px solid var(--line);
    }
    .brand{display:flex; align-items:center; gap:10px; margin-bottom:18px; letter-spacing:.08em; text-transform:uppercase; font-weight:700; font-size:12px; color:rgba(232,238,252,.78)}
    .dot{width:10px; height:10px; border-radius:999px; background: linear-gradient(135deg, var(--accent), var(--accent2)); box-shadow: 0 0 0 6px rgba(43,109,255,.10), 0 0 26px rgba(43,109,255,.35)}
    h1{margin:0 0 10px; font-size:34px; line-height:1.15}
    .sub{margin:0; color:var(--muted); font-size:14px; line-height:1.55; max-width:52ch}
    .form{padding:34px 34px 30px; background: linear-gradient(180deg, rgba(14,21,36,.75), rgba(7,10,16,.72))}
    .title{margin:0 0 6px; font-size:20px; font-weight:700}
    .muted{color:var(--muted); font-size:13px; margin:0 0 18px}
    .row{display:grid; gap:8px; margin:12px 0}
    label{font-size:12px; color:rgba(232,238,252,.78)}
    input{width:100%; background: rgba(9,14,25,.7); border:1px solid rgba(255,255,255,.10); color:var(--text); padding:12px 12px; border-radius: 12px; outline:none; font-size:14px}
    input:focus{border-color: rgba(43,109,255,.55); box-shadow: 0 0 0 4px rgba(43,109,255,.16)}
    .actions{display:flex; align-items:center; justify-content:space-between; margin-top:16px; gap:10px; flex-wrap:wrap}
    .btn{appearance:none; border:1px solid rgba(255,255,255,.12); background: linear-gradient(180deg, rgba(43,109,255,.22), rgba(43,109,255,.08)); color:var(--text); padding:11px 14px; border-radius: 12px; cursor:pointer; font-weight:700; letter-spacing:.02em; box-shadow: 0 10px 26px rgba(0,0,0,.35)}
    .btn:hover{filter:brightness(1.05)}
    .link{color: rgba(232,238,252,.86); text-decoration:none; font-size:13px; border-bottom:1px dashed rgba(255,255,255,.18); padding-bottom:2px}
    .alert{margin:10px 0 0; padding:10px 12px; border-radius:12px; border:1px solid rgba(255,255,255,.10); background: rgba(255,255,255,.04); font-size:13px; color: rgba(232,238,252,.92)}
    .alert.err{border-color: rgba(255,59,92,.35); background: rgba(255,59,92,.10); color: rgba(255,214,220,.98)}
    .foot{margin-top:18px; color: rgba(154,167,195,.75); font-size:12px}
    @media (max-width: 860px){ .card{grid-template-columns:1fr} .hero{border-right:none; border-bottom:1px solid var(--line)} }
  </style>
</head>
<body>
  <div class="card">
    <section class="hero">
      <div class="brand"><span class="dot"></span> ITAHUKA STUDIO</div>
      <h1>Sign in</h1>
      <p class="sub">Access your studio projects and streaming destinations. Projects and platforms are private per user.</p>
    </section>

    <section class="form">
      <div class="title">Welcome back</div>
      <p class="muted">Use the account you registered in this studio database.</p>

      <?php if ($err): ?>
        <div class="alert err"><?php echo h($err); ?></div>
      <?php elseif ($ok): ?>
        <div class="alert"><?php echo h($ok); ?></div>
      <?php endif; ?>

      <form method="post" action="">
        <input type="hidden" name="csrf" value="<?php echo h($csrf); ?>" />
        <div class="row">
          <label>Email</label>
          <input name="email" type="email" autocomplete="username" placeholder="you@example.com" required />
        </div>
        <div class="row">
          <label>Password</label>
          <input name="password" type="password" autocomplete="current-password" placeholder="Your password" required />
        </div>
        <div class="actions">
          <button class="btn" type="submit">Login</button>
          <a class="link" href="register.php">Create an account</a>
        </div>
      </form>

      <div class="foot">This login auto-detects the users password column (password_hash / password / pass_hash / pass).</div>
    </section>
  </div>
</body>
</html>
