<?php
declare(strict_types=1);

require_once __DIR__ . '/GdprController.php';
require_once __DIR__ . '/GdprExporter.php';

/**
 * DSGVO data-export plugin (Art. 15 — Right of access by the data subject).
 *
 * Two paths to a copy of the personal data Plenvo holds:
 *   1. Global admin → /admin/users → "DSGVO-Export" button per user row.
 *      Allowed for any active user on the instance.
 *   2. Self-service → /settings → card with download button. Available
 *      only when the operator has flipped the
 *      `gdpr_user_self_export_enabled` setting and the cooldown window
 *      has elapsed for the requesting user.
 *
 * Group admins (Provider Edition) get NO export rights over their
 * group members. Each user only sees their own data; cross-tenant
 * extraction stays a global-admin operation.
 *
 * The plugin ships disabled by default and is opt-in via /admin/plugins.
 * No persistent storage of generated exports — every download is built
 * on the fly and streamed to the browser, then the temp file is removed.
 */
class GdprPlugin
{
    public function register(): void
    {
        // Admin plugin-settings page
        PluginManager::addRoute('/admin/plugins/gdpr', fn() => GdprController::adminSettings());

        // Admin-triggered export for a specific user (POST only)
        PluginManager::addDynamicRoute(
            '#^/admin/users/(\d+)/gdpr-export$#',
            fn($m) => GdprController::adminExport((int)$m[1])
        );

        // Self-service export
        PluginManager::addRoute('/settings/gdpr-export', fn() => GdprController::userExport());

        // Admin user-table action: render the export button
        PluginManager::on('admin_user_actions', function (array $u): void {
            if (!Auth::isAdmin()) return;
            ?>
            <form method="POST" action="/admin/users/<?= (int)$u['id'] ?>/gdpr-export" style="display:inline">
                <?= Helper::csrf() ?>
                <button type="submit" class="btn btn-ghost btn-xs" title="<?= Helper::e(Lang::get('gdpr_export_admin_btn_title')) ?>">
                    <?= Helper::e(Lang::get('gdpr_export_admin_btn')) ?>
                </button>
            </form>
            <?php
        });

        // User settings: render self-export card on the profile page (/settings)
        // so it sits next to the password / 2FA / delete-account cards, which
        // is where users land by default. Listening on the profile-extra hook
        // (rather than preferences-extra) means users do not have to navigate
        // into the separate /settings/preferences sub-page to find it.
        PluginManager::on('settings_profile_extra', function (mixed $ctx): void {
            if (Helper::getSetting('gdpr_user_self_export_enabled', '0') !== '1') return;
            $cooldownHours = max(1, (int)Helper::getSetting('gdpr_self_export_cooldown_hours', '24'));
            $lastTs        = self::lastSelfExportTs(Auth::id());
            $nextOk        = $lastTs === 0 ? 0 : ($lastTs + $cooldownHours * 3600);
            $waitSeconds   = max(0, $nextOk - time());
            ?>
            <div class="card">
                <div class="card-header">
                    <h2 class="card-title"><?= Helper::e(Lang::get('gdpr_self_export_card_title')) ?></h2>
                </div>
                <div class="card-body">
                    <p style="margin:0 0 14px;color:var(--text-muted);font-size:.9rem">
                        <?= Helper::e(Lang::get('gdpr_self_export_card_desc')) ?>
                    </p>
                    <?php if ($waitSeconds > 0): ?>
                        <button type="button" class="btn btn-ghost btn-sm" disabled>
                            <?= sprintf(Helper::e(Lang::get('gdpr_self_export_cooldown')), (int)ceil($waitSeconds / 3600)) ?>
                        </button>
                    <?php else: ?>
                        <form method="POST" action="/settings/gdpr-export" style="display:inline">
                            <?= Helper::csrf() ?>
                            <button type="submit" class="btn btn-primary btn-sm">
                                <?= Helper::e(Lang::get('gdpr_self_export_btn')) ?>
                            </button>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
            <?php
        });
    }

    /**
     * Look up the last `gdpr_export_self` SecurityLog timestamp for the user
     * to enforce the operator-configured cooldown window. Returns 0 when
     * the user has never run a self-export.
     */
    private static function lastSelfExportTs(?int $userId): int
    {
        if (!$userId) return 0;
        try {
            $row = Database::getInstance()->fetch(
                "SELECT created_at FROM security_events
                  WHERE event_type = 'gdpr_export_self' AND user_id = ?
                  ORDER BY created_at DESC LIMIT 1",
                [$userId]
            );
            return $row ? (int)strtotime((string)$row['created_at']) : 0;
        } catch (\Throwable) {
            return 0;
        }
    }
}
