<?php
declare(strict_types=1);
require __DIR__ . '/app/bootstrap.php';
if (user()) redirect('index.php');

$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $email = strtolower(trim($_POST['email'] ?? ''));
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $check = db()->prepare('SELECT COUNT(*) FROM login_attempts WHERE (email=? OR ip_address=?) AND attempted_at > DATE_SUB(NOW(), INTERVAL 15 MINUTE)');
    $check->execute([$email, $ip]);
    if ((int)$check->fetchColumn() >= 10) {
        $error = 'Too many attempts. Please wait 15 minutes before trying again.';
    } else {
        $stmt = db()->prepare('SELECT * FROM users WHERE email=? AND active=1 LIMIT 1');
        $stmt->execute([$email]);
        $account = $stmt->fetch();
        if ($account && password_verify((string)($_POST['password'] ?? ''), $account['password_hash'])) {
            session_regenerate_id(true);
            unset($account['password_hash']);
            $account['session_version'] = (int)($account['session_version'] ?? 1);
            $_SESSION['user'] = $account;
            $_SESSION['last_activity_at'] = time();
            $_SESSION['session_rotated_at'] = time();
            $_SESSION['csrf'] = bin2hex(random_bytes(32));
            db()->prepare('UPDATE users SET last_login_at=NOW() WHERE id=?')->execute([$account['id']]);
            db()->prepare('DELETE FROM login_attempts WHERE email=? AND ip_address=?')->execute([$email, $ip]);
            audit('login', 'user', (int)$account['id']);
            redirect('index.php');
        }
        db()->prepare('INSERT INTO login_attempts (email,ip_address) VALUES (?,?)')->execute([$email, $ip]);
        $error = 'The email or password is incorrect.';
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
    <meta name="theme-color" content="#062b4d">
    <title>Login &mdash; Soda ZW Billing</title>
    <link rel="stylesheet" href="assets/accounting-os-v6.css?v=<?=e(BILLING_BUILD_ID)?>">
    <link rel="stylesheet" href="assets/sodazw-v10.css?v=<?=e(BILLING_BUILD_ID)?>">
    <link rel="stylesheet" href="assets/sodazw-v12.css?v=<?=e(BILLING_BUILD_ID)?>">
    <link rel="stylesheet" href="assets/sodazw-mobile.css?v=<?=e(BILLING_BUILD_ID)?>">
    <link rel="stylesheet" href="assets/sodazw-v14.css?v=<?=e(BILLING_BUILD_ID)?>">
</head>
<body class="auth-page accounting-v6 sodazw-v10 sodazw-v12 sodazw-v14">
<main class="auth-shell">
    <section class="auth-brand" aria-label="Soda ZW Billing and Operations">
        <div class="auth-brand-top">
            <img src="assets/sodazw-logo.png" alt="Soda ZW">
            <span>Private business workspace</span>
        </div>
        <div class="auth-brand-copy">
            <span class="eyebrow">Soda ZW Business OS</span>
            <h1>Everything together.<br><em>Ready when you are.</em></h1>
            <p>Manage sales, money, customers, stock and fulfilment from one secure Soda ZW workspace.</p>
            <div class="auth-benefits" aria-label="Workspace features">
                <span><b>01</b>Sales &amp; billing</span>
                <span><b>02</b>Cash &amp; accounts</span>
                <span><b>03</b>Stock &amp; fulfilment</span>
            </div>
        </div>
        <small><i aria-hidden="true"></i> Private Soda ZW system &middot; Authorised team members only</small>
    </section>
    <section class="auth-card">
        <div class="auth-card-heading">
            <span class="auth-access-mark"><i aria-hidden="true"></i> Secure team access</span>
            <h2>Welcome back</h2>
            <p>Enter your team credentials to continue.</p>
        </div>
        <?php if (isset($_GET['installed'])):?><div class="alert success" role="status">Installation complete. Sign in with your owner account.</div><?php endif;?>
        <?php if ($error):?><div class="alert error" role="alert"><?=e($error)?></div><?php endif;?>
        <form method="post">
            <?=csrf_field()?>
            <label><span class="auth-field-label">Email address</span><span class="auth-input"><i aria-hidden="true">@</i><input type="email" name="email" autocomplete="username" placeholder="name@sodazw.co.zw" required autofocus></span></label>
            <label><span class="auth-field-label">Password</span><span class="auth-input"><i aria-hidden="true">&#9679;</i><input id="login-password" type="password" name="password" autocomplete="current-password" placeholder="Enter your password" required><button type="button" class="password-toggle" aria-controls="login-password" aria-label="Show password">Show</button></span><small class="auth-caps-warning" data-caps-warning hidden>Caps Lock is on</small></label>
            <button class="button primary" type="submit"><span>Sign in securely</span><b aria-hidden="true">&rarr;</b></button>
        </form>
        <div class="auth-security"><span aria-hidden="true">&#10003;</span><p><strong>Protected access</strong><small>Rate-limited sign-in with secure sessions.</small></p></div>
        <div class="auth-help"><span>Access is managed by the Soda ZW workspace owner.</span><small>Billing &middot; Operations &middot; Finance</small></div>
    </section>
</main>
<script src="assets/app.js?v=<?=e(BILLING_BUILD_ID)?>"></script>
</body>
</html>
