<?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\Documents\DocumentRepository;
use Throwable;

final class DocumentController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin(); Permission::require('axiom.documents.view'); $repo=new DocumentRepository();
        $id=max(0,(int)($_GET['document']??0));$q=trim((string)($_GET['q']??''));$category=max(0,(int)($_GET['category']??0));
        $this->view('axiom_documents/index',[
            'pageTitle'=>'AXIOM Document Engine','dashboard'=>$repo->dashboard(),'categories'=>$repo->categories(),'objects'=>$repo->objects(),'documents'=>$repo->documents($q,$category),
            'selectedDocument'=>$id?$repo->document($id):null,'versions'=>$id?$repo->versions($id):[],'links'=>$id?$repo->links($id):[],'signatures'=>$id?$repo->signatures($id):[],'templates'=>$repo->templates(),
            'query'=>$q,'categoryFilter'=>$category,'canManage'=>Permission::can('axiom.documents.manage'),'canSign'=>Permission::can('axiom.documents.sign'),
            'flashSuccess'=>$_SESSION['axiom_documents_success']??null,'flashError'=>$_SESSION['axiom_documents_error']??null,
        ]);unset($_SESSION['axiom_documents_success'],$_SESSION['axiom_documents_error']);
    }
    public function upload():void{$this->run('axiom.documents.manage',fn(DocumentRepository $r)=>$r->upload($_POST,$_FILES['document_file']??[],$this->userId()),'Document ajouté.');}
    public function addVersion():void{$id=(int)($_POST['document_id']??0);$this->run('axiom.documents.manage',fn(DocumentRepository $r)=>$r->addVersion($id,$_FILES['document_file']??[],trim((string)($_POST['notes']??'')),$this->userId()),'Nouvelle version ajoutée.',$id);}
    public function saveCategory():void{$this->run('axiom.documents.manage',fn(DocumentRepository $r)=>$r->saveCategory($_POST),'Catégorie enregistrée.');}
    public function link():void{$id=(int)($_POST['document_id']??0);$this->run('axiom.documents.manage',function(DocumentRepository $r)use($id){$r->link($id,(string)($_POST['object_uuid']??''),(string)($_POST['link_role']??'attachment'),$this->userId());},'Document rattaché à l’objet.',$id);}
    public function requestSignature():void{$id=(int)($_POST['document_id']??0);$this->run('axiom.documents.sign',fn(DocumentRepository $r)=>$r->requestSignature($_POST,$this->userId()),'Demande de signature créée.',$id);}
    public function markSigned():void{$id=(int)($_POST['document_id']??0);$sid=(int)($_POST['signature_id']??0);$this->run('axiom.documents.sign',function(DocumentRepository $r)use($sid){$r->markSigned($sid,$this->userId());},'Signature validée.',$id);}
    public function saveTemplate():void{$this->run('axiom.documents.manage',fn(DocumentRepository $r)=>$r->saveTemplate($_POST,$this->userId()),'Modèle enregistré.');}
    public function archive():void{$id=(int)($_POST['document_id']??0);$this->run('axiom.documents.manage',function(DocumentRepository $r)use($id){$r->archive($id,$this->userId());},'Document archivé.');}
    public function download():void
    {
        Auth::requireLogin();Permission::require('axiom.documents.view');$row=(new DocumentRepository())->versionForDownload((int)($_GET['version']??0));
        if(!$row||!is_file($row['absolute_path'])){http_response_code(404);echo 'Fichier introuvable.';return;}
        header('Content-Type: '.$row['mime_type']);header('Content-Length: '.filesize($row['absolute_path']));header('Content-Disposition: attachment; filename="'.str_replace('"','',basename($row['original_name'])).'"');header('X-Content-Type-Options: nosniff');readfile($row['absolute_path']);exit;
    }
    private function run(string $permission,callable $action,string $success,int $documentId=0):void{Auth::requireLogin();Permission::require($permission);Csrf::verify($_POST['_csrf']??null);try{$result=$action(new DocumentRepository());if(is_int($result)&&$documentId===0&&str_contains($success,'Document ajouté'))$documentId=$result;$_SESSION['axiom_documents_success']=$success;}catch(Throwable $e){$_SESSION['axiom_documents_error']=$e->getMessage();}$url='/administration/axiom/documents';if($documentId>0)$url.='?document='.$documentId;$this->redirect($url);}
    private function userId():?int{return isset($_SESSION['user_id'])?(int)$_SESSION['user_id']:null;}
}
