<?php
declare(strict_types=1);

require_once __DIR__ . '/app/Helpers/bootstrap.php';

$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]])
    ?: filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$token = (string)($_POST['token'] ?? $_GET['token'] ?? '');
$record = null;
$error = null;

if ($id && preg_match('/^[a-f0-9]{64}$/', $token)) {
    try {
        $query = db()->prepare('SELECT mt.id,mt.current_admin_id,mt.target_user_id,mt.token_hash,u.first_name,u.preferred_language FROM ' . table('main_admin_transfers') . ' mt JOIN ' . table('users') . " u ON u.id=mt.target_user_id WHERE mt.id=:id AND mt.confirmed_at IS NULL AND mt.cancelled_at IS NULL AND mt.expires_at>NOW() AND u.role='admin' AND u.status='active' AND u.deleted_at IS NULL");
        $query->execute([':id' => $id]);
        $candidate = $query->fetch();
        if ($candidate && hash_equals((string)$candidate['token_hash'], hash('sha256', $token))) {
            $record = $candidate;
            start_session();
            if (array_key_exists((string)($candidate['preferred_language'] ?? ''), triptale_available_languages())) {
                $_SESSION['language'] = (string)$candidate['preferred_language'];
            }
        }
    } catch (Throwable $exception) {
        $record = null;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    if (!$record) {
        $error = t('main_admin_transfer_confirm.error_invalid');
    } else {
        try {
            $pdo = db();
            $pdo->beginTransaction();
            $locked = $pdo->prepare('SELECT id,current_admin_id,target_user_id,token_hash FROM ' . table('main_admin_transfers') . ' WHERE id=:id AND confirmed_at IS NULL AND cancelled_at IS NULL AND expires_at>NOW() FOR UPDATE');
            $locked->execute([':id' => $id]);
            $pending = $locked->fetch();
            if (!$pending || !hash_equals((string)$pending['token_hash'], hash('sha256', $token))) {
                throw new RuntimeException(t('main_admin_transfer_confirm.error_invalid'));
            }
            $current = $pdo->prepare('SELECT id FROM ' . table('users') . " WHERE id=:id AND role='main_admin' AND status='active' AND deleted_at IS NULL FOR UPDATE");
            $current->execute([':id' => $pending['current_admin_id']]);
            $target = $pdo->prepare('SELECT id FROM ' . table('users') . " WHERE id=:id AND role='admin' AND status='active' AND deleted_at IS NULL FOR UPDATE");
            $target->execute([':id' => $pending['target_user_id']]);
            if (!$current->fetchColumn() || !$target->fetchColumn()) {
                throw new RuntimeException(t('main_admin_transfer_confirm.error_changed'));
            }
            $pdo->prepare('UPDATE ' . table('users') . " SET role='admin',password_hash=NULL WHERE id=:id")->execute([':id' => $pending['current_admin_id']]);
            $pdo->prepare('UPDATE ' . table('users') . " SET role='main_admin',password_hash=NULL WHERE id=:id")->execute([':id' => $pending['target_user_id']]);
            $pdo->prepare('UPDATE ' . table('main_admin_transfers') . ' SET confirmed_at=NOW() WHERE id=:id')->execute([':id' => $id]);
            $pdo->prepare('UPDATE ' . table('main_admin_transfers') . ' SET cancelled_at=NOW() WHERE id<>:id AND confirmed_at IS NULL AND cancelled_at IS NULL')->execute([':id' => $id]);
            $pdo->commit();
            start_session();
            session_regenerate_id(true);
            $_SESSION['user_id'] = (int)$pending['target_user_id'];
            $_SESSION['login_expires_at'] = time() + (14 * 24 * 60 * 60);
            session_write_close();
            $passwordUrl = '/main-admin-password.php?transferred=1';
            if (!headers_sent()) { header('Location: ' . $passwordUrl, true, 303); }
            echo '<!doctype html><html lang="' . htmlspecialchars(language(), ENT_QUOTES, 'UTF-8') . '"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="refresh" content="0;url=' . htmlspecialchars($passwordUrl, ENT_QUOTES, 'UTF-8') . '"><title>' . htmlspecialchars(t('main_admin_password.title'), ENT_QUOTES, 'UTF-8') . '</title></head><body><p>' . htmlspecialchars(t('main_admin_transfer.success'), ENT_QUOTES, 'UTF-8') . '</p><p><a href="' . htmlspecialchars($passwordUrl, ENT_QUOTES, 'UTF-8') . '">' . htmlspecialchars(t('main_admin_password.nav'), ENT_QUOTES, 'UTF-8') . '</a></p><script>location.replace(' . json_encode($passwordUrl, JSON_UNESCAPED_SLASHES) . ');</script></body></html>';
            exit;
        } catch (Throwable $exception) {
            if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) { $pdo->rollBack(); }
            $error = $exception instanceof RuntimeException ? $exception->getMessage() : t('main_admin_transfer_confirm.error_save');
        }
    }
}

if (!$record && $error === null) { $error = t('main_admin_transfer_confirm.error_invalid'); }
?>
<!doctype html>
<html lang="<?= htmlspecialchars(language(), ENT_QUOTES, 'UTF-8') ?>">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?= htmlspecialchars(t('main_admin_transfer_confirm.title'), ENT_QUOTES, 'UTF-8') ?> · TripTale</title>
<style>body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:620px;margin:auto;background:#fff;padding:28px;border-radius:14px;box-shadow:0 4px 18px #0001}.danger{display:inline-block;padding:10px 13px;background:#9d2d2d;color:#fff;border:0;border-radius:7px;font:inherit;font-weight:700;cursor:pointer;margin-top:16px}.notice,.error{padding:13px;border-radius:8px}.notice{background:#eef5f8;color:#28556d}.error{background:#ffe6e3;color:#8b2424}@media(max-width:600px){body{padding:12px}main{padding:16px}.danger{width:100%}}</style></head>
<body><main><h1><?= htmlspecialchars(t('main_admin_transfer_confirm.title'), ENT_QUOTES, 'UTF-8') ?></h1><?php if ($error): ?><p class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p><?php else: ?><p class="notice"><?= htmlspecialchars(str_replace('{name}', (string)$record['first_name'], t('main_admin_transfer_confirm.intro')), ENT_QUOTES, 'UTF-8') ?></p><form method="post"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><input type="hidden" name="id" value="<?= (int)$id ?>"><input type="hidden" name="token" value="<?= htmlspecialchars($token, ENT_QUOTES, 'UTF-8') ?>"><button class="danger" type="submit"><?= htmlspecialchars(t('main_admin_transfer_confirm.submit'), ENT_QUOTES, 'UTF-8') ?></button></form><?php endif; ?></main></body></html>
