<?php
require_once 'includes/auth.php';
require_once 'config/database.php';
require_once 'vendor/autoload.php';

use Dompdf\Dompdf;
use Dompdf\Options;

$projet_id = filter_input(INPUT_GET, 'projet_id', FILTER_VALIDATE_INT);
if (!$projet_id) {
    die("Projet invalide.");
}

$pdo = getPDO();

$stmt = $pdo->prepare("SELECT nom FROM projets WHERE id = ?");
$stmt->execute([$projet_id]);
$projet = $stmt->fetch();
if (!$projet) {
    die("Projet introuvable.");
}

$show_deleted = filter_input(INPUT_GET, 'deleted', FILTER_VALIDATE_BOOLEAN) ? true : false;
$sql_where = $show_deleted ? "f.deleted_at IS NOT NULL" : "f.deleted_at IS NULL";

$sql = "SELECT f.numero_fiche, f.titre, d.nom as dossier_nom, sd.nom as sous_dossier_nom,
               f.zone, f.type_reserve, f.statut, u.nom as createur_nom,
               f.date_creation, f.date_soumission, ud.nom as deleted_by_nom, f.deleted_at
        FROM fiches f
        JOIN sous_dossiers sd ON f.sous_dossier_id = sd.id
        JOIN dossiers d ON sd.dossier_id = d.id
        LEFT JOIN users u ON f.createur_id = u.id
        LEFT JOIN users ud ON f.deleted_by = ud.id
        WHERE d.projet_id = ? AND $sql_where
        ORDER BY f.date_creation DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute([$projet_id]);
$fiches = $stmt->fetchAll();

$html = '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Récapitulatif - ' . htmlspecialchars($projet['nom']) . '</title>
    <style>
        body { font-family: DejaVu Sans, Arial, sans-serif; font-size: 12px; margin: 20px; }
        h1 { color: #0d6efd; text-align: center; }
        .info { margin-bottom: 20px; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th { background: #343a40; color: white; padding: 8px; text-align: left; border: 1px solid #dee2e6; }
        td { padding: 6px; border: 1px solid #dee2e6; vertical-align: top; }
        tr:nth-child(even) { background: #f8f9fa; }
        .badge { display: inline-block; padding: 2px 6px; border-radius: 10px; font-size: 10px; font-weight: bold; }
        .badge-success { background: #d4edda; color: #155724; }
        .badge-danger { background: #f8d7da; color: #721c24; }
        .footer { margin-top: 30px; font-size: 10px; text-align: center; color: #6c757d; border-top: 1px dashed #dee2e6; padding-top: 10px; }
    </style>
</head>
<body>
    <h1>CIBER BTP - Récapitulatif des fiches</h1>
    <div class="info">
        <p><strong>Projet :</strong> ' . htmlspecialchars($projet['nom']) . '</p>
        <p><strong>Date d\'édition :</strong> ' . date('d/m/Y H:i') . '</p>
        <p><strong>Filtre :</strong> ' . ($show_deleted ? 'Corbeille' : 'Fiches actives') . '</p>
    </div>

    <table>
        <thead>
            <tr>
                <th>N° Fiche</th>
                <th>Titre</th>
                <th>Dossier</th>
                <th>Sous-dossier</th>
                <th>Zone</th>
                <th>Type</th>
                <th>Statut</th>
                <th>Créateur</th>
                <th>Date création</th>
                ' . ($show_deleted ? '<th>Supprimé par</th><th>Date suppression</th>' : '') . '
            </tr>
        </thead>
        <tbody>';

foreach ($fiches as $fiche) {
    $type_badge = ($fiche['type_reserve'] == 'sans_reserve') ? 'badge-success' : 'badge-danger';
    $type_label = ($fiche['type_reserve'] == 'sans_reserve') ? 'Sans réserve' : 'Avec réserve';

    $html .= '<tr>
        <td>' . htmlspecialchars($fiche['numero_fiche']) . '</td>
        <td>' . htmlspecialchars($fiche['titre']) . '</td>
        <td>' . htmlspecialchars($fiche['dossier_nom']) . '</td>
        <td>' . htmlspecialchars($fiche['sous_dossier_nom']) . '</td>
        <td>' . htmlspecialchars($fiche['zone'] ?? '') . '</td>
        <td><span class="badge ' . $type_badge . '">' . $type_label . '</span></td>
        <td>' . htmlspecialchars($fiche['statut']) . '</td>
        <td>' . htmlspecialchars($fiche['createur_nom'] ?? '') . '</td>
        <td>' . date('d/m/Y', strtotime($fiche['date_creation'])) . '</td>';

    if ($show_deleted) {
        $html .= '<td>' . htmlspecialchars($fiche['deleted_by_nom'] ?? '') . '</td>
                  <td>' . ($fiche['deleted_at'] ? date('d/m/Y H:i', strtotime($fiche['deleted_at'])) : '') . '</td>';
    }

    $html .= '</tr>';
}

$html .= '
        </tbody>
    </table>
    <div class="footer">
        Document généré automatiquement par l\'application CIBER Auto-contrôle.
    </div>
</body>
</html>';

$options = new Options();
$options->set('defaultFont', 'DejaVu Sans');
$options->set('isRemoteEnabled', false);

$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();

$dompdf->stream("recap_" . $projet['nom'] . "_" . date('Ymd') . ".pdf", array("Attachment" => 1));
exit;