<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Core\{Auth,Controller,Csrf,Permission};
use App\Services\AdminTrashService;

final class AdminTrashController extends Controller
{
    private function org():int{return (int)(Auth::user()['organisation_id']??1);}
    private function admin():void{Auth::requireLogin();if(!Permission::isAdmin()){$this->deny();}}
    private function super():void{Auth::requireLogin();if(!Permission::isSuperAdmin()){$this->deny();}}
    private function deny():void{http_response_code(403);exit('Accès réservé à l’administration.');}
    public function index():void{$this->admin();$this->view('admin/trash',['pageTitle'=>'Corbeille','groups'=>AdminTrashService::grouped($this->org()),'superAdmin'=>Permission::isSuperAdmin()]);}
    public function archive():void{Auth::requireLogin();$type=(string)($_POST['entity_type']??'');$required=['client'=>'clients.archive','family'=>'familles.archive','invoice'=>'facturation.archive','slot'=>'planning_slots.archive'][$type]??'';if($required===''||(!Permission::can($required)&&!Permission::isAdmin()))$this->deny();Csrf::verify($_POST['_csrf']??null);try{AdminTrashService::archive($type,(int)($_POST['entity_id']??0),$this->org(),(int)Auth::id(),(string)($_POST['entity_label']??''),(string)($_POST['reason']??''));$_SESSION['success']='Élément archivé et placé dans la corbeille.';}catch(\Throwable$e){$_SESSION['error']=$e->getMessage();}$this->redirect((string)($_POST['return_to']??'/administration/corbeille'));}
    public function restore():void{$this->admin();Csrf::verify($_POST['_csrf']??null);try{AdminTrashService::restore((int)($_POST['trash_id']??0),$this->org(),(int)Auth::id());$_SESSION['success']='Élément restauré.';}catch(\Throwable$e){$_SESSION['error']=$e->getMessage();}$this->redirect('/administration/corbeille');}
    public function purge():void{$this->super();Csrf::verify($_POST['_csrf']??null);try{AdminTrashService::purge((int)($_POST['trash_id']??0),$this->org(),(int)Auth::id());$_SESSION['success']='Élément supprimé définitivement de la base.';}catch(\Throwable$e){$_SESSION['error']=$e->getMessage();}$this->redirect('/administration/corbeille');}
}
