<?php
$formatMoney = static fn($value): string => number_format((float)$value, 2, ',', ' ') . ' DH';
$legacyUrl = $documentManager->legacyUrl($document);
$actionUrl = $legacyUrl;
$actionLabel = match ((string)($document['source_table'] ?? '')) {
    'devis' => 'Consulter devis',
    'bons_livraison' => 'Consulter BL',
    'factures' => 'Consulter facture',
    default => 'Consulter',
};
$actionClass = 'btn-outline-secondary';
if (($document['type_document'] ?? '') === 'FACTURE' && (string)($document['source_table'] ?? '') === 'factures' && (int)($document['source_id'] ?? 0) > 0) {
    $actionUrl = 'index.php?page=encaissements_create&facture_id=' . (int)$document['source_id'];
    $actionLabel = '💰 Encaisser';
    $actionClass = 'btn-outline-success';
}
$typeLabels = [
    'DEVIS' => 'Devis',
    'BL' => 'Bon de livraison',
    'FACTURE' => 'Facture',
    'AVOIR' => 'Avoir',
];
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1"><?= htmlspecialchars($typeLabels[$document['type_document']] ?? $document['type_document']) ?> <?= htmlspecialchars($document['numero']) ?></h1>
        <p class="text-muted mb-0">
            Client : <?= htmlspecialchars($document['client_nom']) ?>
            <?php if (!empty($document['parent_numero'])): ?>
                — issu de <?= htmlspecialchars(($typeLabels[$document['parent_type']] ?? $document['parent_type']) . ' ' . $document['parent_numero']) ?>
            <?php endif; ?>
        </p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=documents" class="btn btn-outline-secondary">Retour</a>
        <?php if ($actionUrl): ?>
            <a href="<?= htmlspecialchars($actionUrl) ?>" class="btn <?= htmlspecialchars($actionClass) ?>"><?= htmlspecialchars($actionLabel) ?></a>
        <?php endif; ?>
        <?php if (($document['type_document'] ?? '') === 'FACTURE' && (float)($document['reste_du'] ?? 0) > 0.005): ?>
            <a href="index.php?page=documents_edit&id=<?= (int)$document['id'] ?>" class="btn btn-outline-warning">Modifier</a>
        <?php endif; ?>
        <?php if (($document['type_document'] ?? '') === 'FACTURE'): ?>
            <a href="index.php?page=avoirs_create&facture_id=<?= (int)$document['id'] ?>" class="btn btn-outline-success">Créer un avoir</a>
        <?php endif; ?>
        <a href="index.php?page=documents_pdf&id=<?= (int)$document['id'] ?>" target="_blank" class="btn btn-outline-primary">📄 Générer le PDF</a>
    </div>
</div>

<?php if (!empty($transformTargets)): ?>
    <div class="darlink-card p-3 mb-4">
        <form method="post" action="index.php?page=documents_transform" class="d-flex align-items-center gap-2 flex-wrap">
            <input type="hidden" name="id" value="<?= (int)$document['id'] ?>">
            <strong>Transformer en :</strong>
            <?php foreach ($transformTargets as $targetType => $targetLabel): ?>
                <button type="submit" name="target_type" value="<?= htmlspecialchars($targetType) ?>" class="btn btn-sm darlink-btn-primary">
                    <?= htmlspecialchars($targetLabel) ?>
                </button>
            <?php endforeach; ?>
        </form>
        <div class="text-muted small mt-2">
            Les transformations sont gérées par DocumentManager. Le stock est décrémenté uniquement lors d'un BL ou d'une facture directe.
        </div>
    </div>
<?php endif; ?>

<div class="darlink-card p-4 mb-4">
    <div class="row g-3">
        <div class="col-md-3"><div class="darlink-stat"><span>Date</span><strong><?= htmlspecialchars(date('d/m/Y', strtotime((string)$document['date_document']))) ?></strong></div></div>
        <div class="col-md-3"><div class="darlink-stat"><span>Statut</span><strong><?= htmlspecialchars((($document['type_document'] ?? '') === 'FACTURE' && ($document['statut'] ?? '') === 'émise') ? 'En cours' : ($document['statut'] ?? '')) ?></strong></div></div>
        <div class="col-md-3"><div class="darlink-stat"><span>Total TTC</span><strong><?= $formatMoney($document['total_ttc']) ?></strong></div></div>
        <div class="col-md-3"><div class="darlink-stat"><span>Reste dû</span><strong><?= $formatMoney($document['reste_du'] ?? 0) ?></strong></div></div>
    </div>
</div>

<?php if (!empty($relatedDocuments) && count($relatedDocuments) > 1): ?>
    <div class="darlink-card p-4 mb-4">
        <h5 class="darlink-section-title">Documents liés</h5>
        <div class="table-responsive">
            <table class="table table-sm darlink-table align-middle">
                <thead><tr><th>Type</th><th>Numéro</th><th>Date</th><th>Statut</th><th class="text-end">Total TTC</th><th></th></tr></thead>
                <tbody>
                <?php foreach ($relatedDocuments as $linked): ?>
                    <tr class="<?= (int)$linked['id'] === (int)$document['id'] ? 'table-light' : '' ?>">
                        <td><?= htmlspecialchars($typeLabels[$linked['type_document']] ?? $linked['type_document']) ?></td>
                        <td><strong><?= htmlspecialchars($linked['numero']) ?></strong></td>
                        <td><?= htmlspecialchars(date('d/m/Y', strtotime((string)$linked['date_document']))) ?></td>
                        <td><?= htmlspecialchars($linked['statut']) ?></td>
                        <td class="text-end"><?= $formatMoney($linked['total_ttc']) ?></td>
                        <td class="text-end">
                            <?php if ((int)$linked['id'] === (int)$document['id']): ?>
                                <span class="badge bg-secondary">Document actuel</span>
                            <?php else: ?>
                                <a href="index.php?page=documents_show&id=<?= (int)$linked['id'] ?>" class="btn btn-sm btn-outline-primary">Voir</a>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php endif; ?>

<div class="darlink-card p-4 mb-4">
    <h5 class="darlink-section-title">Client</h5>
    <div class="row">
        <div class="col-md-6">
            <strong><?= htmlspecialchars($document['client_nom']) ?></strong><br>
            <?= nl2br(htmlspecialchars((string)($document['adresse'] ?? ''))) ?><br>
            <?= htmlspecialchars((string)($document['ville'] ?? '')) ?>
        </div>
        <div class="col-md-6 text-md-end text-muted">
            <?= htmlspecialchars((string)($document['telephone'] ?? $document['mobile'] ?? '')) ?><br>
            <?= htmlspecialchars((string)($document['email'] ?? '')) ?>
        </div>
    </div>
</div>

<div class="darlink-card p-4">
    <h5 class="darlink-section-title">Lignes</h5>
    <div class="table-responsive">
        <table class="table darlink-table align-middle">
            <thead>
            <tr>
                <th>Réf.</th>
                <th>Désignation</th>
                <th class="text-end">Qté</th>
                <th>Unité</th>
                <th class="text-end">PU HT</th>
                <th class="text-end">TVA</th>
                <th class="text-end">Total HT</th>
                <th class="text-end">Total TTC</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($lines as $line): ?>
                <tr>
                    <td><?= htmlspecialchars((string)($line['reference'] ?? '')) ?></td>
                    <td><?= htmlspecialchars($line['designation']) ?></td>
                    <td class="text-end"><?= number_format((float)$line['quantite'], 0, ',', ' ') ?></td>
                    <td><?= htmlspecialchars((string)($line['unite'] ?? '')) ?></td>
                    <td class="text-end"><?= $formatMoney($line['prix_vente_ht']) ?></td>
                    <td class="text-end"><?= number_format((float)$line['taux_tva'], 2, ',', ' ') ?> %</td>
                    <td class="text-end"><?= $formatMoney($line['total_ht']) ?></td>
                    <td class="text-end"><strong><?= $formatMoney($line['total_ttc']) ?></strong></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
            <tfoot>
            <tr><th colspan="6" class="text-end">Total HT</th><th colspan="2" class="text-end"><?= $formatMoney($document['total_ht']) ?></th></tr>
            <tr><th colspan="6" class="text-end">TVA</th><th colspan="2" class="text-end"><?= $formatMoney($document['total_tva']) ?></th></tr>
            <tr><th colspan="6" class="text-end">Total TTC</th><th colspan="2" class="text-end fs-5"><?= $formatMoney($document['total_ttc']) ?></th></tr>
            </tfoot>
        </table>
    </div>
</div>
