<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/lib/client.php';

$tenantParam = tenant_param();
$_GET['tenant'] = $tenantParam;
$tenant = resolve_tenant_from_host();
if (!$tenant) {
    http_response_code(404);
    echo 'Shop not found.';
    exit;
}
$tenantId = (int) $tenant['id'];

if (client_current_user()) {
    header('Location: ' . APP_BASE . '/client/dashboard.php?tenant=' . urlencode($tenantParam));
    exit;
}

$error = '';
$flash = '';
$mode = (string) ($_POST['mode'] ?? $_GET['mode'] ?? 'password');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $email = trim((string) ($_POST['email'] ?? ''));
        $user = client_find_by_email($tenantId, $email);
        if ($mode === 'register') {
            $name = trim((string) ($_POST['name'] ?? ''));
            $phone = trim((string) ($_POST['phone'] ?? ''));
            $pass = (string) ($_POST['password'] ?? '');
            $pass2 = (string) ($_POST['password2'] ?? '');
            if ($pass !== $pass2) {
                throw new RuntimeException('Passwords do not match.');
            }
            $created = client_register_account($tenantId, $name, $email, $pass, $phone !== '' ? $phone : null);
            client_login_user($created);
            header('Location: ' . APP_BASE . '/client/dashboard.php?tenant=' . urlencode($tenantParam));
            exit;
        }

        if (!$user) {
            throw new RuntimeException('No account found for that email. Create an account first.');
        }
        if (user_is_owner($user)) {
            throw new RuntimeException('Owner accounts sign in at Admin, not the customer portal.');
        }

        if ($mode === 'magic') {
            $url = client_send_magic_link($user, $tenantParam);
            $flash = 'Sign-in link sent to your email.';
            if (REMINDER_MAIL_DRIVER === 'log') {
                $flash .= ' (Local: check storage/reminders/email.log — link: ' . $url . ')';
            }
        } else {
            $pass = (string) ($_POST['password'] ?? '');
            if (!client_verify_password($user, $pass)) {
                throw new RuntimeException('Incorrect password. Use “Email link” or set a password first.');
            }
            client_login_user($user);
            header('Location: ' . APP_BASE . '/client/dashboard.php?tenant=' . urlencode($tenantParam));
            exit;
        }
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

client_layout_header('Client login · ' . shop_company_name(null, $tenant), $tenant, $tenantParam, null);
?>
<section class="client-wrap">
  <h1>Client login</h1>
  <p class="muted">Create an account or sign in to manage appointments, cancel, or reschedule.</p>
  <?php if ($flash): ?><div class="book-flash ok"><?= htmlspecialchars($flash) ?></div><?php endif; ?>
  <?php if ($error): ?><div class="book-flash err"><?= htmlspecialchars($error) ?></div><?php endif; ?>

  <div class="tabs">
    <button type="button" class="active" data-tab="password">Password</button>
    <button type="button" data-tab="magic">Email link</button>
    <button type="button" data-tab="register">Create account</button>
  </div>

  <form method="post" class="book-form login-form" id="form-password">
    <input type="hidden" name="tenant" value="<?= htmlspecialchars($tenantParam) ?>">
    <input type="hidden" name="mode" value="password">
    <label>Email</label>
    <input type="email" name="email" required>
    <label>Password</label>
    <input type="password" name="password" required>
    <button class="btn" type="submit">Sign in</button>
  </form>

  <form method="post" class="book-form login-form panel-hidden" id="form-magic">
    <input type="hidden" name="tenant" value="<?= htmlspecialchars($tenantParam) ?>">
    <input type="hidden" name="mode" value="magic">
    <label>Email</label>
    <input type="email" name="email" required>
    <button class="btn" type="submit">Send sign-in link</button>
  </form>

  <form method="post" class="book-form login-form panel-hidden" id="form-register">
    <input type="hidden" name="tenant" value="<?= htmlspecialchars($tenantParam) ?>">
    <input type="hidden" name="mode" value="register">
    <label>Your name</label>
    <input type="text" name="name" required autocomplete="name">
    <label>Email</label>
    <input type="email" name="email" required autocomplete="email">
    <label>Phone (optional)</label>
    <input type="tel" name="phone" autocomplete="tel">
    <label>Password</label>
    <input type="password" name="password" required minlength="6" autocomplete="new-password">
    <label>Confirm password</label>
    <input type="password" name="password2" required minlength="6" autocomplete="new-password">
    <button class="btn" type="submit">Create account &amp; sign in</button>
  </form>
</section>
<script>
document.querySelectorAll('.tabs button').forEach(btn => {
  btn.addEventListener('click', () => {
    document.querySelectorAll('.tabs button').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    const tab = btn.dataset.tab;
    ['password','magic','register'].forEach(id => {
      document.getElementById('form-' + id).classList.toggle('panel-hidden', id !== tab);
    });
  });
});
</script>
<?php client_layout_footer(); ?>
