<?php
namespace App\Models;
use App\Core\Database;

final class BackupJob {
 public static function all(): array { return Database::connection()->query("SELECT b.*,CONCAT(u.prenom,' ',u.nom) cree_par_nom FROM cda_backup_jobs b LEFT JOIN utilisateurs u ON u.id=b.cree_par ORDER BY b.created_at DESC,b.id DESC")->fetchAll(); }
 public static function create(int $userId,string $type='manuel'): int { $s=Database::connection()->prepare("INSERT INTO cda_backup_jobs(type_backup,statut,version_erp,cree_par) VALUES(:type,'en_attente',:version,:user)"); $s->execute(['type'=>$type,'version'=>is_file(BASE_PATH.'/VERSION')?trim((string)file_get_contents(BASE_PATH.'/VERSION')):'inconnue','user'=>$userId?:null]); return (int)Database::connection()->lastInsertId(); }
 public static function find(int $id): ?array { $s=Database::connection()->prepare('SELECT * FROM cda_backup_jobs WHERE id=:id LIMIT 1');$s->execute(['id'=>$id]);return $s->fetch()?:null; }
 public static function update(int $id,array $data): void { $s=Database::connection()->prepare("UPDATE cda_backup_jobs SET statut=:statut,chemin=:chemin,base_nom=:base_nom,taille_fichiers=:tf,taille_base=:tb,taille_totale=:tt,checksum_sha256=:checksum,message=:message,started_at=COALESCE(started_at,NOW()),finished_at=:finished WHERE id=:id");$s->execute(['statut'=>$data['statut'],'chemin'=>$data['chemin']??null,'base_nom'=>$data['base_nom']??null,'tf'=>$data['taille_fichiers']??0,'tb'=>$data['taille_base']??0,'tt'=>$data['taille_totale']??0,'checksum'=>$data['checksum']??null,'message'=>$data['message']??null,'finished'=>in_array($data['statut'],['succes','echec'],true)?date('Y-m-d H:i:s'):null,'id'=>$id]); }
}
