<?php
// ============================================================
//  AÉRYA PRO — generate_pdf.php
//  Génère le PDF d'un devis
// ============================================================
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/vendor/autoload.php';
session_start();
if (!current_user()) { header('Location: login.php'); exit; }
$me = current_user();
$db = db();

$devis_id = (int)($_GET['id'] ?? 0);
if (!$devis_id) { header('Location: index.php'); exit; }

$stmt = $db->prepare("
    SELECT d.*, c.firstname as cf, c.lastname as cl, c.email as ce, c.phone as cp, c.address as ca
    FROM devis d
    LEFT JOIN clients c ON c.id = d.client_id
    WHERE d.id = ? AND d.user_id = ?
");
$stmt->execute([$devis_id, $me['id']]);
$devis = $stmt->fetch();
if (!$devis) { header('Location: index.php'); exit; }

$lignes_stmt = $db->prepare("SELECT * FROM devis_lignes WHERE devis_id=? ORDER BY id ASC");
$lignes_stmt->execute([$devis_id]);
$lignes = $lignes_stmt->fetchAll();

$html = '
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body { font-family: Arial, sans-serif; color: #333; font-size: 12px; }
.header { display: flex; justify-content: space-between; margin-bottom: 30px; }
.company { font-size: 18px; font-weight: bold; color: #c9a96e; }
.devis-num { font-size: 14px; color: #666; margin-top: 5px; }
.section { margin-bottom: 20px; }
.section-title { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: #999; border-bottom: 1px solid #eee; padding-bottom: 5px; margin-bottom: 10px; }
.client-info { background: #f9f9f9; padding: 10px; border-radius: 5px; }
table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
th { background: #c9a96e; color: white; padding: 8px; text-align: left; font-size: 11px; }
td { padding: 7px 8px; border-bottom: 1px solid #eee; }
tr:nth-child(even) { background: #f9f9f9; }
.total-table { width: 300px; margin-left: auto; }
.total-table td { padding: 5px 8px; }
.total-ttc { font-weight: bold; font-size: 14px; color: #c9a96e; border-top: 2px solid #c9a96e; }
.footer { margin-top: 40px; font-size: 10px; color: #999; text-align: center; border-top: 1px solid #eee; padding-top: 10px; }
</style>
</head>
<body>

<div class="header">
    <div>
        <div class="company">' . htmlspecialchars($me['company_name'] ?? 'Mon Entreprise') . '</div>
        <div>' . htmlspecialchars($me['firstname'] ?? '') . '</div>
        <div>' . htmlspecialchars($me['phone'] ?? '') . '</div>
        <div>' . htmlspecialchars($me['address'] ?? '') . '</div>
        ' . ($me['siret'] ? '<div>SIRET : ' . htmlspecialchars($me['siret']) . '</div>' : '') . '
    </div>
    <div style="text-align:right">
        <div class="devis-num">DEVIS N° ' . htmlspecialchars($devis['numero']) . '</div>
        <div style="color:#999;margin-top:5px">Date : ' . date('d/m/Y', strtotime($devis['created_at'])) . '</div>
    </div>
</div>

<div class="section">
    <div class="section-title">Client</div>
    <div class="client-info">
        <strong>' . htmlspecialchars(($devis['cf'] ?? '') . ' ' . ($devis['cl'] ?? '')) . '</strong><br>
        ' . ($devis['ce'] ? htmlspecialchars($devis['ce']) . '<br>' : '') . '
        ' . ($devis['cp'] ? htmlspecialchars($devis['cp']) : '') . '
    </div>
</div>

' . ($devis['description'] ? '
<div class="section">
    <div class="section-title">Description</div>
    <p>' . nl2br(htmlspecialchars($devis['description'])) . '</p>
</div>' : '') . '

<div class="section">
    <div class="section-title">Détail des travaux</div>
    <table>
        <thead>
            <tr>
                <th>Désignation</th>
                <th>Quantité</th>
                <th>Prix unitaire HT</th>
                <th>Total HT</th>
            </tr>
        </thead>
        <tbody>';

foreach ($lignes as $l) {
    $html .= '<tr>
        <td>' . htmlspecialchars($l['description']) . '</td>
        <td>' . number_format($l['quantite'], 2, ',', ' ') . '</td>
        <td>' . number_format($l['prix_unitaire'], 2, ',', ' ') . ' €</td>
        <td>' . number_format($l['total'], 2, ',', ' ') . ' €</td>
    </tr>';
}

$html .= '
        </tbody>
    </table>
</div>

<table class="total-table">
    <tr><td>Total HT</td><td style="text-align:right">' . number_format($devis['montant_ht'], 2, ',', ' ') . ' €</td></tr>
    <tr><td>TVA (20%)</td><td style="text-align:right">' . number_format($devis['montant_ht'] * 0.2, 2, ',', ' ') . ' €</td></tr>
    <tr class="total-ttc"><td><strong>TOTAL TTC</strong></td><td style="text-align:right"><strong>' . number_format($devis['montant_ttc'], 2, ',', ' ') . ' €</strong></td></tr>
</table>

<div class="footer">
    ' . htmlspecialchars($me['company_name'] ?? '') . ' — ' . htmlspecialchars($me['address'] ?? '') . '
    ' . ($me['siret'] ? '— SIRET : ' . htmlspecialchars($me['siret']) : '') . '
</div>

</body>
</html>';

$mpdf = new \Mpdf\Mpdf(['margin_top'=>15,'margin_bottom'=>15,'margin_left'=>15,'margin_right'=>15]);
$mpdf->SetTitle('Devis ' . $devis['numero']);
$mpdf->WriteHTML($html);
$mpdf->Output('Devis_' . $devis['numero'] . '.pdf', 'D');