<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require DENTAL_ROOT . '/app/layout.php';

if (!staff_invite_schema_ready()) {
    throw new RuntimeException('Staff account activation is not available until Version 0.5.8.3 is applied.');
}

$token = trim((string)($_GET['token'] ?? $_POST['token'] ?? ''));
$invite = null;
$error = '';
if ($token !== '' && preg_match('/^[a-f0-9]{64}$/i', $token)) {
    $stmt = db()->prepare(
        'SELECT i.id invite_id,i.user_id,i.email,i.expires_at,i.used_at,u.name,u.status,r.name role_name '
        . 'FROM `' . table('staff_account_invites') . '` i '
        . 'JOIN `' . table('users') . '` u ON u.id=i.user_id '
        . 'JOIN `' . table('roles') . '` r ON r.id=u.role_id '
        . 'WHERE i.token_hash=? AND i.used_at IS NULL AND i.expires_at>NOW() LIMIT 1'
    );
    $stmt->execute([hash('sha256', $token)]);
    $invite = $stmt->fetch() ?: null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $invite) {
    try {
        verify_csrf();
        $password = (string)($_POST['password'] ?? '');
        $confirmation = (string)($_POST['password_confirmation'] ?? '');
        if (strlen($password) < 10) throw new RuntimeException('Use a password containing at least 10 characters.');
        if ($password !== $confirmation) throw new RuntimeException('The passwords do not match.');
        if (preg_match('/^\s|\s$/', $password)) throw new RuntimeException('The password cannot begin or end with a space.');

        $pdo = db();
        $pdo->beginTransaction();
        $lock = $pdo->prepare('SELECT id,user_id FROM `' . table('staff_account_invites') . '` WHERE id=? AND used_at IS NULL AND expires_at>NOW() FOR UPDATE');
        $lock->execute([(int)$invite['invite_id']]);
        $current = $lock->fetch();
        if (!$current) throw new RuntimeException('This setup link has expired or has already been used.');
        $updateUser = $pdo->prepare('UPDATE `' . table('users') . '` SET password_hash=?,email_verified_at=NOW(),must_change_password=0,updated_at=NOW() WHERE id=? AND status="active"');
        $updateUser->execute([password_hash($password, PASSWORD_DEFAULT), (int)$invite['user_id']]);
        if ($updateUser->rowCount() < 1) throw new RuntimeException('This account is not active. Ask the clinic administrator to review it.');
        $pdo->prepare('UPDATE `' . table('staff_account_invites') . '` SET used_at=NOW(),updated_at=NOW() WHERE id=?')->execute([(int)$invite['invite_id']]);
        $pdo->prepare('UPDATE `' . table('staff_account_invites') . '` SET expires_at=NOW(),updated_at=NOW() WHERE user_id=? AND id<>? AND used_at IS NULL')->execute([(int)$invite['user_id'],(int)$invite['invite_id']]);
        $pdo->commit();
        audit('staff_account_activated', 'user', (int)$invite['user_id'], ['email' => (string)$invite['email']]);
        flash('success', 'Your account is active. Sign in using the password you created.');
        header('Location: login.php');
        exit;
    } catch (Throwable $exception) {
        if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) $pdo->rollBack();
        $error = $exception->getMessage();
    }
}

$brand = branding_profile();
?><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Activate staff account · <?=e((string)$brand['name'])?></title>
    <link rel="stylesheet" href="public/assets/css/app.css?v=<?=e(app_release_version())?>">
    <style>:root{--primary:<?=e((string)$brand['primary'])?>;--primary2:<?=e((string)$brand['secondary'])?>}</style>
</head>
<body class="public-page">
<main class="login-shell">
    <section class="login-card account-activation-card">
        <a class="brand" href="index.php"><?=brand_mark($brand)?><span><?=e((string)$brand['name'])?></span></a>
        <?php if (!$invite): ?>
            <h1>Setup link unavailable</h1>
            <div class="flash error">This staff-account link is invalid, expired, or already used.</div>
            <p>Ask the clinic administrator to open Staff Accounts &amp; Roles and send a new setup link.</p>
            <a class="btn primary" href="login.php">Staff login</a>
        <?php else: ?>
            <span class="eyebrow">Secure account setup</span>
            <h1>Welcome, <?=e((string)$invite['name'])?></h1>
            <p>Create a password for <strong><?=e((string)$invite['email'])?></strong>. Your assigned role is <?=e((string)$invite['role_name'])?>.</p>
            <?php if ($error !== ''): ?><div class="flash error"><?=e($error)?></div><?php endif; ?>
            <form method="post" class="form-grid">
                <input type="hidden" name="csrf" value="<?=e(csrf_token())?>">
                <input type="hidden" name="token" value="<?=e($token)?>">
                <label class="wide">New password<input type="password" name="password" minlength="10" autocomplete="new-password" required><small>Use at least 10 characters.</small></label>
                <label class="wide">Confirm password<input type="password" name="password_confirmation" minlength="10" autocomplete="new-password" required></label>
                <button class="btn primary" type="submit">Activate account</button>
            </form>
        <?php endif; ?>
    </section>
</main>
</body>
</html>
