<?php
require __DIR__ . '/includes/functions.php';
$currentPage = 'account';
$pageTitle = 'Customer Login | Furnify';
$errors = array();
$next = isset($_GET['next']) ? (string) $_GET['next'] : 'customer-dashboard.php';
if (strpos($next, '://') !== false || strpos($next, "\n") !== false) {
    $next = 'customer-dashboard.php';
}
if (customer_current()) {
    header('Location: customer-dashboard.php');
    exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token((string) (isset($_POST['csrf_token']) ? $_POST['csrf_token'] : ''))) {
        $errors[] = 'Security token expired. Please try again.';
    }
    if (!$errors) {
        $result = customer_login(isset($_POST['email']) ? $_POST['email'] : '', isset($_POST['password']) ? $_POST['password'] : '');
        if ($result['ok']) {
            $postedNext = isset($_POST['next']) ? (string) $_POST['next'] : 'customer-dashboard.php';
            if (strpos($postedNext, '://') !== false || strpos($postedNext, "\n") !== false) {
                $postedNext = 'customer-dashboard.php';
            }
            header('Location: ' . $postedNext);
            exit;
        }
        $errors[] = $result['error'];
    }
}
require __DIR__ . '/includes/header.php';
?>
<section class="page-section">
    <div class="container narrow">
        <div class="premium-panel p-4 p-lg-5">
            <p class="eyebrow">Customer portal</p>
            <h1>Login to Furnify</h1>
            <p class="lead">View your orders, payment status, custom sofa requests, and Re-Up estimates.</p>
            <?php if (!customer_accounts_available()): ?><div class="alert alert-warning">Customer accounts require MySQL setup.</div><?php endif; ?>
            <?php foreach ($errors as $error): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endforeach; ?>
            <form method="post" class="row g-3">
                <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
                <input type="hidden" name="next" value="<?= e($next) ?>">
                <div class="col-12"><label class="form-label">Email</label><input class="form-control" type="email" name="email" required autocomplete="email" value="<?= e(isset($_POST['email']) ? $_POST['email'] : '') ?>"></div>
                <div class="col-12"><label class="form-label">Password</label><input class="form-control" type="password" name="password" required autocomplete="current-password"></div>
                <div class="col-12"><button class="btn btn-primary btn-lg w-100" type="submit" <?= customer_accounts_available() ? '' : 'disabled' ?>>Login</button></div>
            </form>
            <p class="mt-4 mb-2 text-center"><a href="forgot-password.php">Forgot password?</a></p>
            <p class="mb-0 text-center">No account yet? <a href="register.php">Create customer account</a>.</p>
        </div>
    </div>
</section>
<?php require __DIR__ . '/includes/footer.php'; ?>
