<?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 ?? [];
$filters = $filters ?? [];
$clientsPerformance = $clientsPerformance ?? [];
$topClients = $topClients ?? array_slice($clientsPerformance, 0, 10);
$clientsDus = $clientsDus ?? [];
$clientsInactifs = $clientsInactifs ?? [];
$recentEncaissements = $recentEncaissements ?? [];
$clients = $clients ?? [];
$tris = [
    'ca' => 'Chiffre d’affaires',
    'reste' => 'Reste dû',
    'marge' => 'Marge',
    'documents' => 'Nombre de documents',
    'factures' => 'Nombre de factures',
    'devis' => 'Nombre de devis',
    'panier' => 'Panier moyen',
    'dernier' => 'Dernière activité',
];
$documentTypes = [
    'tous' => 'Devis + factures',
    'factures' => 'Factures uniquement',
    'devis' => 'Devis uniquement',
];
$clientStatuses = [
    '' => 'Tous les statuts',
    'tres_actif' => 'Très actif',
    'actif' => 'Actif',
    'peu_actif' => 'Peu actif',
    'inactif' => 'Inactif',
];
$statusBadge = static function (string $status): string {
    return match ($status) {
        'tres_actif' => 'text-bg-success',
        'actif' => 'text-bg-primary',
        'peu_actif' => 'text-bg-warning',
        'inactif' => 'text-bg-secondary',
        default => 'text-bg-light border',
    };
};
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Analyse clients / performance commerciale</h1>
        <p class="text-muted mb-0">CA par client, devis, factures, panier moyen, top clients et clients à relancer — <?= htmlspecialchars($version ?? 'Phoenix P3.6.5') ?></p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=dashboard_commercial" class="btn btn-outline-secondary">Dashboard commercial</a>
        <a href="index.php?page=clients" class="btn btn-primary">Clients</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">Clients actifs sur filtre</div>
            <div class="h4 mb-1"><?= $qty($kpis['nb_clients_actifs'] ?? 0) ?></div>
            <div class="small text-muted">sur <?= $qty($kpis['nb_clients_total'] ?? 0) ?> client(s) enregistrés</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">CA TTC clients</div>
            <div class="h4 mb-1"><?= $fmt($kpis['ca_ttc'] ?? 0) ?></div>
            <div class="small text-muted"><?= $fmt($kpis['ca_ht'] ?? 0) ?> HT</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Reste dû clients</div>
            <div class="h4 mb-1 text-danger"><?= $fmt($kpis['reste_du'] ?? 0) ?></div>
            <div class="small text-muted"><?= $qty($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">Panier moyen document</div>
            <div class="h4 mb-1"><?= $fmt($kpis['panier_moyen_ttc'] ?? 0) ?></div>
            <div class="small text-muted">Marge <?= $pct($kpis['marge_pourcentage'] ?? 0) ?></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">Documents commerciaux</div><div class="h5 mb-1"><?= $qty($kpis['nb_documents'] ?? 0) ?></div><div class="small text-muted"><?= $qty($kpis['nb_devis'] ?? 0) ?> devis / <?= $qty($kpis['nb_factures'] ?? 0) ?> factures</div></div></div>
    <div class="col-md-3"><div class="darlink-card p-3 h-100"><div class="text-muted small">CA facturé TTC</div><div class="h5 mb-1"><?= $fmt($kpis['ca_factures_ttc'] ?? 0) ?></div><div class="small text-muted">Factures uniquement</div></div></div>
    <div class="col-md-3"><div class="darlink-card p-3 h-100"><div class="text-muted small">Potentiel devis TTC</div><div class="h5 mb-1"><?= $fmt($kpis['ca_devis_ttc'] ?? 0) ?></div><div class="small text-muted">Devis uniquement</div></div></div>
    <div class="col-md-3"><div class="darlink-card p-3 h-100"><div class="text-muted small">Panier moyen client</div><div class="h5 mb-1"><?= $fmt($kpis['panier_moyen_client_ttc'] ?? 0) ?></div><div class="small text-muted">CA / clients actifs</div></div></div>
</div>

<form method="get" class="darlink-card p-3 mb-4">
    <input type="hidden" name="page" value="clients_analysis">
    <div class="row g-2 align-items-end">
        <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">
            <label class="form-label small text-muted">Documents</label>
            <select name="document_type" class="form-select">
                <?php foreach ($documentTypes as $value => $label): ?>
                    <option value="<?= htmlspecialchars($value) ?>" <?= (($filters['document_type'] ?? 'tous') === $value) ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label small text-muted">Statut client</label>
            <select name="client_status" class="form-select">
                <?php foreach ($clientStatuses as $value => $label): ?>
                    <option value="<?= htmlspecialchars($value) ?>" <?= (($filters['client_status'] ?? '') === $value) ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>
    <div class="row g-2 align-items-end mt-2">
        <div class="col-md-2">
            <label class="form-label small text-muted">Montant min.</label>
            <input type="text" name="amount_min" value="<?= htmlspecialchars((string)($filters['amount_min'] ?? '')) ?>" class="form-control" placeholder="0">
        </div>
        <div class="col-md-2">
            <label class="form-label small text-muted">Montant max.</label>
            <input type="text" name="amount_max" value="<?= htmlspecialchars((string)($filters['amount_max'] ?? '')) ?>" class="form-control" placeholder="ex. 5000">
        </div>
        <div class="col-md-3">
            <label class="form-label small text-muted">Trier par</label>
            <select name="tri" class="form-select">
                <?php foreach ($tris as $value => $label): ?>
                    <option value="<?= htmlspecialchars($value) ?>" <?= (($filters['tri'] ?? 'ca') === $value) ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-5 d-flex gap-2">
            <button class="btn btn-primary">Filtrer</button>
            <a href="index.php?page=clients_analysis" class="btn btn-outline-secondary">Réinitialiser</a>
        </div>
    </div>
</form>

<div class="darlink-card p-4 mb-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="mb-0">Performance clients</h5>
        <span class="badge text-bg-light border"><?= count($clientsPerformance) ?> résultat(s)</span>
    </div>
    <?php if (empty($clientsPerformance)): ?>
        <p class="text-muted mb-0">Aucune donnée client ne correspond aux filtres sélectionnés.</p>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead>
                    <tr>
                        <th>Client</th>
                        <th class="text-end">Docs</th>
                        <th class="text-end">Devis</th>
                        <th class="text-end">Factures</th>
                        <th class="text-end">CA TTC</th>
                        <th class="text-end">Part CA</th>
                        <th class="text-end">Marge</th>
                        <th class="text-end">Reste dû</th>
                        <th class="text-end">Panier moyen</th>
                        <th>Dernière activité</th>
                        <th>Statut</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($clientsPerformance as $row): ?>
                    <tr>
                        <td><strong><?= htmlspecialchars((string)$row['client_nom']) ?></strong></td>
                        <td class="text-end"><?= $qty($row['nb_documents'] ?? 0) ?></td>
                        <td class="text-end"><?= $qty($row['nb_devis'] ?? 0) ?></td>
                        <td class="text-end"><?= $qty($row['nb_factures'] ?? 0) ?></td>
                        <td class="text-end"><?= $fmt($row['ca_ttc'] ?? 0) ?></td>
                        <td class="text-end"><?= $pct($row['part_ca'] ?? 0) ?></td>
                        <td class="text-end"><?= $fmt($row['marge_ht'] ?? 0) ?><br><span class="small text-muted"><?= $pct($row['marge_pourcentage'] ?? 0) ?></span></td>
                        <td class="text-end <?= ((float)($row['reste_du'] ?? 0) > 0) ? 'text-danger' : 'text-muted' ?>"><strong><?= $fmt($row['reste_du'] ?? 0) ?></strong></td>
                        <td class="text-end"><?= $fmt($row['panier_moyen_ttc'] ?? 0) ?></td>
                        <td><?= htmlspecialchars((string)($row['derniere_activite'] ?? '')) ?></td>
                        <td><span class="badge <?= $statusBadge((string)($row['client_status'] ?? '')) ?>"><?= htmlspecialchars((string)($row['client_status_label'] ?? '')) ?></span></td>
                        <td class="text-end"><a class="btn btn-sm btn-outline-primary" href="index.php?page=clients_show&id=<?= (int)$row['client_id'] ?>">Voir</a></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</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 par chiffre d’affaires</h5>
                <span class="badge text-bg-light border">Top 10</span>
            </div>
            <?php if (empty($topClients)): ?>
                <p class="text-muted mb-0">Aucun top client à afficher.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm align-middle">
                        <thead><tr><th>#</th><th>Client</th><th class="text-end">CA TTC</th><th class="text-end">Documents</th><th class="text-end">Part</th></tr></thead>
                        <tbody>
                        <?php foreach ($topClients as $index => $row): ?>
                            <tr>
                                <td><?= (int)$index + 1 ?></td>
                                <td><a href="index.php?page=clients_show&id=<?= (int)$row['client_id'] ?>"><?= htmlspecialchars((string)$row['client_nom']) ?></a></td>
                                <td class="text-end"><strong><?= $fmt($row['ca_ttc'] ?? 0) ?></strong></td>
                                <td class="text-end"><?= $qty($row['nb_documents'] ?? 0) ?></td>
                                <td class="text-end"><?= $pct($row['part_ca'] ?? 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">Clients avec reste dû</h5>
                <span class="badge text-bg-danger"><?= count($clientsDus) ?></span>
            </div>
            <?php if (empty($clientsDus)): ?>
                <p class="text-muted mb-0">Aucun reste dû client sur les filtres sélectionnés.</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><th class="text-end">Retard</th><th>Échéance</th></tr></thead>
                        <tbody>
                        <?php foreach ($clientsDus as $row): ?>
                            <tr>
                                <td><a href="index.php?page=clients_show&id=<?= (int)$row['client_id'] ?>"><?= htmlspecialchars((string)$row['client_nom']) ?></a></td>
                                <td class="text-end"><?= $qty($row['nb_factures'] ?? 0) ?></td>
                                <td class="text-end text-danger"><strong><?= $fmt($row['reste_du'] ?? 0) ?></strong></td>
                                <td class="text-end"><?= $fmt($row['retard_ttc'] ?? 0) ?></td>
                                <td><?= htmlspecialchars((string)($row['prochaine_echeance'] ?: 'Sans échéance')) ?></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">Clients à relancer</h5>
                <span class="badge text-bg-light border"><?= count($clientsInactifs) ?></span>
            </div>
            <?php if (empty($clientsInactifs)): ?>
                <p class="text-muted mb-0">Aucun client inactif détecté.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm align-middle">
                        <thead><tr><th>Client</th><th>Dernière facture</th><th>Dernier devis</th><th class="text-end">CA historique</th><th>Action conseillée</th><th></th></tr></thead>
                        <tbody>
                        <?php foreach ($clientsInactifs as $row): ?>
                            <tr>
                                <td><?= htmlspecialchars((string)$row['client_nom']) ?></td>
                                <td><?= htmlspecialchars((string)($row['derniere_facture'] ?: 'Jamais facturé')) ?></td>
                                <td><?= htmlspecialchars((string)($row['dernier_devis'] ?: 'Aucun devis')) ?></td>
                                <td class="text-end"><?= $fmt($row['ca_ttc'] ?? 0) ?></td>
                                <td><?= htmlspecialchars((string)($row['action_conseillee'] ?? 'Relance commerciale')) ?></td>
                                <td class="text-end"><a class="btn btn-sm btn-outline-secondary" href="index.php?page=clients_show&id=<?= (int)$row['client_id'] ?>">Fiche</a></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-primary">Voir 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"><strong><?= $fmt($enc['montant'] ?? 0) ?></strong></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
