<?php
require_once 'app/helpers/auth.php';
require_once 'app/helpers/csrf.php';
initSessionConfig();
$csrf = generateCsrfToken();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Forgot Password</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/auth.css" rel="stylesheet">
    <style>.muted-small{color:#6b7280;font-size:13px}</style>
</head>
<body class="auth-bg">

<main class="auth-card">
    <div class="auth-hero">
        <div class="auth-chip">🔁 Reset</div>
        <div>
            <h1 class="auth-title">Forgot your password?</h1>
            <p class="auth-sub">Enter your account email and we'll send a reset link.</p>
        </div>
    </div>

    <div id="errorBox" class="alert alert-danger error-box" role="alert" aria-live="polite"></div>

    <div class="mb-3">
        <label for="email" class="form-label small">Email</label>
        <input type="email" id="email" class="form-control" placeholder="you@example.com" autocomplete="email" required>
    </div>

    <div class="d-grid gap-2">
        <button id="sendReset" class="btn btn-primary btn-lg" type="button">
            <span id="btnLabel">Send Reset Link</span>
            <span id="btnSpinner" class="spinner-border spinner-border-sm ms-2 d-none" role="status" aria-hidden="true"></span>
        </button>
    </div>

    <div class="text-center mt-3 small">
        <a class="small-link" href="login.php">Back to Login</a>
    </div>

</main>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
var CSRF_TOKEN = <?= json_encode($csrf) ?>;

function showError(msg){ var $e = $('#errorBox'); $e.text(msg).addClass('show'); }

$('#sendReset').on('click', function(){
    $('#errorBox').removeClass('show').text('');
    var email = $('#email').val().trim();
    if (!email) { showError('Email is required.'); return; }

    var $btn = $(this); $btn.prop('disabled', true); $('#btnSpinner').removeClass('d-none');

    $.post('api/password.php?action=forgot', {
        email: email,
        _csrf_token: CSRF_TOKEN
    }, function(res){
        if (res && res.status === 'success') {
            alert(res.message || 'Reset email sent.');
        } else {
            showError((res && res.message) ? res.message : 'Unable to send reset link.');
        }
    }, 'json').fail(function(xhr){
        showError('Unable to process request. HTTP ' + xhr.status);
    }).always(function(){
        $btn.prop('disabled', false); $('#btnSpinner').addClass('d-none');
    });
});
</script>

</body>
</html>