<?php
$fmt = static fn($v): string => number_format((float)$v, 2, ',', ' ') . ' MAD';
$pct = static fn($v): string => number_format((float)$v, 2, ',', ' ') . ' %';
$kpis = $kpis ?? [];
$filters = $filters ?? [];
$devisStatus = $devisStatus ?? [];
$devisList = $devisList ?? [];
$devisRelance = $devisRelance ?? [];
$topClientsDevis = $topClientsDevis ?? [];
$clients = $clients ?? [];
$statuts = ['brouillon' => 'Brouillon', 'validé' => 'Validé', 'en attente' => 'En attente', 'accepté' => 'Accepté', 'transformé' => 'Transformé', 'refusé' => 'Refusé'];
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Analyse devis / transformation commerciale</h1>
        <p class="text-muted mb-0">Suivi des devis à transformer, potentiel commercial et relances — <?= htmlspecialchars($version ?? 'Phoenix P3.6.2') ?></p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=devis_create" class="btn btn-primary">+ Nouveau devis</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="devis_analysis">
    <div class="row g-2 align-items-end">
        <div class="col-md-3">
            <label class="form-label small text-muted">Statut</label>
            <select name="statut" class="form-select">
                <option value="">Tous les statuts</option>
                <?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">Devis total</div>
            <div class="h4 mb-1"><?= (int)($kpis['nb_total'] ?? 0) ?></div>
            <div class="small text-muted"><?= $fmt($kpis['total_ttc'] ?? 0) ?> TTC</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Potentiel à transformer</div>
            <div class="h4 mb-1 text-primary"><?= $fmt($kpis['potentiel_ttc'] ?? 0) ?></div>
            <div class="small text-muted"><?= (int)($kpis['nb_en_attente'] ?? 0) ?> devis en attente</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Taux de transformation</div>
            <div class="h4 mb-1 text-success"><?= $pct($kpis['taux_transformation'] ?? 0) ?></div>
            <div class="small text-muted">Acceptés + transformés</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Devis à relancer</div>
            <div class="h4 mb-1 text-danger"><?= count($devisRelance) ?></div>
            <div class="small text-muted">Validité dépassée ou ancien</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">Répartition 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 sur cette sélection.</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">Relances prioritaires</h5>
                <span class="badge text-bg-danger"><?= count($devisRelance) ?></span>
            </div>
            <?php if (empty($devisRelance)): ?>
                <p class="text-muted mb-0">Aucun devis prioritaire à relancer.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm align-middle">
                        <thead><tr><th>Devis</th><th>Client</th><th>Motif</th><th class="text-end">TTC</th></tr></thead>
                        <tbody>
                        <?php foreach ($devisRelance as $devis): ?>
                            <tr>
                                <td><a href="index.php?page=devis_show&id=<?= (int)$devis['id'] ?>"><?= htmlspecialchars((string)$devis['numero']) ?></a></td>
                                <td><?= htmlspecialchars((string)$devis['client_nom']) ?></td>
                                <td><span class="badge text-bg-warning"><?= htmlspecialchars((string)$devis['motif_relance']) ?></span></td>
                                <td class="text-end"><?= $fmt($devis['total_ttc'] ?? 0) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="darlink-card p-4 mb-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="mb-0">Devis analysés</h5>
        <span class="text-muted small">Limité aux 100 derniers résultats</span>
    </div>
    <?php if (empty($devisList)): ?>
        <p class="text-muted mb-0">Aucun devis trouvé.</p>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead>
                <tr>
                    <th>N°</th><th>Client</th><th>Date</th><th>Validité</th><th>Statut</th>
                    <th class="text-end">Total TTC</th><th class="text-end">Marge %</th><th class="text-end">Action</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($devisList as $devis): ?>
                    <tr>
                        <td><strong><?= htmlspecialchars((string)$devis['numero']) ?></strong></td>
                        <td><?= htmlspecialchars((string)$devis['client_nom']) ?></td>
                        <td><?= htmlspecialchars((string)$devis['date_devis']) ?></td>
                        <td><?= htmlspecialchars((string)($devis['validite'] ?: '-')) ?></td>
                        <td>
                            <span class="badge text-bg-light border"><?= htmlspecialchars((string)$devis['statut']) ?></span>
                            <?php if ((int)($devis['a_relancer'] ?? 0) === 1): ?>
                                <span class="badge text-bg-warning ms-1">À relancer</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end"><?= $fmt($devis['total_ttc'] ?? 0) ?></td>
                        <td class="text-end"><?= $pct($devis['marge_pourcentage'] ?? 0) ?></td>
                        <td class="text-end"><a class="btn btn-sm btn-outline-primary" href="index.php?page=devis_show&id=<?= (int)$devis['id'] ?>">Ouvrir</a></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<div class="darlink-card p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="mb-0">Top clients devis</h5>
        <span class="text-muted small">Classé par potentiel à transformer</span>
    </div>
    <?php if (empty($topClientsDevis)): ?>
        <p class="text-muted mb-0">Aucune donnée client.</p>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-sm align-middle">
                <thead><tr><th>Client</th><th class="text-end">Devis</th><th class="text-end">Potentiel TTC</th><th class="text-end">Total TTC</th></tr></thead>
                <tbody>
                <?php foreach ($topClientsDevis as $client): ?>
                    <tr>
                        <td><?= htmlspecialchars((string)$client['client_nom']) ?></td>
                        <td class="text-end"><?= (int)($client['nb_devis'] ?? 0) ?></td>
                        <td class="text-end text-primary"><strong><?= $fmt($client['potentiel_ttc'] ?? 0) ?></strong></td>
                        <td class="text-end"><?= $fmt($client['total_ttc'] ?? 0) ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>
