<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/iscms_public_auth.php';

iscms_public_session();

$error = '';
$info = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!iscms_csrf_validate($_POST['csrf_token'] ?? null)) {
        $error = 'Invalid security token. Reload and try again.';
    } else {
        $now = time();
        $_SESSION['forgot_pw_window'] = $_SESSION['forgot_pw_window'] ?? $now;
        if ($now - (int) $_SESSION['forgot_pw_window'] > 3600) {
            $_SESSION['forgot_pw_count'] = 0;
            $_SESSION['forgot_pw_window'] = $now;
        }
        $_SESSION['forgot_pw_count'] = (int) ($_SESSION['forgot_pw_count'] ?? 0) + 1;
        if ($_SESSION['forgot_pw_count'] > 10) {
            $error = 'Too many requests. Try again in an hour.';
        } else {
            require_once __DIR__ . '/layouts/dbconn.php';
            /** @var mysqli $conn */
            if (!iscms_table_exists($conn, 'password_resets')) {
                $error = 'Password reset is not available. Contact your administrator.';
            } else {
                $email = trim((string) ($_POST['email'] ?? ''));
                if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $error = 'Enter a valid email address.';
                } else {
                    $st = $conn->prepare(
                        'SELECT u.id, u.status, u.first_name FROM users u
                         INNER JOIN roles r ON u.role_id = r.id AND r.is_active = 1
                         WHERE u.email = ? LIMIT 1'
                    );
                    $uid = '';
                    $okUser = false;
                    if ($st) {
                        $st->bind_param('s', $email);
                        $st->execute();
                        $row = $st->get_result()->fetch_assoc();
                        $st->close();
                        if ($row && in_array($row['status'], ['active', 'pending_verification'], true)) {
                            $uid = (string) $row['id'];
                            $okUser = true;
                        }
                    }

                    if ($okUser && $uid !== '') {
                        $conn->query("DELETE FROM password_resets WHERE user_id = '" . $conn->real_escape_string($uid) . "'");
                        $raw = bin2hex(random_bytes(32));
                        $hash = hash('sha256', $raw);
                        $exp = date('Y-m-d H:i:s', strtotime('+2 hours'));
                        $ins = $conn->prepare(
                            'INSERT INTO password_resets (id, user_id, token_hash, expires_at) VALUES (UUID(), ?, ?, ?)'
                        );
                        if ($ins) {
                            $ins->bind_param('sss', $uid, $hash, $exp);
                            $ins->execute();
                            $ins->close();
                        }

                        $proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
                        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
                        $dir = dirname($_SERVER['SCRIPT_NAME'] ?? '');
                        $prefix = ($dir === '/' || $dir === '\\' || $dir === '.') ? '' : $dir;
                        $resetLink = $proto . '://' . $host . $prefix . '/reset_password.php?token=' . urlencode($raw);

                        if (function_exists('mail')) {
                            $subj = 'SSBS-ISCMS password reset';
                            $body = "You requested a password reset.\r\n\r\nUse this link (valid 2 hours):\r\n{$resetLink}\r\n\r\nIf you did not request this, ignore this email.\r\n";
                            @mail($email, $subj, $body, "From: noreply@ssbs.local\r\nContent-Type: text/plain; charset=UTF-8");
                        }
                    }

                    $info = 'If an account exists for that email, reset instructions have been sent. '
                        . 'Check your inbox or ask an administrator if you do not receive mail.';
                }
            }
            if (isset($conn) && $conn instanceof mysqli) {
                $conn->close();
            }
        }
    }
}

$csrf = iscms_csrf_token();
$pageTitle = 'Forgot password';

iscms_public_head($pageTitle);
?>
    <div class="iscms-pub-h"><i class="ri-lock-unlock-line me-2"></i><?= iscms_h($pageTitle) ?></div>
    <div class="iscms-pub-b">
        <?php if ($error !== ''): ?>
        <div class="alert alert-danger py-2" style="font-size:.85rem"><?= iscms_h($error) ?></div>
        <?php endif; ?>
        <?php if ($info !== ''): ?>
        <div class="alert alert-success py-2" style="font-size:.85rem"><?= iscms_h($info) ?></div>
        <?php endif; ?>
        <?php if ($info === ''): ?>
        <p class="text-muted small mb-3">Enter your registered email. We will send a reset link if the account is active.</p>
        <form method="post" action="forgot_password.php">
            <input type="hidden" name="csrf_token" value="<?= iscms_h($csrf) ?>">
            <div class="mb-3">
                <label class="form-label">Email</label>
                <input type="email" name="email" class="form-control form-control-sm" required maxlength="255" autocomplete="email">
            </div>
            <button type="submit" class="btn btn-primary btn-sm w-100">Send reset link</button>
        </form>
        <?php endif; ?>
    </div>
    <div class="iscms-pub-foot text-muted">
        <a class="brand-back" href="login.php"><i class="ri-arrow-left-line me-1"></i>Back to sign in</a>
    </div>
<?php
iscms_public_foot();
