<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require 'config.php';
require 'vendor/autoload.php';

use Dompdf\Dompdf;

// Vérifier si l'utilisateur est connecté
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// Vérifier si l'ID du rapport est passé en paramètre
if (!isset($_GET['id'])) {
    header('Location: dashboard.php');
    exit;
}

$report_id = $_GET['id'];
$role = $_SESSION['role'];
$entreprise = $_SESSION['entreprise'];
$user_id = $_SESSION['user_id'];

// Récupérer le rapport
$stmt = $pdo->prepare("SELECT * FROM reports WHERE id = ?");
$stmt->execute([$report_id]);
$report = $stmt->fetch();

// Vérifier si le rapport existe
if (!$report) {
    die("Rapport non trouvé.");
}

// Sécurité : Vérifier les permissions
$isAuthorized = ($role === 'super_admin' || ($role === 'admin_entreprise' && $report['entreprise'] === $entreprise) || ($role === 'client' && $report['created_by'] === $user_id));
if (!$isAuthorized) {
    die("Accès non autorisé à ce rapport.");
}

$date_intervention_fr = (new DateTime($report['date_intervention']))->format('d/m/Y');

// Générer le HTML stylisé
$html = "
<!DOCTYPE html>
<html lang='fr'>
<head>
    <meta charset='UTF-8'>
        <script src='https://unpkg.com/feather-icons'></script>
    <title>Fiche d'intervention</title>
    <style>
        body { font-family: Arial, sans-serif; font-size: 12px; margin: 0; padding: 2px; }
        .header { text-align: center; font-size: 12px; font-weight: bold; background: #ccc;border-radius: 25% 10%; color: white; padding: 10px; }
        .section { margin: 1px 0; padding: 4px; border: 1px solid #ccc;border-radius:6px }
        .table { width: 100%; order-collapse: collapse; }
        .table th, .table td { order: 1px solid #ccc; padding: 2px; text-align: left; }
        .signature-table { width: 100%; margin-top: 20px; }
        .signature-table td { text-align: center; vertical-align: top; }
        .signature-table img { width: 150px; height: auto; border: 1px solid #ccc; border-radius:6px; }
	h4 {color:grey; }
    </style>
</head>
<body>
    <div class='header'>Fiche d'intervention N° {$report['id']} <br>$date_intervention_fr
    </div>
    <h4 style='border-bottom:1px solid #ccc'>Client</h4>
    <div class='section'>
        <strong>Intervenant(s) :</strong> {$report['nom_prenom']}<br>
        <strong>Client :</strong> {$report['nom_client']}<br>
        <strong>Adresse :</strong> {$report['adresse']}, {$report['code_postal']} {$report['ville']}<br>
        <strong>Téléphone :</strong> {$report['telephone']}<br>
    </div>
    <h4 style='border-bottom:1px solid #ccc'>Anomalies constatés</h4>
    <div class='section' style='height:100px;'><strong></strong> {$report['anomalies']}</div>
    <h4 style='border-bottom:1px solid #ccc;'>Intervention</h4>
    <div class='section' style='height:100px;'><strong></strong> {$report['intervention']}</div>
    <h4 style='border-bottom:1px solid #ccc;'>Fournitures</h4>
<!--    <div class='section' style='height:120px'>
        <strong></strong>
        <table class='table'>
            <tr></tr>
            ".implode("", array_map(function($item) {
                return "<tr><td>".htmlspecialchars($item)."</td></tr>";
            }, explode(",", $report['equipement'])))."
        </table>
    </div>
-->
<div class='section' style='height:120px'>
    <strong></strong>
    <ul>
        " . implode("", array_map(function($item) {
            // Enlève les guillemets et les espaces superflus
            return "<li>" . htmlspecialchars(trim($item, '" ')) . "</li>";
        }, explode(",", trim($report['equipement'], "[]"))) ) . "
    </ul>
</div>

    <h4 style='border-bottom:1px solid #ccc'>Main d'oeuvre</h4>
    <div class='section'>
        <strong>Type de facture :</strong> {$report['facture']} |
        <strong>Zone de déplacement :</strong> {$report['deplacement']} |
        <strong>Heure d'arrivée :</strong> {$report['heure_arrivee']} | <strong>heure de départ</strong> {$report['heure_depart']} | <strong>Temps de trajet :</strong> {$report['heure_trajet']}
        <!--<strong>Temps de trajet :</strong> {$report['heure_trajet']}-->
    </div>
    <h4 style='border-bottom:1px solid #ccc'>Commentaire</h4>
    <div class='section' style='height:80px;'><strong></strong> {$report['commentaires']}</div>

    <!-- Table pour les signatures -->
    <table class='signature-table'>
        <tr>
            <td>
                <strong>Technicien</strong><br>
                <img src='{$report['signature_technicien_data']}'>
            </td>
            <td>
                <strong>Client</strong><br>
                <img src='{$report['signature_client_data']}'>
            </td>
        </tr>
    </table>
<!--    <center><p style='margin-top:2px'>Rapport crée le : {$report['created_at']}</p></center>-->
<script>
        feather.replace();
    </script>

</body>
</html>
";

// Générer le PDF
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("fiche_intervention_{$report['id']}.pdf", ["Attachment" => true]);
?>
