<?php
declare(strict_types=1);

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

function triptale_ensure_main_admin_transfers_table(): void
{
    db()->exec('CREATE TABLE IF NOT EXISTS ' . table('main_admin_transfers') . ' (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        current_admin_id BIGINT UNSIGNED NOT NULL,
        target_user_id BIGINT UNSIGNED NOT NULL,
        token_hash CHAR(64) NOT NULL,
        expires_at DATETIME NOT NULL,
        confirmed_at DATETIME NULL,
        cancelled_at DATETIME NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY idx_main_admin_transfer_current (current_admin_id),
        KEY idx_main_admin_transfer_target (target_user_id),
        KEY idx_main_admin_transfer_expiry (expires_at),
        FOREIGN KEY (current_admin_id) REFERENCES ' . table('users') . '(id) ON DELETE CASCADE,
        FOREIGN KEY (target_user_id) REFERENCES ' . table('users') . '(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');
}

$user = require_login();
if (($user['role'] ?? '') !== 'main_admin') {
    http_response_code(403);
    exit(t('main_admin_transfer.error_access'));
}

try {
    triptale_ensure_main_admin_transfers_table();
} catch (Throwable $exception) {
    http_response_code(500);
    exit(t('main_admin_transfer.error_structure'));
}

$error = null;
$sent = isset($_GET['sent']);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $targetId = filter_input(INPUT_POST, 'target_id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
    $confirmed = (string)($_POST['confirmed'] ?? '') === '1';
    if (!$targetId || !$confirmed) {
        $error = t('main_admin_transfer.error_confirmation');
    } elseif (!triptale_mail_is_configured(triptale_mail_settings())) {
        $error = t('main_admin_transfer.error_mail_config');
    } else {
        try {
            $pdo = db();
            $pdo->beginTransaction();
            $target = $pdo->prepare('SELECT id,first_name,email,preferred_language FROM ' . table('users') . " WHERE id=:id AND role='admin' AND status='active' AND deleted_at IS NULL FOR UPDATE");
            $target->execute([':id' => $targetId]);
            $targetUser = $target->fetch();
            if (!$targetUser) {
                throw new RuntimeException(t('main_admin_transfer.error_target'));
            }
            $current = $pdo->prepare('SELECT id FROM ' . table('users') . " WHERE id=:id AND role='main_admin' AND deleted_at IS NULL FOR UPDATE");
            $current->execute([':id' => $user['id']]);
            if (!$current->fetchColumn()) {
                throw new RuntimeException(t('main_admin_transfer.error_current'));
            }
            $token = bin2hex(random_bytes(32));
            $pdo->prepare('UPDATE ' . table('main_admin_transfers') . ' SET cancelled_at=NOW() WHERE confirmed_at IS NULL AND cancelled_at IS NULL AND (current_admin_id=:current OR target_user_id=:target)')->execute([':current' => $user['id'], ':target' => $targetId]);
            $insert = $pdo->prepare('INSERT INTO ' . table('main_admin_transfers') . ' (current_admin_id,target_user_id,token_hash,expires_at) VALUES (:current,:target,:token_hash,DATE_ADD(NOW(),INTERVAL 24 HOUR))');
            $insert->execute([':current' => $user['id'], ':target' => $targetId, ':token_hash' => hash('sha256', $token)]);
            $url = triptale_public_url('/main-admin-transfer-confirm.php?id=' . (int)$pdo->lastInsertId() . '&token=' . $token);
            $mailLanguage = (string)($targetUser['preferred_language'] ?? 'de');
            $subject = t_in_language('main_admin_transfer.mail_subject', $mailLanguage);
            $body = str_replace(['{name}','{url}','\\n'], [(string)$targetUser['first_name'], $url, PHP_EOL], t_in_language('main_admin_transfer.mail_body', $mailLanguage));
            if (!triptale_send_mail((string)$targetUser['email'], $subject, $body)) {
                throw new RuntimeException(triptale_mail_failure_message('main_admin_transfer.error_mail'));
            }
            $pdo->commit();
            header('Location: /main-admin-transfer.php?sent=1');
            exit;
        } catch (Throwable $exception) {
            if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) { $pdo->rollBack(); }
            $error = $exception instanceof RuntimeException ? $exception->getMessage() : t('main_admin_transfer.error_save');
        }
    }
}

$admins = db()->query('SELECT id, first_name, last_name, email FROM ' . table('users') . " WHERE role='admin' AND status='active' AND deleted_at IS NULL ORDER BY last_name, first_name")->fetchAll();
?>
<!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.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:680px;margin:auto;background:#fff;padding:28px;border-radius:14px;box-shadow:0 4px 18px #0001}.button,button{display:inline-block;padding:10px 13px;background:#126e82;color:#fff;border:0;border-radius:7px;text-decoration:none;font:inherit;font-weight:700;cursor:pointer}.back{background:#e3ebee;color:#126e82}.danger{background:#9d2d2d;margin-top:20px}.notice,.error,.success{padding:13px;border-radius:8px}.notice{background:#eef5f8;color:#28556d}.success{background:#e6f5e9;color:#1d6831}.error{background:#ffe6e3;color:#8b2424}label{display:block;margin-top:18px;font-weight:700}select{box-sizing:border-box;width:100%;padding:11px;margin-top:6px;border:1px solid #b9c1c8;border-radius:7px;font:inherit}.confirm{display:flex;gap:9px;align-items:flex-start;font-weight:400}.confirm input{margin-top:4px}@media(max-width:600px){body{padding:12px}main{padding:16px}.danger{width:100%}}</style></head>
<body><main><a class="button back" href="/profile.php"><?= htmlspecialchars(t('main_admin_transfer.back'), ENT_QUOTES, 'UTF-8') ?></a><h1><?= htmlspecialchars(t('main_admin_transfer.title'), ENT_QUOTES, 'UTF-8') ?></h1><p class="notice"><?= htmlspecialchars(t('main_admin_transfer.intro'), ENT_QUOTES, 'UTF-8') ?></p><?php if ($sent): ?><p class="success"><?= htmlspecialchars(t('main_admin_transfer.sent'), ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?><?php if ($error): ?><p class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?><?php if (!$admins): ?><p class="notice"><?= htmlspecialchars(t('main_admin_transfer.none'), ENT_QUOTES, 'UTF-8') ?></p><?php else: ?><form method="post" onsubmit="return confirm(<?= json_encode(t('main_admin_transfer.confirm_dialog'), JSON_UNESCAPED_UNICODE) ?>)"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><label><?= htmlspecialchars(t('main_admin_transfer.select'), ENT_QUOTES, 'UTF-8') ?><select name="target_id" required><option value=""><?= htmlspecialchars(t('main_admin_transfer.placeholder'), ENT_QUOTES, 'UTF-8') ?></option><?php foreach ($admins as $admin): ?><option value="<?= (int)$admin['id'] ?>"><?= htmlspecialchars($admin['first_name'] . ' ' . $admin['last_name'] . ' · ' . $admin['email'], ENT_QUOTES, 'UTF-8') ?></option><?php endforeach; ?></select></label><label class="confirm"><input name="confirmed" value="1" type="checkbox" required><span><?= htmlspecialchars(t('main_admin_transfer.confirmation'), ENT_QUOTES, 'UTF-8') ?></span></label><button class="danger" type="submit"><?= htmlspecialchars(t('main_admin_transfer.submit'), ENT_QUOTES, 'UTF-8') ?></button></form><?php endif; ?></main></body></html>
