<?php
/**
 * Branded client portal login.
 * URL: http://localhost/medmecs/client/login.php?slug=blue-central
 */
require_once __DIR__ . '/../includes/config.php';
start_session();

$slug = trim((string) ($_GET['slug'] ?? $_POST['slug'] ?? ''));
if ($slug === '') { http_response_code(404); exit('Client portal not found.'); }

$pdo = db();
$st = $pdo->prepare('SELECT cb.*, c.name AS client_name, c.id AS client_id
                     FROM client_branding cb JOIN clients c ON c.id = cb.client_id
                     WHERE cb.login_slug = ? AND c.deleted_at IS NULL');
$st->execute([$slug]);
$brand = $st->fetch();
if (!$brand) { http_response_code(404); exit('Client portal not found.'); }

if (is_logged_in()) {
    $u = current_user();
    if ($u['user_type'] === 'client' && (int)$u['client_id'] === (int)$brand['client_id']) {
        redirect('/client/overall.php?slug=' . urlencode($slug));
    }
    logout();
}

$errors = [];
$emailVal = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die();
    $emailVal = trim((string) input('email'));
    $password = (string) input('password');
    $emailLc  = strtolower($emailVal);

    $rateKey = 'cli_login|' . $slug . '|' . $emailLc . '|' . client_ip();
    if (!rate_limit_check($rateKey, LOGIN_MAX_ATTEMPTS, 60*15)) {
        $secs = rate_limit_remaining_seconds($rateKey);
        login_log_attempt(null, $emailLc, 'locked', "Rate limit; retry in {$secs}s");
        $errors[] = "Too many attempts. Try again in {$secs} seconds.";
    } elseif ($emailVal === '' || $password === '') {
        $errors[] = 'Both email and password are required.';
    } else {
        $u = $pdo->prepare("SELECT * FROM users WHERE email=? AND user_type='client' AND client_id=? LIMIT 1");
        $u->execute([$emailLc, $brand['client_id']]);
        $user = $u->fetch();

        $generic = 'Invalid email or password.';
        if (!$user || !password_verify($password, $user['password']) || $user['status'] !== 'active') {
            login_log_attempt($user['id'] ?? null, $emailLc, 'failed', 'Bad credentials');
            $errors[] = $generic;
        } else {
            rate_limit_reset($rateKey);
            $pdo->prepare('UPDATE users SET last_login_at=NOW(), last_login_ip=?, login_attempts=0, locked_until=NULL WHERE id=?')
                ->execute([client_ip(), $user['id']]);
            login_user($user);
            login_log_attempt((int)$user['id'], $emailLc, 'success');
            if (!empty($user['must_change_password'])) {
                redirect('/change-password.php');
            }
            redirect('/client/overall.php?slug=' . urlencode($slug));
        }
    }
}

$primary = $brand['primary_color'] ?? '#206bc4';
?><!doctype html><html lang="en"><head>
<meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/>
<title><?= e($brand['client_name']) ?> &mdash; Sign in</title>
<link href="https://cdn.jsdelivr.net/npm/@tabler/core@1.0.0-beta20/dist/css/tabler.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@2.47.0/tabler-icons.min.css" rel="stylesheet"/>
<style>:root{--tblr-primary:<?= e($primary) ?>;}body{background:linear-gradient(135deg,#f5f7fb 0%,#eef1f7 100%);}</style>
<?php require __DIR__ . '/../includes/compact-css.php'; ?>
</head><body><div class="page page-center"><div class="container container-tight py-4">
    <div class="text-center mb-4">
        <?php if (!empty($brand['logo_path'])): ?>
            <img src="<?= e($brand['logo_path']) ?>" height="48" alt="<?= e($brand['client_name']) ?>"/>
        <?php else: ?>
            <span class="d-inline-flex align-items-center fs-2 fw-bold" style="color:var(--tblr-primary)">
                <i class="ti ti-building-skyscraper me-2"></i><?= e($brand['client_name']) ?>
            </span>
        <?php endif; ?>
        <div class="text-secondary mt-2"><?= e($brand['login_message'] ?? 'Reporting portal') ?></div>
    </div>
    <div class="card card-md"><div class="card-body">
        <h2 class="h3 text-center mb-4">Sign in</h2>
        <?php if ($errors): ?><div class="alert alert-danger"><?php foreach ($errors as $m): ?><div><?= e($m) ?></div><?php endforeach; ?></div><?php endif; ?>
        <form method="POST" action="<?= e(url('/client/login.php')) ?>" autocomplete="off">
            <?= csrf_field() ?>
            <input type="hidden" name="slug" value="<?= e($slug) ?>">
            <div class="mb-3"><label class="form-label">Email</label>
                <input type="email" name="email" class="form-control" required value="<?= e($emailVal) ?>"></div>
            <div class="mb-3"><label class="form-label">Password</label>
                <input type="password" name="password" class="form-control" required></div>
            <div class="form-footer"><button class="btn btn-primary w-100"><i class="ti ti-login me-2"></i>Sign in</button></div>
        </form>
    </div></div>
    <div class="text-center text-secondary mt-3 small">Powered by <?= e(APP_NAME) ?></div>
</div></div></body></html>
