<?php

require_once __DIR__ . '/app/auth.php';
require_once __DIR__ . '/app/customer-portal-accounts.php';
require_once __DIR__ . '/app/public-layout.php';

sparrow_start_session();

if (sparrow_current_user()) {
    sparrow_redirect('/sparrowseed/backyard/dashboard.php');
}

if (!empty($_SESSION['customer_portal_account_id'])) {
    sparrow_redirect('/sparrowseed/customer-portal.php');
}

$business_name = sparrow_public_setting(
    'business_name',
    'Sparrow & Seed Creations'
);

$error = '';
$login_csrf = $_SESSION['login_csrf'] ??= bin2hex(random_bytes(32));
$login_attempts = $_SESSION['login_attempts'] ?? [];
$login_attempts = array_values(array_filter(
    $login_attempts,
    static fn ($attempt) => is_int($attempt) && $attempt > time() - 900
));
$_SESSION['login_attempts'] = $login_attempts;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $login = trim($_POST['login'] ?? '');
    $password = $_POST['password'] ?? '';

    $submitted_csrf = (string) ($_POST['login_csrf'] ?? '');

    if (!hash_equals($login_csrf, $submitted_csrf)) {
        $error = 'Your login session expired. Please refresh and try again.';
    } elseif (count($login_attempts) >= 10) {
        http_response_code(429);
        $error = 'Too many login attempts. Please wait 15 minutes and try again.';
    } elseif ($login === '' || $password === '') {
        $error = 'Please enter your email or username and password.';
    } elseif (sparrow_login($login, $password)) {
        /*
         * Remove any leftover customer-session information
         * before entering the Backyard.
         */
        unset(
            $_SESSION['customer_portal_account_id'],
            $_SESSION['customer_key']
        );

        sparrow_redirect('/sparrowseed/backyard/dashboard.php');
    } else {
        $_SESSION['login_attempts'][] = time();
        $portal_account = sparrow_get_portal_account_by_username($login);

        if (
            $portal_account
            && !empty($portal_account['is_active'])
            && password_verify(
                $password,
                $portal_account['password_hash']
            )
        ) {
            session_regenerate_id(true);

            unset($_SESSION['backyard_user_id']);

            $_SESSION['customer_portal_account_id']
                = (int) $portal_account['id'];

            $_SESSION['customer_key']
                = $portal_account['customer_key'];

            $stmt = sparrow_db()->prepare("
                UPDATE customer_portal_accounts
                SET last_login_at = NOW()
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':id' => (int) $portal_account['id'],
            ]);

            sparrow_redirect('/sparrowseed/customer-portal.php');
        }

        $error = 'That login did not work. Please try again.';
    }
}

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Account Login | <?php echo sparrow_escape(sparrow_config('app_name')); ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #f9f2f7;
            color: #352733;
        }

        .login-wrap {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 24px;
        }

        .login-card {
            width: 100%;
            max-width: 420px;
            background: #ffffff;
            border: 1px solid #ead7e5;
            border-radius: 18px;
            padding: 28px;
            box-shadow: 0 8px 30px rgba(70, 35, 60, 0.08);
        }

        h1 {
            margin: 0 0 8px;
            font-size: 28px;
        }

        .subtext {
            margin: 0 0 24px;
            color: #725d6d;
        }

        label {
            display: block;
            margin: 14px 0 6px;
            font-weight: bold;
        }

        input {
            width: 100%;
            box-sizing: border-box;
            padding: 12px;
            border: 1px solid #d8c4d2;
            border-radius: 10px;
            font-size: 16px;
        }

        button {
            width: 100%;
            margin-top: 20px;
            padding: 12px 16px;
            border: 0;
            border-radius: 999px;
            background: #9b5c8f;
            color: white;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
        }

        button:hover {
            background: #864b7b;
        }

        .error {
            margin: 0 0 16px;
            padding: 12px;
            background: #fff0f0;
            border: 1px solid #efb9b9;
            border-radius: 10px;
            color: #8a2525;
        }
		
		.back-to-site {
    display: block;
    margin-top: 16px;
    color: #864b7b;
    text-align: center;
    text-decoration: none;
    font-weight: bold;
}

.back-to-site:hover {
    text-decoration: underline;
}
    </style>
</head>
<body>

<div class="login-wrap">
    <main class="login-card">
        <h1>Account Login</h1>
<p class="subtext">
    Log in to the Backyard or Customer Portal.
</p>

        <?php if ($error): ?>
            <div class="error">
                <?php echo sparrow_escape($error); ?>
            </div>
        <?php endif; ?>

        <form method="post">
            <input type="hidden" name="login_csrf" value="<?php echo sparrow_escape($login_csrf); ?>">
            <label for="login">Email or Username</label>
<input
    type="text"
    id="login"
    name="login"
    value="<?php echo sparrow_escape($_POST['login'] ?? ''); ?>"
    autocomplete="username"
    required
>

            <label for="password">Password</label>
            <input
                type="password"
                id="password"
                name="password"
                autocomplete="current-password"
                required
            >

            <button type="submit">Log In</button>
        </form>
		
		        <a
            class="back-to-site"
            href="<?php echo sparrow_escape(sparrow_url('/index.php')); ?>"
        >
            Back to Main Site
        </a>
		
    </main>
</div>

</body>
</html>
