<?php

declare(strict_types=1);

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

$config = require __DIR__ . '/../config/config.php';

auth_start_session();

$secret = 'CHANGE_ME_RESET_KEY';

$providedKey = (string)($_GET['key'] ?? '');

$remoteAddr = (string)($_SERVER['REMOTE_ADDR'] ?? '');
$isLocal = in_array($remoteAddr, ['127.0.0.1', '::1'], true);

$title = 'Reset Passwords';

$error = '';
$done = false;
$newPassword = '';
$updatedUsers = 0;

if (!$isLocal && ($providedKey === '' || !hash_equals($secret, $providedKey))) {
    http_response_code(403);
    $error = 'Forbidden';
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $newPassword = (string)($_POST['new_password'] ?? '');

    if ($newPassword === '') {
        $newPassword = 'Pest@12345';
    }

    try {
        $pdo = Database::pdo();
        $pdo->beginTransaction();

        $hash = password_hash($newPassword, PASSWORD_BCRYPT);

        $stmt = $pdo->prepare('UPDATE users SET password_hash = :hash, updated_at = CURRENT_TIMESTAMP');
        $stmt->execute(['hash' => $hash]);
        $updatedUsers = $stmt->rowCount();

        $pdo->commit();
        $done = true;

        $_SESSION['last_reset_password'] = $newPassword;

        if (version_compare(PHP_VERSION, '7.3.0', '>=')) {
            setcookie('last_reset_password', $newPassword, [
                'expires' => time() + 3600,
                'path' => '/pest/',
                'secure' => false,
                'httponly' => false,
                'samesite' => 'Lax',
            ]);
        } else {
            setcookie('last_reset_password', $newPassword, time() + 3600, '/pest/');
        }
    } catch (Throwable $e) {
        if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $error = $e->getMessage();
    }
}

ob_start();
?>
<div class="mx-auto max-w-xl space-y-6">
    <div class="rounded-xl border bg-white p-6">
        <h1 class="text-xl font-semibold">Reset All Passwords</h1>
        <p class="mt-1 text-sm text-slate-600">This will reset <span class="font-medium">all</span> passwords in <span class="font-medium">users</span>.</p>

        <?php if ($error !== ''): ?>
            <div class="mt-4 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                <?= e($error) ?>
            </div>
        <?php endif; ?>

        <?php if ($done): ?>
            <div class="mt-4 rounded-lg border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-800">
                <div class="font-medium">Done</div>
                <div class="mt-1">Updated users: <span class="font-medium"><?= e((string)$updatedUsers) ?></span></div>
                <div class="mt-1">New password: <span class="font-mono font-semibold"><?= e($newPassword) ?></span></div>
            </div>
        <?php endif; ?>

        <?php if ($isLocal || ($providedKey !== '' && hash_equals($secret, $providedKey))): ?>
            <form class="mt-6 space-y-4" method="post" action="">
                <div>
                    <label class="block text-sm font-medium" for="new_password">New password (optional)</label>
                    <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900" id="new_password" name="new_password" type="text" placeholder="Leave empty to use Pest@12345">
                </div>
                <button class="w-full rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-500" type="submit">Reset passwords</button>
            </form>
        <?php endif; ?>
    </div>

    <div class="rounded-xl border bg-white p-6 text-sm text-slate-600">
        <div class="font-medium text-slate-900">Important</div>
        <div class="mt-2">After using this page, delete <span class="font-mono">public/reset_pws.php</span> or change the key.</div>
    </div>
</div>
<?php
$content = ob_get_clean();
require __DIR__ . '/../includes/layout.php';
