<?php

namespace App\Core;

class Permission
{
    /** Only Super Admin may pass. Redirects to login/workspace otherwise. */
    public static function requireSuperAdmin(): array
    {
        $user = Auth::currentUser();

        if (!$user) {
            Router::redirect('/login');
        }

        if (!$user['is_super_admin']) {
            http_response_code(403);
            echo 'Access denied — Super Admin only.';
            exit;
        }

        self::enforcePasswordChange();

        return $user;
    }

    /** Any authenticated user may pass. Blocks writes during impersonation. */
    public static function requireLogin(): array
    {
        $user = Auth::currentUser();
        if (!$user) {
            // If this is a modal/iframe request, show inline error instead of
            // redirecting to login (which causes "page not found" in iframes)
            if (!empty($_GET['modal']) || !empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
                http_response_code(401);
                echo '<!DOCTYPE html><html><head><link rel="stylesheet" href="/assets/css/app.css"></head><body style="padding:40px;text-align:center;background:#fff;">
                    <div style="font-size:32px;margin-bottom:16px;">🔒</div>
                    <h3 style="color:#991b1b;">Session expired</h3>
                    <p style="color:#6b7280;">Please <a href="/login" target="_top">log in again</a> to continue.</p>
                </body></html>';
                exit;
            }
            Router::redirect('/login');
        }
        self::enforcePasswordChange();
        self::blockWritesDuringImpersonation();
        return $user;
    }

    /**
     * During impersonation (View-as-User mode), all POST/PUT/DELETE requests
     * are blocked — the dev admin can only view, never write. This ensures
     * the impersonated user's data is never accidentally changed.
     */
    private static function blockWritesDuringImpersonation(): void
    {
        if (!Auth::isImpersonating()) return;
        $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
        if (in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE'], true)) {
            http_response_code(403);
            $info = Auth::impersonatorInfo();
            $exitUrl = '/dev/impersonate/stop';
            echo '<div style="font-family:sans-serif;max-width:600px;margin:80px auto;padding:32px;
                              background:#fef2f2;border:2px solid #dc2626;border-radius:16px;text-align:center;">
                    <div style="font-size:28px;margin-bottom:12px;">🔒</div>
                    <h2 style="color:#991b1b;margin:0 0 8px;">Write Blocked — View Mode Active</h2>
                    <p style="color:#7f1d1d;margin:0 0 20px;">
                      You are viewing as another user. All write actions are disabled to protect their data.
                    </p>
                    <a href="' . htmlspecialchars($exitUrl) . '"
                       style="background:#dc2626;color:#fff;padding:10px 24px;border-radius:8px;
                              text-decoration:none;font-weight:700;">
                      ← Exit View Mode
                    </a>
                  </div>';
            exit;
        }
    }

    private static function enforcePasswordChange(): void
    {
        if (!empty($_SESSION['must_change_password'])) {
            Router::redirect('/change-password');
        }
    }
}
