<?php
$fmt = static fn($v): string => number_format((float)$v, 2, ',', ' ') . ' MAD';
$qty = static fn($v): string => number_format((float)$v, 0, ',', ' ');
$filters = $filters ?? [];
$kpis = $kpis ?? [];
$actions = $actions ?? [];
$clients = $clients ?? [];
$priorities = ['' => 'Toutes priorités', 'haute' => 'Haute', 'moyenne' => 'Moyenne', 'basse' => 'Basse'];
$actionTypes = ['' => 'Tous types', 'impaye' => 'Relance règlement', 'devis' => 'Relance devis', 'reactivation' => 'Réactivation client', 'premier_contact' => 'Premier contact'];
$priorityBadge = static function (string $priority): string {
    return match ($priority) {
        'haute' => 'text-bg-danger',
        'moyenne' => 'text-bg-warning',
        'basse' => 'text-bg-secondary',
        default => 'text-bg-light border',
    };
};
$typeBadge = static function (string $type): string {
    return match ($type) {
        'impaye' => 'text-bg-danger',
        'devis' => 'text-bg-primary',
        'reactivation' => 'text-bg-success',
        'premier_contact' => 'text-bg-info',
        default => 'text-bg-light border',
    };
};
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Actions commerciales / relances clients</h1>
        <p class="text-muted mb-0">Liste priorisée des clients à contacter : impayés, devis ouverts, réactivation et premiers contacts — <?= htmlspecialchars($version ?? 'Phoenix P3.6.6') ?></p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=clients_analysis" class="btn btn-outline-secondary">Analyse clients</a>
        <a href="index.php?page=dashboard_commercial" class="btn btn-primary">Dashboard commercial</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">Actions à traiter</div><div class="h4 mb-1"><?= $qty($kpis['nb_actions'] ?? 0) ?></div><div class="small text-muted"><?= $qty($kpis['priorite_haute'] ?? 0) ?> haute priorité</div></div></div>
    <div class="col-md-3"><div class="darlink-card p-3 h-100"><div class="text-muted small">Montant en retard</div><div class="h4 mb-1 text-danger"><?= $fmt($kpis['total_retard'] ?? 0) ?></div><div class="small text-muted">Relances règlement</div></div></div>
    <div class="col-md-3"><div class="darlink-card p-3 h-100"><div class="text-muted small">Devis ouverts</div><div class="h4 mb-1"><?= $fmt($kpis['total_devis_ouverts'] ?? 0) ?></div><div class="small text-muted">Potentiel commercial à relancer</div></div></div>
    <div class="col-md-3"><div class="darlink-card p-3 h-100"><div class="text-muted small">Fiches sans contact</div><div class="h4 mb-1"><?= $qty($kpis['clients_sans_contact'] ?? 0) ?></div><div class="small text-muted">Email ou téléphone manquant</div></div></div>
</div>

<form method="get" class="darlink-card p-3 mb-4">
    <input type="hidden" name="page" value="commercial_actions">
    <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">Priorité</label>
            <select name="priority" class="form-select">
                <?php foreach ($priorities as $value => $label): ?>
                    <option value="<?= htmlspecialchars($value) ?>" <?= (($filters['priority'] ?? '') === $value) ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label small text-muted">Type d’action</label>
            <select name="action_type" class="form-select">
                <?php foreach ($actionTypes as $value => $label): ?>
                    <option value="<?= htmlspecialchars($value) ?>" <?= (($filters['action_type'] ?? '') === $value) ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label small text-muted">Inactivité après</label>
            <input type="number" min="30" max="730" name="days_inactive" value="<?= (int)($filters['days_inactive'] ?? 180) ?>" class="form-control">
        </div>
        <div class="col-md-2">
            <label class="form-label small text-muted">Contact</label>
            <div class="form-check mt-2">
                <input class="form-check-input" type="checkbox" name="with_contact_only" value="1" id="withContact" <?= !empty($filters['with_contact_only']) ? 'checked' : '' ?>>
                <label class="form-check-label" for="withContact">Avec contact seulement</label>
            </div>
        </div>
    </div>
    <div class="mt-3 d-flex gap-2">
        <button class="btn btn-primary">Filtrer</button>
        <a href="index.php?page=commercial_actions" class="btn btn-outline-secondary">Réinitialiser</a>
        <button type="button" onclick="window.print()" class="btn btn-outline-dark">Imprimer la liste</button>
    </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">Plan d’actions commerciales</h5>
        <span class="badge text-bg-light border"><?= count($actions) ?> résultat(s)</span>
    </div>
    <?php if (empty($actions)): ?>
        <p class="text-muted mb-0">Aucune action commerciale ne correspond aux filtres sélectionnés.</p>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead>
                    <tr>
                        <th>Priorité</th>
                        <th>Client</th>
                        <th>Contact</th>
                        <th>Action</th>
                        <th class="text-end">Retard</th>
                        <th class="text-end">Devis ouverts</th>
                        <th class="text-end">CA client</th>
                        <th>Dernière activité</th>
                        <th>Message conseillé</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($actions as $row): ?>
                    <tr>
                        <td><span class="badge <?= $priorityBadge((string)($row['priority'] ?? '')) ?>"><?= htmlspecialchars((string)($row['priority_label'] ?? '')) ?></span></td>
                        <td><strong><?= htmlspecialchars((string)$row['client_nom']) ?></strong></td>
                        <td class="small">
                            <?php if (!empty($row['telephone'])): ?><div>☎ <?= htmlspecialchars((string)$row['telephone']) ?></div><?php endif; ?>
                            <?php if (!empty($row['email'])): ?><div>✉ <?= htmlspecialchars((string)$row['email']) ?></div><?php endif; ?>
                            <?php if (empty($row['telephone']) && empty($row['email'])): ?><span class="text-danger">Contact à compléter</span><?php endif; ?>
                        </td>
                        <td><span class="badge <?= $typeBadge((string)($row['action_type'] ?? '')) ?>"><?= htmlspecialchars((string)($row['action_label'] ?? '')) ?></span></td>
                        <td class="text-end text-danger"><strong><?= $fmt($row['retard_ttc'] ?? 0) ?></strong></td>
                        <td class="text-end"><?= $qty($row['nb_devis_ouverts'] ?? 0) ?><br><span class="small text-muted"><?= $fmt($row['montant_devis_ouverts'] ?? 0) ?></span></td>
                        <td class="text-end"><?= $fmt($row['ca_ttc'] ?? 0) ?></td>
                        <td><?= htmlspecialchars((string)($row['derniere_activite'] ?? '')) ?></td>
                        <td class="small"><?= htmlspecialchars((string)($row['message_suggere'] ?? '')) ?></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="alert alert-info">
    <strong>Conseil d’utilisation :</strong> traiter d’abord les priorités hautes, puis les devis ouverts. La liste est imprimable pour préparer les appels ou les relances de la journée.
</div>
