<?php
// controllers/ProjetsController.php
require_once __DIR__ . '/../models/Projet.php';
require_once __DIR__ . '/../models/ProjetCompteRendu.php';
require_once __DIR__ . '/../models/ProjetDocumentLink.php';
require_once __DIR__ . '/../models/Client.php';
require_once __DIR__ . '/../models/Database.php';
require_once __DIR__ . '/../models/Devis.php';
require_once __DIR__ . '/../models/Facture.php';
require_once __DIR__ . '/../models/RdvModel.php';
require_once __DIR__ . '/../models/Email.php';
require_once __DIR__ . '/../models/EmailAttachment.php';
require_once __DIR__ . '/../models/ReglagesEntreprise.php';
require_once __DIR__ . '/../lib/PdfBootstrap.php';
class ProjetsController {
private $projetModel;
private $projetCompteRenduModel;
private $projectLinkModel;
private $clientModel;
private $reglagesEntrepriseModel;
public function __construct() {
$this->projetModel = new Projet();
$this->projetCompteRenduModel = new ProjetCompteRendu();
$this->projectLinkModel = new ProjetDocumentLink();
$this->clientModel = new Client();
$this->reglagesEntrepriseModel = new ReglagesEntreprise(Database::getInstance()->getConnection());
}
public function handle() {
$action = $_GET['action'] ?? '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if ($action === 'add' || $action === 'save') {
$this->saveFromPost();
return;
}
if ($action === 'save-report') {
$this->saveCompteRendu();
return;
}
}
if ($action === 'view' && isset($_GET['id'])) {
$this->view((int) $_GET['id']);
return;
}
if ($action === 'edit' && isset($_GET['id'])) {
$this->edit((int) $_GET['id']);
return;
}
if ($action === 'delete' && isset($_GET['id'])) {
$this->delete((int) $_GET['id']);
return;
}
if ($action === 'detach-document' && isset($_GET['id'])) {
$this->detachDocument((int) $_GET['id']);
return;
}
$this->list();
}
private function list() {
$projets = $this->projetModel->getAll();
$clients = $this->clientModel->getAll();
require __DIR__ . '/../views/projets.php';
}
private function view(int $id): void {
$projet = $this->projetModel->getById($id);
if (!$projet) {
$this->redirect($this->buildUrl());
}
$comptesRendus = $this->projetCompteRenduModel->getByProjetId($id);
$projectDocuments = $this->getProjectDocuments($id);
$infosEntreprise = $this->reglagesEntrepriseModel->get();
require __DIR__ . '/../views/projet_view.php';
}
private function edit(int $id): void {
$projet = $this->projetModel->getById($id);
if (!$projet) {
$this->redirect($this->buildUrl());
}
$clients = $this->clientModel->getAll();
$comptesRendus = $this->projetCompteRenduModel->getByProjetId($id);
require __DIR__ . '/../views/projet_edit.php';
}
private function saveFromPost() {
$id = isset($_POST['projet_id']) && $_POST['projet_id'] !== '' ? (int) $_POST['projet_id'] : null;
$redirectTo = trim((string) ($_POST['redirect_to'] ?? 'list'));
$existingProject = $id ? $this->projetModel->getById($id) : null;
$data = [
'devis_id' => $existingProject['devis_id'] ?? null,
'client_id' => isset($_POST['client_id']) && $_POST['client_id'] !== '' ? (int) $_POST['client_id'] : null,
'titre' => trim((string) ($_POST['titre'] ?? '')),
'description' => trim((string) ($_POST['description'] ?? '')),
'date_projet' => trim((string) ($_POST['date_projet'] ?? date('Y-m-d'))),
'montant' => (float) ($_POST['montant'] ?? 0),
'statut' => trim((string) ($_POST['statut'] ?? 'Proposition')),
];
if ($data['titre'] === '') {
if ($id && $redirectTo === 'edit') {
$this->redirect($this->buildUrl('edit', ['id' => $id, 'missing_title' => 1]));
}
$this->list();
return;
}
$targetId = $id;
if ($id) {
$this->projetModel->update($id, $data);
} else {
$targetId = $this->projetModel->create($data);
}
if ($redirectTo === 'edit' && $targetId) {
$this->redirect($this->buildUrl('edit', ['id' => $targetId, 'saved' => 1]));
}
$this->redirect($this->buildUrl());
}
private function saveCompteRendu(): void {
$projetId = isset($_POST['projet_id']) ? (int) $_POST['projet_id'] : 0;
$reportId = isset($_POST['report_id']) ? (int) $_POST['report_id'] : 0;
$contenu = trim((string) ($_POST['contenu'] ?? ''));
if ($projetId <= 0) {
$this->redirect($this->buildUrl());
}
if (!$this->hasRichTextContent($contenu)) {
$this->redirect($this->buildUrl('edit', ['id' => $projetId, 'empty_report' => 1]));
}
if ($reportId > 0) {
$existing = $this->projetCompteRenduModel->getById($reportId);
if (!$existing || (int) $existing['projet_id'] !== $projetId) {
$this->redirect($this->buildUrl('edit', ['id' => $projetId, 'report_missing' => 1]));
}
$this->projetCompteRenduModel->update($reportId, $projetId, $contenu);
$this->redirect($this->buildUrl('edit', ['id' => $projetId, 'report_updated' => 1]));
}
$this->projetCompteRenduModel->create($projetId, $contenu);
$this->redirect($this->buildUrl('edit', ['id' => $projetId, 'report_saved' => 1]));
}
private function delete(int $id): void {
if ($id > 0) {
$this->projectLinkModel->deleteByProjectId($id);
$this->projetCompteRenduModel->deleteByProjetId($id);
$this->projetModel->delete($id);
}
$this->redirect($this->buildUrl());
}
private function getProjectDocuments(int $projectId): array {
$links = $this->projectLinkModel->getByProjectId($projectId);
if (!$links) {
return [];
}
$devisModel = new Devis();
$factureModel = new Facture();
$rdvModel = new RdvModel();
$emailModel = new Email();
$emailAttachmentModel = new EmailAttachment();
$documents = [];
foreach ($links as $link) {
$entityType = (string) ($link['entity_type'] ?? '');
$entityId = (int) ($link['entity_id'] ?? 0);
if ($entityId <= 0) {
continue;
}
if ($entityType === 'devis') {
$devis = $devisModel->getById($entityId);
if (!$devis) {
continue;
}
$documents[] = [
'type' => 'devis',
'entity_type' => 'devis',
'entity_id' => $entityId,
'title' => trim((string) ($devis['numero'] ?? '')) !== '' ? 'Devis ' . (string) $devis['numero'] : 'Devis #' . $entityId,
'meta' => trim((string) ($devis['date_devis'] ?? '')) !== '' ? 'Date : ' . date('d/m/Y', strtotime((string) $devis['date_devis'])) : '',
'status' => (string) ($devis['statut'] ?? ''),
'view_url' => 'index.php?page=devis&action=apercu&id=' . $entityId,
'view_label' => 'Aperçu du devis',
'attachments' => [],
'added_at' => (string) ($link['created_at'] ?? ''),
];
continue;
}
if ($entityType === 'facture') {
$facture = $factureModel->getById($entityId);
if (!$facture) {
continue;
}
$documents[] = [
'type' => 'facture',
'entity_type' => 'facture',
'entity_id' => $entityId,
'title' => trim((string) ($facture['numero'] ?? '')) !== '' ? 'Facture ' . (string) $facture['numero'] : 'Facture #' . $entityId,
'meta' => trim((string) ($facture['date_facture'] ?? '')) !== '' ? 'Date : ' . date('d/m/Y', strtotime((string) $facture['date_facture'])) : '',
'status' => (string) ($facture['statut'] ?? ''),
'view_url' => 'index.php?page=factures&action=apercu&id=' . $entityId,
'view_label' => 'Aperçu de la facture',
'attachments' => [],
'added_at' => (string) ($link['created_at'] ?? ''),
];
continue;
}
if ($entityType === 'rdv') {
$rdv = $rdvModel->getRdvById($entityId);
if (!$rdv) {
continue;
}
$meta = [];
if (!empty($rdv['date'])) {
$meta[] = 'Date : ' . date('d/m/Y', strtotime((string) $rdv['date']));
}
if (!empty($rdv['heure'])) {
$meta[] = 'Heure : ' . substr((string) $rdv['heure'], 0, 5);
}
$documents[] = [
'type' => 'rdv',
'entity_type' => 'rdv',
'entity_id' => $entityId,
'title' => trim((string) ($rdv['titre'] ?? '')) !== '' ? (string) $rdv['titre'] : 'Rendez-vous #' . $entityId,
'meta' => implode(' · ', $meta),
'status' => (string) ($rdv['statut'] ?? ''),
'view_url' => 'index.php?page=calendar&open_rdv_id=' . $entityId,
'view_label' => 'Aperçu du rendez-vous',
'attachments' => [],
'added_at' => (string) ($link['created_at'] ?? ''),
];
continue;
}
if ($entityType === 'email') {
$email = $emailModel->getById($entityId);
if (!$email) {
continue;
}
$attachments = [];
foreach ($emailAttachmentModel->getByEmailId($entityId) as $attachment) {
$attachments[] = [
'label' => (string) ($attachment['filename'] ?? 'Pièce jointe'),
'url' => 'index.php?page=boite-mail&action=att&att_id=' . (int) ($attachment['id'] ?? 0),
];
}
$meta = [];
if (!empty($email['destinataire'])) {
$meta[] = 'À : ' . (string) $email['destinataire'];
}
if (!empty($email['date_message'])) {
$meta[] = 'Le ' . date('d/m/Y H:i', strtotime((string) $email['date_message']));
}
$documents[] = [
'type' => 'email',
'entity_type' => 'email',
'entity_id' => $entityId,
'title' => trim((string) ($email['sujet'] ?? '')) !== '' ? (string) $email['sujet'] : 'E-mail #' . $entityId,
'meta' => implode(' · ', $meta),
'status' => (string) ($email['statut'] ?? ''),
'view_url' => 'index.php?page=boite-mail&open_email_id=' . $entityId,
'view_label' => 'Aperçu de l\'e-mail',
'attachments' => $attachments,
'added_at' => (string) ($link['created_at'] ?? ''),
];
}
}
return $documents;
}
private function detachDocument(int $projectId): void {
$entityType = trim((string) ($_GET['entity_type'] ?? ''));
$entityId = isset($_GET['entity_id']) ? (int) $_GET['entity_id'] : 0;
if ($projectId <= 0 || $entityId <= 0 || $entityType === '') {
$this->redirect($this->buildUrl('view', ['id' => $projectId, 'detach_error' => 1]));
}
$link = $this->projectLinkModel->getForEntity($entityType, $entityId);
if (!$link || (int) ($link['projet_id'] ?? 0) !== $projectId) {
$this->redirect($this->buildUrl('view', ['id' => $projectId, 'detach_error' => 1]));
}
$this->projectLinkModel->deleteByEntity($entityType, $entityId);
$this->redirect($this->buildUrl('view', ['id' => $projectId, 'detached' => 1]));
}
private function hasRichTextContent(string $html): bool {
$decoded = html_entity_decode($html, ENT_QUOTES | ENT_HTML5, 'UTF-8');
$text = trim(str_replace("\xC2\xA0", ' ', strip_tags($decoded)));
return $text !== '';
}
private function buildUrl(string $action = '', array $params = []): string {
$query = ['page' => 'projets'];
if ($action !== '') {
$query['action'] = $action;
}
foreach ($params as $key => $value) {
$query[$key] = $value;
}
return 'index.php?' . http_build_query($query);
}
private function redirect(string $url): void {
header('Location: ' . $url);
exit;
}
}