<?php
namespace App\Models;
use App\Core\Database;
use PDO;
final class ProfessorConsent
{
 public static function professor(int $id):?array{$s=Database::connection()->prepare("SELECT id,organisation_id,code_professeur,nom,prenom,email,rgpd_accepte,droit_image FROM professeurs WHERE id=? AND deleted_at IS NULL");$s->execute([$id]);return$s->fetch()?:null;}
 public static function all(int $professorId):array{$s=Database::connection()->prepare("SELECT d.*,(SELECT MAX(t.expires_at) FROM professeur_consentement_tokens t WHERE t.document_id=d.id AND t.revoked_at IS NULL AND t.used_at IS NULL) token_expires_at,CASE WHEN d.statut IN('signe','importe') THEN d.statut WHEN EXISTS(SELECT 1 FROM professeur_consentement_tokens tx WHERE tx.document_id=d.id AND tx.revoked_at IS NULL AND tx.used_at IS NULL AND tx.expires_at<NOW()) THEN 'expire' ELSE d.statut END display_status FROM professeur_consentements d WHERE d.professeur_id=? AND d.deleted_at IS NULL ORDER BY d.id DESC");$s->execute([$professorId]);return$s->fetchAll(PDO::FETCH_ASSOC)?:[];}
 public static function find(int $id):?array{$s=Database::connection()->prepare("SELECT d.*,p.nom,p.prenom,p.email FROM professeur_consentements d JOIN professeurs p ON p.id=d.professeur_id WHERE d.id=? AND d.deleted_at IS NULL");$s->execute([$id]);return$s->fetch()?:null;}
 public static function create(array $d):int{$s=Database::connection()->prepare("INSERT INTO professeur_consentements(organisation_id,professeur_id,type_document,annee_scolaire,version_document,statut,choix_json,email_destinataire,created_by) VALUES(:organisation_id,:professeur_id,:type_document,:annee_scolaire,'1.0','a_preparer',:choix_json,:email_destinataire,:created_by)");$s->execute($d);return(int)Database::connection()->lastInsertId();}
 public static function createToken(int$id,string$email,string$token,string$expires):void{$pdo=Database::connection();$pdo->prepare("UPDATE professeur_consentement_tokens SET revoked_at=NOW() WHERE document_id=? AND used_at IS NULL AND revoked_at IS NULL")->execute([$id]);$pdo->prepare("INSERT INTO professeur_consentement_tokens(document_id,token_hash,email_destinataire,expires_at) VALUES(?,?,?,?)")->execute([$id,hash('sha256',$token),$email,$expires]);$pdo->prepare("UPDATE professeur_consentements SET statut='lien_genere',email_destinataire=?,envoye_at=NOW(),updated_at=NOW() WHERE id=?")->execute([$email,$id]);}
 public static function emailResult(int$id,bool$ok,?string$error):void{Database::connection()->prepare("UPDATE professeur_consentements SET statut=?,email_status=?,email_error=?,updated_at=NOW() WHERE id=?")->execute([$ok?'envoye':'echec_envoi',$ok?'sent':'failed',$error,$id]);}
 public static function byToken(string$token):?array{$s=Database::connection()->prepare("SELECT d.*,p.nom,p.prenom,t.id token_id,t.expires_at,t.used_at,t.viewed_at,t.revoked_at FROM professeur_consentement_tokens t JOIN professeur_consentements d ON d.id=t.document_id JOIN professeurs p ON p.id=d.professeur_id WHERE t.token_hash=? LIMIT 1");$s->execute([hash('sha256',$token)]);$d=$s->fetch();if(!$d||$d['used_at']||$d['revoked_at']||strtotime((string)$d['expires_at'])<time())return null;if(!$d['viewed_at']){Database::connection()->prepare("UPDATE professeur_consentement_tokens SET viewed_at=NOW() WHERE id=?")->execute([$d['token_id']]);Database::connection()->prepare("UPDATE professeur_consentements SET statut='consulte',consulte_at=NOW(),updated_at=NOW() WHERE id=? AND statut IN('lien_genere','envoye')")->execute([$d['id']]);}return$d;}
 public static function sign(int$id,int$tokenId,string$name,string$signature,string$mode):void{$pdo=Database::connection();$pdo->beginTransaction();try{$pdo->prepare("UPDATE professeur_consentements SET statut='signe',nom_signataire=?,signature_data=?,mode_signature=?,signe_at=NOW(),updated_at=NOW() WHERE id=?")->execute([$name,$signature,$mode,$id]);if($tokenId)$pdo->prepare("UPDATE professeur_consentement_tokens SET used_at=NOW() WHERE id=?")->execute([$tokenId]);self::updateProfessorStatus($pdo,$id);$pdo->commit();}catch(\Throwable$e){$pdo->rollBack();throw$e;}}
 public static function import(int$id,string$path,string$checksum):void{$pdo=Database::connection();$pdo->beginTransaction();try{$pdo->prepare("UPDATE professeur_consentements SET statut='importe',mode_signature='document_importe',fichier_signe=?,checksum_sha256=?,signe_at=NOW(),updated_at=NOW() WHERE id=?")->execute([$path,$checksum,$id]);self::updateProfessorStatus($pdo,$id);$pdo->commit();}catch(\Throwable$e){$pdo->rollBack();throw$e;}}
 private static function updateProfessorStatus(PDO$pdo,int$id):void{$s=$pdo->prepare("SELECT professeur_id,type_document,choix_json FROM professeur_consentements WHERE id=?");$s->execute([$id]);$d=$s->fetch();if(!$d)return;if($d['type_document']==='rgpd')$pdo->prepare("UPDATE professeurs SET rgpd_accepte=1,updated_at=NOW() WHERE id=?")->execute([$d['professeur_id']]);else{$choices=json_decode((string)$d['choix_json'],true)?:[];$decision=($choices['decision']??'accorde')==='refuse'?'refuse':'accorde';$pdo->prepare("UPDATE professeurs SET droit_image=?,updated_at=NOW() WHERE id=?")->execute([$decision,$d['professeur_id']]);}}
}
