<?php
$fmt = static fn($v): string => number_format((float)$v, 2, ',', ' ') . ' MAD';
$kpis = $kpis ?? [];
$filters = $filters ?? [];
$factures = $factures ?? [];
$enRetard = $enRetard ?? [];
$topClientsDus = $topClientsDus ?? [];
$recentEncaissements = $recentEncaissements ?? [];
$clients = $clients ?? [];
$statuts = [
    '' => 'Tous les statuts',
    'non_reglee' => 'Non réglées',
    'partielle' => 'Partiellement réglées',
    'reglee' => 'Réglées',
    'en_retard' => 'En retard',
];
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Suivi factures clients / encaissements</h1>
        <p class="text-muted mb-0">Factures à encaisser, retards, reste dû et derniers règlements — <?= htmlspecialchars($version ?? 'Phoenix P3.6.3') ?></p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=encaissements_create" class="btn btn-success">+ Encaisser</a>
        <a href="index.php?page=dashboard_commercial" class="btn btn-outline-secondary">Tableau commercial</a>
    </div>
</div>

<form method="get" class="darlink-card p-3 mb-4">
    <input type="hidden" name="page" value="factures_clients_suivi">
    <div class="row g-2 align-items-end">
        <div class="col-md-3">
            <label class="form-label small text-muted">Statut règlement</label>
            <select name="statut" class="form-select">
                <?php foreach ($statuts as $value => $label): ?>
                    <option value="<?= htmlspecialchars($value) ?>" <?= (($filters['statut'] ?? '') === $value) ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label small text-muted">Client</label>
            <select name="client_id" class="form-select">
                <option value="0">Tous les clients</option>
                <?php foreach ($clients as $client): ?>
                    <option value="<?= (int)$client['id'] ?>" <?= ((int)($filters['client_id'] ?? 0) === (int)$client['id']) ? 'selected' : '' ?>><?= htmlspecialchars((string)$client['raison_sociale']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label small text-muted">Du</label>
            <input type="date" name="date_from" value="<?= htmlspecialchars((string)($filters['date_from'] ?? '')) ?>" class="form-control">
        </div>
        <div class="col-md-2">
            <label class="form-label small text-muted">Au</label>
            <input type="date" name="date_to" value="<?= htmlspecialchars((string)($filters['date_to'] ?? '')) ?>" class="form-control">
        </div>
        <div class="col-md-2 d-grid">
            <button class="btn btn-dark">Filtrer</button>
        </div>
    </div>
</form>

<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">Total facturé TTC</div><div class="h4 mb-1"><?= $fmt($kpis['total_ttc'] ?? 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">Total encaissé</div><div class="h4 mb-1 text-success"><?= $fmt($kpis['total_regle'] ?? 0) ?></div><div class="small text-muted">dont <?= $fmt($kpis['encaisse_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">Reste à encaisser</div><div class="h4 mb-1 text-danger"><?= $fmt($kpis['reste_a_encaisser'] ?? 0) ?></div><div class="small text-muted"><?= (int)($kpis['nb_non_reglees'] ?? 0) ?> non réglée(s), <?= (int)($kpis['nb_partielles'] ?? 0) ?> partielle(s)</div></div></div>
    <div class="col-md-3"><div class="darlink-card p-3 h-100"><div class="text-muted small">Factures en retard</div><div class="h4 mb-1 text-warning"><?= (int)($kpis['nb_retard'] ?? 0) ?></div><div class="small text-muted"><?= $fmt($kpis['retard_ttc'] ?? 0) ?> en retard</div></div></div>
</div>

<div class="row g-3 mb-4">
    <div class="col-lg-7">
        <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 clients à suivre</h5>
                <a href="index.php?page=factures" class="btn btn-sm btn-outline-primary">Voir factures</a>
            </div>
            <?php if (empty($factures)): ?>
                <p class="text-muted mb-0">Aucune facture trouvée.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead><tr><th>Facture</th><th>Client</th><th>Date</th><th>Échéance</th><th>Statut</th><th class="text-end">TTC</th><th class="text-end">Reste</th><th></th></tr></thead>
                        <tbody>
                        <?php foreach ($factures as $facture): ?>
                            <tr>
                                <td><a href="index.php?page=factures_show&id=<?= (int)$facture['id'] ?>"><strong><?= htmlspecialchars((string)$facture['numero']) ?></strong></a></td>
                                <td><?= htmlspecialchars((string)$facture['client_nom']) ?></td>
                                <td><?= htmlspecialchars((string)$facture['date_facture']) ?></td>
                                <td><?= htmlspecialchars((string)($facture['date_echeance'] ?: 'Sans échéance')) ?></td>
                                <td>
                                    <span class="badge text-bg-light border"><?= htmlspecialchars((string)$facture['statut_reglement']) ?></span>
                                    <?php if ((int)($facture['en_retard'] ?? 0) === 1): ?>
                                        <span class="badge text-bg-warning ms-1">Retard <?= (int)($facture['jours_retard'] ?? 0) ?> j</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-end"><?= $fmt($facture['total_ttc'] ?? 0) ?></td>
                                <td class="text-end text-danger"><strong><?= $fmt($facture['reste_du'] ?? 0) ?></strong></td>
                                <td class="text-end">
                                    <?php if ((float)($facture['reste_du'] ?? 0) > 0): ?>
                                        <a class="btn btn-sm btn-outline-success" href="index.php?page=encaissements_create&facture_id=<?= (int)$facture['id'] ?>">Encaisser</a>
                                    <?php else: ?>
                                        <a class="btn btn-sm btn-outline-secondary" href="index.php?page=factures_show&id=<?= (int)$facture['id'] ?>">Voir</a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div class="text-muted small">Limité aux 150 résultats les plus importants.</div>
            <?php endif; ?>
        </div>
    </div>

    <div class="col-lg-5">
        <div class="darlink-card p-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">Retards prioritaires</h5>
                <span class="badge text-bg-warning"><?= count($enRetard) ?></span>
            </div>
            <?php if (empty($enRetard)): ?>
                <p class="text-muted mb-0">Aucune facture client en retard.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm align-middle">
                        <thead><tr><th>Facture</th><th>Client</th><th class="text-end">Retard</th><th class="text-end">Reste</th></tr></thead>
                        <tbody>
                        <?php foreach ($enRetard 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 class="text-end"><?= (int)($facture['jours_retard'] ?? 0) ?> j</td>
                                <td class="text-end text-danger"><strong><?= $fmt($facture['reste_du'] ?? 0) ?></strong></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">
            <h5 class="mb-3">Top clients à encaisser</h5>
            <?php if (empty($topClientsDus)): ?>
                <p class="text-muted mb-0">Aucun reste dû client.</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">Reste dû</th></tr></thead>
                        <tbody>
                        <?php foreach ($topClientsDus as $client): ?>
                            <tr><td><?= htmlspecialchars((string)$client['client_nom']) ?></td><td class="text-end"><?= (int)$client['nb_factures'] ?></td><td class="text-end text-danger"><strong><?= $fmt($client['reste_du'] ?? 0) ?></strong></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 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>
