<?php
declare(strict_types=1);

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

iscms_public_session();

if (isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

$error = '';
$success = false;
$token_in = (string) ($_GET['token'] ?? $_POST['token'] ?? '');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!iscms_csrf_validate($_POST['csrf_token'] ?? null)) {
        $error = 'Invalid security token.';
    } elseif ($token_in === '') {
        $error = 'Reset link is invalid or expired.';
    } else {
        $p1 = (string) ($_POST['password'] ?? '');
        $p2 = (string) ($_POST['password_confirm'] ?? '');
        if (strlen($p1) < 8) {
            $error = 'Password must be at least 8 characters.';
        } elseif (!hash_equals($p1, $p2)) {
            $error = 'Passwords do not match.';
        } else {
            require_once __DIR__ . '/layouts/dbconn.php';
            /** @var mysqli $conn */
            if (!iscms_table_exists($conn, 'password_resets')) {
                $error = 'Password reset is not available.';
            } else {
                $th = hash('sha256', $token_in);
                $st = $conn->prepare(
                    'SELECT id, user_id FROM password_resets
                     WHERE token_hash = ? AND used_at IS NULL AND expires_at > NOW() LIMIT 1'
                );
                if ($st) {
                    $st->bind_param('s', $th);
                    $st->execute();
                    $row = $st->get_result()->fetch_assoc();
                    $st->close();
                    if (!$row) {
                        $error = 'This reset link is invalid or has expired. Request a new one.';
                    } else {
                        $rid = (string) $row['id'];
                        $uid = (string) $row['user_id'];
                        $hash = password_hash($p1, PASSWORD_DEFAULT);
                        $hasMcp = iscms_column_exists($conn, 'users', 'must_change_password');
                        $hasPca = iscms_column_exists($conn, 'users', 'password_changed_at');
                        if ($hasMcp && $hasPca) {
                            $up = $conn->prepare(
                                'UPDATE users SET password_hash = ?, must_change_password = 0,
                                 password_changed_at = NOW(), failed_logins = 0, locked_until = NULL WHERE id = ?'
                            );
                        } elseif ($hasMcp) {
                            $up = $conn->prepare(
                                'UPDATE users SET password_hash = ?, must_change_password = 0,
                                 failed_logins = 0, locked_until = NULL WHERE id = ?'
                            );
                        } else {
                            $up = $conn->prepare(
                                'UPDATE users SET password_hash = ?, failed_logins = 0, locked_until = NULL WHERE id = ?'
                            );
                        }
                        if ($up) {
                            $up->bind_param('ss', $hash, $uid);
                            if ($up->execute()) {
                                $mk = $conn->prepare('UPDATE password_resets SET used_at = NOW() WHERE id = ?');
                                if ($mk) {
                                    $mk->bind_param('s', $rid);
                                    $mk->execute();
                                    $mk->close();
                                }
                                $success = true;
                            } else {
                                $error = 'Could not update password.';
                            }
                            $up->close();
                        }
                    }
                }
            }
            if (isset($conn) && $conn instanceof mysqli) {
                $conn->close();
            }
        }
    }
}

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

iscms_public_head($pageTitle);
?>
    <div class="iscms-pub-h"><i class="ri-key-2-line me-2"></i><?= iscms_h($pageTitle) ?></div>
    <div class="iscms-pub-b">
        <?php if ($success): ?>
        <div class="alert alert-success py-2" style="font-size:.85rem">Your password was updated. You can sign in now.</div>
        <a class="btn btn-primary btn-sm w-100" href="login.php">Go to sign in</a>
        <?php elseif ($error !== ''): ?>
        <div class="alert alert-danger py-2" style="font-size:.85rem"><?= iscms_h($error) ?></div>
        <a class="brand-back" href="forgot_password.php">Request a new link</a>
        <?php elseif ($token_in === ''): ?>
        <div class="alert alert-warning py-2" style="font-size:.85rem">Missing token. Open the link from your email.</div>
        <a class="brand-back" href="forgot_password.php">Request reset</a>
        <?php else: ?>
        <p class="text-muted small mb-3">Choose a new password for your account.</p>
        <form method="post" action="reset_password.php">
            <input type="hidden" name="csrf_token" value="<?= iscms_h($csrf) ?>">
            <input type="hidden" name="token" value="<?= iscms_h($token_in) ?>">
            <div class="mb-2">
                <label class="form-label">New password</label>
                <input type="password" name="password" class="form-control form-control-sm" required minlength="8" autocomplete="new-password">
            </div>
            <div class="mb-3">
                <label class="form-label">Confirm password</label>
                <input type="password" name="password_confirm" class="form-control form-control-sm" required minlength="8" autocomplete="new-password">
            </div>
            <button type="submit" class="btn btn-primary btn-sm w-100">Save password</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>Sign in</a>
    </div>
<?php
iscms_public_foot();
