<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Core\Auth;use App\Core\Controller;use App\Core\Csrf;use App\Core\Permission;use App\Services\PortalAccountService;
final class PortalAccountController extends Controller{
 private function service():PortalAccountService{return new PortalAccountService();}
 public function index():void{Auth::requireLogin();Permission::require('portal.accounts.view');$q=trim((string)($_GET['q']??''));$this->view('portal_accounts/index',['pageTitle'=>'Comptes portail','accounts'=>$this->service()->accounts($q),'query'=>$q]);}
 public function resend():void{Auth::requireLogin();Permission::require('portal.accounts.manage');Csrf::verify($_POST['_csrf']??null);$ok=$this->service()->resend((int)($_POST['account_id']??0),(int)Auth::id());$_SESSION[$ok?'success':'error']=$ok?'Une nouvelle invitation a été envoyée.':'Le lien a été régénéré, mais le serveur de messagerie a refusé l’envoi.';$this->redirect('/administration/comptes-portail');}
 public function status():void{Auth::requireLogin();Permission::require('portal.accounts.manage');Csrf::verify($_POST['_csrf']??null);$this->service()->changeStatus((int)($_POST['account_id']??0),(string)($_POST['status']??''),(int)Auth::id());$_SESSION['success']='Le statut a été mis à jour et les anciennes sessions ont été invalidées.';$this->redirect('/administration/comptes-portail');}
 public function activationForm():void{$token=trim((string)($_GET['token']??''));$this->view('portal_auth/activate',['pageTitle'=>'Activation de votre espace','hideNavigation'=>true,'token'=>$token,'account'=>$this->service()->validateToken($token)]);}
 public function activate():void{Csrf::verify($_POST['_csrf']??null);$p=(string)($_POST['password']??'');if($p!==(string)($_POST['password_confirmation']??'')){$_SESSION['error']='La confirmation ne correspond pas.';$this->redirect('/portail/activation?token='.rawurlencode((string)($_POST['token']??'')));}try{$this->service()->activate((string)($_POST['token']??''),$p);$_SESSION['success']='Votre espace est activé. Vous pouvez vous connecter.';$this->redirect('/login');}catch(\Throwable $e){$_SESSION['error']=$e->getMessage();$this->redirect('/portail/activation?token='.rawurlencode((string)($_POST['token']??'')));}}
}
