<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Database;
use App\Core\Permission;
use App\Core\Router;

/**
 * Developer / Test Admin — View-as-User feature.
 *
 * Only accounts with is_dev_admin = 1 in superadmins can access these routes.
 * Impersonation is 100% session-based; nothing is written to the DB.
 * All POST actions are blocked while impersonating (Permission::requireLogin enforces this).
 */
class DevAdminController
{
    // ── Guard: dev admin only ────────────────────────────────────────────────

    private function requireDevAdmin(): array
    {
        $user = Auth::currentUser();
        if (!$user) { Router::redirect('/login'); }
        if (Auth::isImpersonating()) {
            http_response_code(403); echo 'Not available in view mode.'; exit;
        }
        if (empty($user['is_super_admin'])) {
            http_response_code(403); echo 'Super Admin access required.'; exit;
        }
        return $user;
    }

    // ── User picker page ─────────────────────────────────────────────────────

    public function picker(): void
    {
        $admin = $this->requireDevAdmin();
        $db    = Database::connection();

        // Load all managers + employees for the picker list
        $managers = $db->query(
            "SELECT id, name, username, email, 'manager' AS user_type,
                    (SELECT r.name FROM user_roles ur JOIN roles r ON r.id=ur.role_id
                     WHERE ur.user_type='manager' AND ur.user_id=managers.id LIMIT 1) AS role_name
             FROM managers WHERE is_active=1 ORDER BY name"
        )->fetchAll(\PDO::FETCH_ASSOC);

        $employees = $db->query(
            "SELECT id, name, NULL AS username, NULL AS email, 'employee' AS user_type,
                    (SELECT r.name FROM user_roles ur JOIN roles r ON r.id=ur.role_id
                     WHERE ur.user_type='employee' AND ur.user_id=employees.id LIMIT 1) AS role_name
             FROM employees ORDER BY name"
        )->fetchAll(\PDO::FETCH_ASSOC);

        $superadmins = $db->query(
            "SELECT id, full_name AS name, username, email, 'superadmin' AS user_type, 'Super Admin' AS role_name
             FROM superadmins WHERE is_dev_admin=0 ORDER BY full_name"
        )->fetchAll(\PDO::FETCH_ASSOC);

        $allUsers = array_merge($superadmins, $managers, $employees);

        require __DIR__ . '/../Views/dev/picker.php';
    }

    // ── Start impersonation ──────────────────────────────────────────────────

    public function start(): void
    {
        $this->requireDevAdmin();

        $targetType = $_POST['user_type'] ?? '';
        $targetId   = (int)($_POST['user_id'] ?? 0);

        if (!in_array($targetType, ['superadmin','manager','employee'], true) || $targetId < 1) {
            $_SESSION['dev_flash'] = 'Invalid user selection.';
            Router::redirect('/dev/view-as');
        }

        if (!Auth::impersonateStart($targetType, $targetId)) {
            $_SESSION['dev_flash'] = 'Could not start view mode.';
            Router::redirect('/dev/view-as');
        }

        // Send to workspace (covers managers/employees) or admin (for superadmin targets)
        $dest = $targetType === 'superadmin' ? '/admin/users' : '/workspace';
        Router::redirect($dest);
    }

    // ── Stop impersonation ───────────────────────────────────────────────────

    public function stop(): void
    {
        Auth::impersonateStop();
        Router::redirect('/dev/view-as');
    }
}
