<?php
$fmt = static fn($v): string => number_format((float)$v, 2, ',', ' ') . ' MAD';
$qty = static fn($v): string => number_format((float)$v, 0, ',', ' ');
$commercial = $commercial ?? [];
$achats = $achats ?? [];
$fournisseurs = $fournisseurs ?? [];
$stockSummary = $stockSummary ?? [];
$stockValuation = $stockValuation ?? [];
$recentDocuments = $recentDocuments ?? [];
$recentOrders = $achats['recentOrders'] ?? [];
$overdueFactures = $fournisseurs['overdueFactures'] ?? [];
$upcomingFactures = $fournisseurs['upcomingFactures'] ?? [];
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Menu général</h1>
        <p class="text-muted mb-0">Vue globale de <?= htmlspecialchars($appName ?? 'Darlink ERP') ?> — <?= htmlspecialchars($version ?? 'Phoenix P3.6.9') ?></p>
    </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($commercial['ca_ht'] ?? 0) ?></div>
            <div class="small text-muted"><?= (int)($commercial['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">Marge factures HT</div>
            <div class="h4 mb-1"><?= $fmt($commercial['marge_ht'] ?? 0) ?></div>
            <div class="small text-muted">Reste client : <?= $fmt($commercial['reste_du'] ?? 0) ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Dû fournisseurs</div>
            <div class="h4 mb-1 <?= ((float)($fournisseurs['total_retard'] ?? 0) > 0) ? 'text-danger' : '' ?>"><?= $fmt($fournisseurs['total_du'] ?? 0) ?></div>
            <div class="small text-muted"><?= (int)($fournisseurs['nb_a_payer'] ?? 0) ?> facture(s) à payer</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Valeur stock achat HT</div>
            <div class="h4 mb-1"><?= $fmt($stockValuation['valeur_achat_ht'] ?? ($stockSummary['valeur_stock'] ?? 0)) ?></div>
            <div class="small text-muted"><?= (int)($stockSummary['total_articles'] ?? 0) ?> article(s) suivis</div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-3"><div class="darlink-card p-3"><div class="text-muted small">Commandes fournisseurs en cours</div><div class="h4 mb-0"><?= (int)($achats['commandes_en_cours'] ?? 0) ?></div></div></div>
    <div class="col-md-3"><div class="darlink-card p-3"><div class="text-muted small">Réceptions attendues</div><div class="h4 mb-0"><?= (int)($achats['receptions_attendues'] ?? 0) ?></div></div></div>
    <div class="col-md-3"><div class="darlink-card p-3"><div class="text-muted small">Factures fournisseurs en retard</div><div class="h4 mb-0 text-danger"><?= (int)($fournisseurs['nb_retard'] ?? 0) ?></div></div></div>
    <div class="col-md-3"><div class="darlink-card p-3"><div class="text-muted small">Ruptures / stock faible</div><div class="h4 mb-0"><span class="text-danger"><?= (int)($stockSummary['ruptures'] ?? 0) ?></span> / <span class="text-warning"><?= (int)($stockSummary['alertes'] ?? 0) ?></span></div></div></div>
</div>

<div class="darlink-card p-4 mb-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h5 class="mb-0">Accès rapides</h5>
            <div class="small text-muted">Menu général Darlink ERP</div>
        </div>
    </div>
    <div class="row row-cols-2 row-cols-md-3 row-cols-xl-5 g-3 darlink-launcher-grid">
        <?php foreach (($quickLinks ?? []) as $link): ?>
            <div class="col">
                <a
                    class="card darlink-launcher-card h-100 text-decoration-none"
                    href="index.php?page=<?= htmlspecialchars($link['page']) ?>"
                    aria-label="Ouvrir <?= htmlspecialchars($link['label']) ?>"
                >
                    <div class="card-body">
                        <div class="darlink-launcher-icon" aria-hidden="true">
                            <?php $icon = (string)($link['icon'] ?? 'bi bi-grid-3x3-gap-fill'); ?>
                            <?php if (str_starts_with($icon, 'bi ')): ?>
                                <i class="<?= htmlspecialchars($icon) ?>"></i>
                            <?php else: ?>
                                <?= htmlspecialchars($icon) ?>
                            <?php endif; ?>
                        </div>
                        <div class="darlink-launcher-title"><?= htmlspecialchars($link['label']) ?></div>
                        <div class="darlink-launcher-text"><?= htmlspecialchars($link['description']) ?></div>
                    </div>
                </a>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-12">
        <div class="darlink-card p-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">Alertes prioritaires</h5>
                <a href="index.php?page=stock_alerts" class="btn btn-sm btn-outline-secondary">Voir alertes stock</a>
            </div>
            <?php if (empty($overdueFactures) && empty($stockAlerts)): ?>
                <p class="text-muted mb-0">Aucune alerte prioritaire pour le moment.</p>
            <?php else: ?>
                <div class="list-group list-group-flush">
                    <?php foreach (array_slice($overdueFactures, 0, 4) as $facture): ?>
                        <a class="list-group-item list-group-item-action px-0" href="index.php?page=factures_fournisseurs_show&id=<?= (int)$facture['id'] ?>">
                            <div class="d-flex justify-content-between">
                                <strong class="text-danger">Facture fournisseur en retard</strong>
                                <span><?= $fmt($facture['reste_du'] ?? 0) ?></span>
                            </div>
                            <div class="small text-muted"><?= htmlspecialchars(($facture['fournisseur_nom'] ?? '') . ' — ' . ($facture['numero_facture_fournisseur'] ?? $facture['numero_interne'] ?? '')) ?></div>
                        </a>
                    <?php endforeach; ?>
                    <?php foreach (array_slice($stockAlerts ?? [], 0, 4) as $alert): ?>
                        <a class="list-group-item list-group-item-action px-0" href="index.php?page=stock_show&id=<?= (int)$alert['article_id'] ?>">
                            <div class="d-flex justify-content-between">
                                <strong class="<?= ($alert['etat_stock'] ?? '') === 'rupture' ? 'text-danger' : 'text-warning' ?>"><?= ($alert['etat_stock'] ?? '') === 'rupture' ? 'Rupture stock' : 'Stock bas' ?></strong>
                                <span><?= $qty($alert['quantite'] ?? 0) ?> / mini <?= $qty($alert['stock_minimum'] ?? 0) ?></span>
                            </div>
                            <div class="small text-muted"><?= htmlspecialchars(($alert['reference'] ?? '') . ' — ' . ($alert['designation'] ?? '')) ?></div>
                        </a>
                    <?php endforeach; ?>
                </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">Commandes fournisseurs récentes</h5>
                <a href="index.php?page=commandes_fournisseurs_dashboard" class="btn btn-sm btn-outline-primary">Tableau achats</a>
            </div>
            <?php if (empty($recentOrders)): ?>
                <p class="text-muted mb-0">Aucune commande fournisseur récente.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm align-middle">
                        <thead><tr><th>N°</th><th>Fournisseur</th><th>Statut</th><th class="text-end">TTC</th></tr></thead>
                        <tbody>
                        <?php foreach ($recentOrders as $order): ?>
                            <tr>
                                <td><a href="index.php?page=commandes_fournisseurs_show&id=<?= (int)$order['id'] ?>"><?= htmlspecialchars($order['numero'] ?? '') ?></a></td>
                                <td><?= htmlspecialchars($order['fournisseur_nom'] ?? '') ?></td>
                                <td><span class="badge text-bg-light"><?= htmlspecialchars($order['statut'] ?? '') ?></span></td>
                                <td class="text-end"><?= $fmt($order['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 fournisseurs à payer</h5>
                <a href="index.php?page=factures_fournisseurs_echeancier" class="btn btn-sm btn-outline-primary">Échéancier</a>
            </div>
            <?php if (empty($upcomingFactures)): ?>
                <p class="text-muted mb-0">Aucune facture fournisseur à venir.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm align-middle">
                        <thead><tr><th>Facture</th><th>Fournisseur</th><th>Échéance</th><th class="text-end">Reste dû</th></tr></thead>
                        <tbody>
                        <?php foreach ($upcomingFactures as $facture): ?>
                            <tr>
                                <td><a href="index.php?page=factures_fournisseurs_show&id=<?= (int)$facture['id'] ?>"><?= htmlspecialchars($facture['numero_facture_fournisseur'] ?? $facture['numero_interne'] ?? '') ?></a></td>
                                <td><?= htmlspecialchars($facture['fournisseur_nom'] ?? '') ?></td>
                                <td><?= htmlspecialchars($facture['date_echeance'] ?: 'Sans échéance') ?></td>
                                <td class="text-end"><?= $fmt($facture['reste_du'] ?? 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 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 class="text-end">TTC</th></tr></thead>
                        <tbody>
                        <?php foreach ($recentDocuments as $document): ?>
                            <tr>
                                <td><?= htmlspecialchars($document['type_document'] ?? '') ?></td>
                                <td><a href="index.php?page=documents_show&id=<?= (int)$document['id'] ?>"><?= htmlspecialchars($document['numero'] ?? '') ?></a></td>
                                <td><?= htmlspecialchars($document['date_document'] ?? '') ?></td>
                                <td class="text-end"><?= $fmt($document['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">Derniers mouvements stock</h5>
                <a href="index.php?page=stock_history" class="btn btn-sm btn-outline-secondary">Historique</a>
            </div>
            <?php if (empty($recentMovements)): ?>
                <p class="text-muted mb-0">Aucun mouvement de stock pour le moment.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm align-middle">
                        <thead><tr><th>Date</th><th>Article</th><th>Type</th><th class="text-end">Qté</th></tr></thead>
                        <tbody>
                        <?php foreach ($recentMovements as $movement): ?>
                            <tr>
                                <td><?= htmlspecialchars($movement['date_mouvement'] ?? '') ?></td>
                                <td><?= htmlspecialchars(trim(($movement['reference'] ?? '') . ' — ' . ($movement['designation'] ?? ''), ' —')) ?></td>
                                <td><span class="badge text-bg-light"><?= htmlspecialchars($movement['type_mouvement'] ?? '') ?></span></td>
                                <td class="text-end <?= (float)($movement['quantite'] ?? 0) < 0 ? 'text-danger' : 'text-success' ?>"><?= $qty($movement['quantite'] ?? 0) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
