<?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>Billing &amp; Operations</span>
        </div>
        <div class="auth-brand-copy">
            <span class="eyebrow">Soda ZW command centre</span>
            <h1>Run the business.<br><em>Keep the sparkle.</em></h1>
            <p>One secure workspace for sales, invoices, payments, stock, refills and customer follow-ups.</p>
            <div class="auth-benefits" aria-label="Workspace features">
                <span><b>01</b>Finance visibility</span>
                <span><b>02</b>Customer records</span>
                <span><b>03</b>Stock &amp; refills</span>
            </div>
        </div>
        <small>Private Soda ZW business system &middot; Authorised users only</small>
    </section>
    <section class="auth-card">
        <div class="auth-card-heading">
            <span class="eyebrow">Secure team access</span>
            <h2>Welcome back</h2>
            <p>Sign in to continue to Soda ZW Billing.</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>Email address<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>Password<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></label>
            <button class="button primary" type="submit">Sign in to workspace <span aria-hidden="true">&rarr;</span></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>
    </section>
</main>
<script>
document.querySelector('.password-toggle')?.addEventListener('click',function(){var input=document.getElementById('login-password');var show=input.type==='password';input.type=show?'text':'password';this.textContent=show?'Hide':'Show';this.setAttribute('aria-label',(show?'Hide':'Show')+' password');});
</script>
</body>
</html>
