<?php
$fmt = static fn($v): string => number_format((float)$v, 2, ',', ' ') . ' MAD';
$pct = static fn($v): string => number_format((float)$v, 2, ',', ' ') . ' %';
$qty = static fn($v): string => number_format((float)$v, 0, ',', ' ');
$kpis = $kpis ?? [];
$devisStatus = $devisStatus ?? [];
$topClients = $topClients ?? [];
$topArticles = $topArticles ?? [];
$facturesAEncaisser = $facturesAEncaisser ?? [];
$recentEncaissements = $recentEncaissements ?? [];
$recentDocuments = $recentDocuments ?? [];
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Tableau de bord commercial</h1>
        <p class="text-muted mb-0">Pilotage des ventes, devis, factures, encaissements et marges — <?= htmlspecialchars($version ?? 'Phoenix P3.6.1') ?></p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=document_cycle" class="btn btn-outline-primary">Cycle documentaire</a>
        <a href="index.php?page=documents_create" class="btn btn-primary">+ Document commercial</a>
        <a href="index.php?page=encaissements_create" class="btn btn-outline-success">+ Encaissement</a>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">CA factures HT</div>
            <div class="h4 mb-1"><?= $fmt($kpis['ca_ht_total'] ?? 0) ?></div>
            <div class="small text-muted"><?= (int)($kpis['nb_factures'] ?? 0) ?> facture(s)</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">CA du mois HT</div>
            <div class="h4 mb-1"><?= $fmt($kpis['ca_ht_mois'] ?? 0) ?></div>
            <div class="small text-muted"><?= (int)($kpis['nb_factures_mois'] ?? 0) ?> facture(s) ce mois</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Reste à encaisser</div>
            <div class="h4 mb-1 text-danger"><?= $fmt($kpis['reste_a_encaisser'] ?? 0) ?></div>
            <div class="small text-muted">Factures clients non réglées</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Marge moyenne</div>
            <div class="h4 mb-1"><?= $pct($kpis['marge_pourcentage_moyenne'] ?? 0) ?></div>
            <div class="small text-muted">Marge factures</div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Marge HT totale</div>
            <div class="h5 mb-1"><?= $fmt($kpis['marge_ht_total'] ?? 0) ?></div>
            <div class="small text-muted">dont <?= $fmt($kpis['marge_ht_mois'] ?? 0) ?> ce mois</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Encaissements du mois</div>
            <div class="h5 mb-1 text-success"><?= $fmt($kpis['montant_encaisse_mois'] ?? 0) ?></div>
            <div class="small text-muted">Règlements clients enregistrés</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Devis</div>
            <div class="h5 mb-1"><?= (int)($kpis['nb_devis'] ?? 0) ?></div>
            <div class="small text-muted"><?= (int)($kpis['nb_devis_mois'] ?? 0) ?> devis ce mois</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Documents du mois</div>
            <div class="h5 mb-1"><?= (int)($kpis['nb_documents_mois'] ?? 0) ?></div>
            <div class="small text-muted">Devis, BL, factures, avoirs</div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-lg-6">
        <div class="darlink-card p-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">Devis par statut</h5>
                <a href="index.php?page=devis" class="btn btn-sm btn-outline-primary">Voir devis</a>
            </div>
            <?php if (empty($devisStatus)): ?>
                <p class="text-muted mb-0">Aucun devis enregistré.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm align-middle">
                        <thead><tr><th>Statut</th><th class="text-end">Nombre</th><th class="text-end">Total TTC</th></tr></thead>
                        <tbody>
                        <?php foreach ($devisStatus as $row): ?>
                            <tr>
                                <td><span class="badge text-bg-light border"><?= htmlspecialchars((string)($row['statut'] ?? '')) ?></span></td>
                                <td class="text-end"><?= (int)($row['nombre'] ?? 0) ?></td>
                                <td class="text-end"><?= $fmt($row['total_ttc'] ?? 0) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="col-lg-6">
        <div class="darlink-card p-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">Factures à encaisser</h5>
                <a href="index.php?page=factures" class="btn btn-sm btn-outline-primary">Voir factures</a>
            </div>
            <?php if (empty($facturesAEncaisser)): ?>
                <p class="text-muted mb-0">Aucune facture client à encaisser.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm align-middle">
                        <thead><tr><th>Facture</th><th>Client</th><th>Échéance</th><th class="text-end">Reste</th><th></th></tr></thead>
                        <tbody>
                        <?php foreach ($facturesAEncaisser as $facture): ?>
                            <tr>
                                <td><a href="index.php?page=factures_show&id=<?= (int)$facture['id'] ?>"><?= htmlspecialchars((string)($facture['numero'] ?? '')) ?></a></td>
                                <td><?= htmlspecialchars((string)($facture['client_nom'] ?? '')) ?></td>
                                <td><?= htmlspecialchars((string)($facture['date_echeance'] ?: 'Sans échéance')) ?></td>
                                <td class="text-end text-danger"><strong><?= $fmt($facture['reste_du'] ?? 0) ?></strong></td>
                                <td class="text-end"><a class="btn btn-sm btn-outline-success" href="index.php?page=encaissements_create&facture_id=<?= (int)$facture['id'] ?>">Encaisser</a></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-lg-6">
        <div class="darlink-card p-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">Top clients</h5>
                <a href="index.php?page=clients" class="btn btn-sm btn-outline-secondary">Clients</a>
            </div>
            <?php if (empty($topClients)): ?>
                <p class="text-muted mb-0">Aucune vente facturée.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm align-middle">
                        <thead><tr><th>Client</th><th class="text-end">Factures</th><th class="text-end">CA TTC</th><th class="text-end">Marge HT</th></tr></thead>
                        <tbody>
                        <?php foreach ($topClients as $client): ?>
                            <tr>
                                <td><?= htmlspecialchars((string)($client['client_nom'] ?? '')) ?></td>
                                <td class="text-end"><?= (int)($client['nb_factures'] ?? 0) ?></td>
                                <td class="text-end"><?= $fmt($client['total_ttc'] ?? 0) ?></td>
                                <td class="text-end"><?= $fmt($client['marge_ht'] ?? 0) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="col-lg-6">
        <div class="darlink-card p-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">Top articles vendus</h5>
                <a href="index.php?page=articles" class="btn btn-sm btn-outline-secondary">Articles</a>
            </div>
            <?php if (empty($topArticles)): ?>
                <p class="text-muted mb-0">Aucune ligne de facture.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm align-middle">
                        <thead><tr><th>Article</th><th class="text-end">Qté</th><th class="text-end">Total HT</th><th class="text-end">Marge HT</th></tr></thead>
                        <tbody>
                        <?php foreach ($topArticles as $article): ?>
                            <tr>
                                <td><?= htmlspecialchars(trim(($article['reference'] ?? '') . ' — ' . ($article['designation'] ?? ''), ' —')) ?></td>
                                <td class="text-end"><?= $qty($article['quantite_vendue'] ?? 0) ?></td>
                                <td class="text-end"><?= $fmt($article['total_ht'] ?? 0) ?></td>
                                <td class="text-end"><?= $fmt($article['marge_ht'] ?? 0) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="row g-3">
    <div class="col-lg-6">
        <div class="darlink-card p-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">Derniers encaissements</h5>
                <a href="index.php?page=encaissements" class="btn btn-sm btn-outline-secondary">Encaissements</a>
            </div>
            <?php if (empty($recentEncaissements)): ?>
                <p class="text-muted mb-0">Aucun encaissement récent.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm align-middle">
                        <thead><tr><th>Date</th><th>Client</th><th>Facture</th><th>Mode</th><th class="text-end">Montant</th></tr></thead>
                        <tbody>
                        <?php foreach ($recentEncaissements as $enc): ?>
                            <tr>
                                <td><?= htmlspecialchars((string)($enc['date_encaissement'] ?? '')) ?></td>
                                <td><?= htmlspecialchars((string)($enc['client_nom'] ?? '')) ?></td>
                                <td><?= htmlspecialchars((string)($enc['facture_numero'] ?? '')) ?></td>
                                <td><?= htmlspecialchars((string)($enc['mode_reglement'] ?? '')) ?></td>
                                <td class="text-end text-success"><?= $fmt($enc['montant'] ?? 0) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="col-lg-6">
        <div class="darlink-card p-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">Derniers documents commerciaux</h5>
                <a href="index.php?page=documents" class="btn btn-sm btn-outline-secondary">Documents</a>
            </div>
            <?php if (empty($recentDocuments)): ?>
                <p class="text-muted mb-0">Aucun document récent.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm align-middle">
                        <thead><tr><th>Type</th><th>N°</th><th>Date</th><th>Statut</th><th class="text-end">TTC</th></tr></thead>
                        <tbody>
                        <?php foreach ($recentDocuments as $document): ?>
                            <tr>
                                <td><?= htmlspecialchars((string)($document['type_document'] ?? '')) ?></td>
                                <td><a href="index.php?page=documents_show&id=<?= (int)$document['id'] ?>"><?= htmlspecialchars((string)($document['numero'] ?? '')) ?></a></td>
                                <td><?= htmlspecialchars((string)($document['date_document'] ?? '')) ?></td>
                                <td><span class="badge text-bg-light"><?= htmlspecialchars((string)($document['statut'] ?? '')) ?></span></td>
                                <td class="text-end"><?= $fmt($document['total_ttc'] ?? 0) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
