<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/lib/tenant.php';
require_once dirname(__DIR__) . '/lib/users.php';
require_once dirname(__DIR__) . '/lib/admin_layout.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

$tenant = resolve_tenant_from_host();
if (!$tenant) {
    http_response_code(404);
    echo 'Shop not found.';
    exit;
}
$tenantId = (int) $tenant['id'];
$_SESSION['tenant_id'] = $tenantId;
$shopName = shop_company_name(null, $tenant);

if (!empty($_SESSION['admin_logged_in']) && (int) ($_SESSION['tenant_id'] ?? 0) === $tenantId) {
    header('Location: ' . APP_BASE . '/admin/index.php');
    exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user = trim((string) ($_POST['username'] ?? ''));
    $pass = (string) ($_POST['password'] ?? '');
    $owner = owner_find_login($tenantId, $user);
    if ($owner && owner_verify_password($owner, $pass)) {
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['tenant_id'] = $tenantId;
        $_SESSION['admin_user_id'] = (int) $owner['id'];
        header('Location: ' . APP_BASE . '/admin/index.php');
        exit;
    }
    $error = 'Invalid owner credentials for this shop.';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Owner login · <?= htmlspecialchars($shopName) ?></title>
  <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600&family=Space+Grotesk:wght@500;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="<?= APP_BASE ?>/assets/admin.css">
</head>
<body>
  <div class="login-wrap">
    <form class="login-card" method="post">
      <h1><?= htmlspecialchars($shopName) ?></h1>
      <p class="muted">Owner / admin login. Customers use the public site or the BarberShop app.</p>
      <?php if ($error): ?><div class="flash error"><?= htmlspecialchars($error) ?></div><?php endif; ?>
      <label>Username or email</label>
      <input type="text" name="username" required autocomplete="username">
      <label>Password</label>
      <input type="password" name="password" required autocomplete="current-password">
      <button class="btn" type="submit" style="width:100%">Sign in</button>
    </form>
    <?php require_once dirname(__DIR__) . '/lib/sn_credit.php'; ?>
    <div class="admin-sn-footer login-sn">
      <?php sn_credit_render(); ?>
    </div>
  </div>
</body>
</html>
