<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Permission;
use App\Core\PortalSimulation;
use App\Core\SpaceAccess;
use App\Core\Database;

final class SpaceController extends Controller
{
    private const SPACES = ['famille', 'professeur', 'direction', 'facturation', 'axiom'];

    public function index(): void
    {
        Auth::requireLogin();
        $available = $this->available();
        $requested = trim((string)($_GET['espace'] ?? ($_SESSION['axiom_space'] ?? '')));
        if (!in_array($requested, $available, true)) {
            $requested = $available[0] ?? 'direction';
        }
        $_SESSION['axiom_space'] = $requested;
        if ($requested === 'axiom') {
            PortalSimulation::clear();
        }
        if ($requested === 'professeur') {
            if (Permission::isSuperAdmin() && PortalSimulation::professorId() === null) {
                $stmt = Database::connection()->prepare(
                    "SELECT id,code_professeur,nom,prenom FROM professeurs
                     WHERE organisation_id=:organisation_id AND actif=1 AND deleted_at IS NULL
                     ORDER BY nom,prenom"
                );
                $stmt->execute(['organisation_id' => (int)(Auth::user()['organisation_id'] ?? 1)]);
                $this->view('spaces/select_professor', [
                    'pageTitle' => 'Choisir un professeur à tester',
                    'professors' => $stmt->fetchAll() ?: [],
                ]);
                return;
            }
            $this->redirect('/professeurs-pro');
            return;
        }
        if ($requested === 'famille' && Permission::isSuperAdmin() && PortalSimulation::clientId() === null) {
            $stmt = Database::connection()->prepare(
                "SELECT id,code_client,nom,prenom FROM clients
                 WHERE organisation_id=:organisation_id AND statut='actif' AND deleted_at IS NULL
                 ORDER BY nom,prenom"
            );
            $stmt->execute(['organisation_id' => (int)(Auth::user()['organisation_id'] ?? 1)]);
            $this->view('spaces/select_client', [
                'pageTitle' => 'Choisir un adhérent à tester',
                'clients' => $stmt->fetchAll() ?: [],
            ]);
            return;
        }
        $this->view('spaces/index', [
            'pageTitle' => 'Espace ' . ucfirst($requested),
            'space' => $requested,
            'availableSpaces' => $available,
        ]);
    }

    public function select(): void
    {
        Auth::requireLogin();
        Csrf::verify($_POST['_csrf'] ?? null);
        $space = trim((string)($_POST['space'] ?? ''));
        if (in_array($space, $this->available(), true)) {
            $_SESSION['axiom_space'] = $space;
        }
        $this->redirect('/espaces?espace=' . rawurlencode((string)($_SESSION['axiom_space'] ?? 'direction')));
    }

    public function simulateProfessor(): void
    {
        Auth::requireLogin();
        Permission::requireSuperAdmin();
        Csrf::verify($_POST['_csrf'] ?? null);
        if (!PortalSimulation::selectProfessor((int)($_POST['professor_id'] ?? 0))) {
            $_SESSION['error'] = 'Le professeur choisi est introuvable ou inactif.';
            $this->redirect('/espaces?espace=professeur');
            return;
        }
        $_SESSION['axiom_space'] = 'professeur';
        $this->redirect('/professeurs-pro');
    }

    public function simulateClient(): void
    {
        Auth::requireLogin();
        Permission::requireSuperAdmin();
        Csrf::verify($_POST['_csrf'] ?? null);
        if (!PortalSimulation::selectClient((int)($_POST['client_id'] ?? 0))) {
            $_SESSION['error'] = 'L’adhérent choisi est introuvable ou archivé.';
            $this->redirect('/espaces?espace=famille');
            return;
        }
        $_SESSION['axiom_space'] = 'famille';
        $this->redirect('/clients');
    }

    public function stopSimulation(): void
    {
        Auth::requireLogin();
        Permission::requireSuperAdmin();
        Csrf::verify($_POST['_csrf'] ?? null);
        PortalSimulation::clear();
        $_SESSION['axiom_space'] = 'axiom';
        $this->redirect('/espaces?espace=axiom');
    }

    private function available(): array
    {
        return SpaceAccess::available();
    }
}
