<?php
$formatMoney = static fn($value): string => number_format((float)$value, 2, ',', ' ') . ' DH';
$formatDate = static fn($value): string => !empty($value) ? date('d/m/Y', strtotime((string)$value)) : '-';
$statusLabels = [
    'non_reglee' => 'Non réglée',
    'partiellement_reglee' => 'Partiellement réglée',
    'reglee' => 'Réglée',
];
$etatLabels = [
    'en_retard' => ['label' => 'En retard', 'class' => 'bg-danger'],
    'sous_7_jours' => ['label' => 'À payer sous 7 jours', 'class' => 'bg-warning text-dark'],
    'sous_30_jours' => ['label' => 'À payer sous 30 jours', 'class' => 'bg-info text-dark'],
    'a_venir' => ['label' => 'À venir', 'class' => 'bg-secondary'],
    'sans_echeance' => ['label' => 'Sans échéance', 'class' => 'bg-dark'],
];
$periodeLabels = [
    'toutes' => 'Toutes les factures à payer',
    'retard' => 'En retard',
    '7_jours' => 'À payer sous 7 jours',
    '30_jours' => 'À payer sous 30 jours',
    'sans_echeance' => 'Sans échéance',
];
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Échéancier fournisseurs</h1>
        <p class="text-muted mb-0">Factures fournisseurs à payer, retards et paiements à venir.</p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=factures_fournisseurs" class="btn btn-outline-primary" role="button">Factures fournisseurs</a>
        <a href="index.php?page=commandes_fournisseurs_dashboard" class="btn btn-primary" role="button">Tableau de bord achats</a>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted">Total à payer</div>
            <div class="h4 mb-0"><?= $formatMoney($stats['total_reste_du'] ?? 0) ?></div>
            <small class="text-muted"><?= (int)($stats['nb_factures'] ?? 0) ?> facture(s)</small>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted">En retard</div>
            <div class="h4 mb-0"><?= $formatMoney($stats['total_retard'] ?? 0) ?></div>
            <small class="text-muted"><?= (int)($stats['nb_retard'] ?? 0) ?> facture(s)</small>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted">Sous 7 jours</div>
            <div class="h4 mb-0"><?= $formatMoney($stats['total_7_jours'] ?? 0) ?></div>
            <small class="text-muted">À régler rapidement</small>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted">Sans échéance</div>
            <div class="h4 mb-0"><?= $formatMoney($stats['total_sans_echeance'] ?? 0) ?></div>
            <small class="text-muted">À contrôler</small>
        </div>
    </div>
</div>

<div class="darlink-card p-4 mb-3">
    <form method="get" class="row g-2 align-items-end">
        <input type="hidden" name="page" value="factures_fournisseurs_echeancier">
        <div class="col-md-3">
            <label class="form-label">Fournisseur</label>
            <select name="fournisseur_id" class="form-select">
                <option value="0">Tous</option>
                <?php foreach ($fournisseurs as $fournisseur): ?>
                    <option value="<?= (int)$fournisseur['id'] ?>" <?= (int)($filters['fournisseur_id'] ?? 0) === (int)$fournisseur['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($fournisseur['raison_sociale']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label">Période</label>
            <select name="periode" class="form-select">
                <?php foreach ($periodeLabels as $key => $label): ?>
                    <option value="<?= htmlspecialchars($key) ?>" <?= ($filters['periode'] ?? 'toutes') === $key ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label">Du</label>
            <input type="date" name="date_debut" class="form-control" value="<?= htmlspecialchars($filters['date_debut'] ?? '') ?>">
        </div>
        <div class="col-md-2">
            <label class="form-label">Au</label>
            <input type="date" name="date_fin" class="form-control" value="<?= htmlspecialchars($filters['date_fin'] ?? '') ?>">
        </div>
        <div class="col-md-2">
            <button class="btn btn-outline-primary w-100">Filtrer</button>
        </div>
    </form>
</div>

<div class="darlink-card p-4">
    <div class="table-responsive">
        <table class="table darlink-table align-middle">
            <thead>
            <tr>
                <th>Échéance</th>
                <th>État</th>
                <th>Facture</th>
                <th>Fournisseur</th>
                <th>Commande</th>
                <th class="text-end">TTC</th>
                <th class="text-end">Réglé</th>
                <th class="text-end">Reste dû</th>
                <th>Statut</th>
                <th class="text-end">Action</th>
            </tr>
            </thead>
            <tbody>
            <?php if (empty($factures)): ?>
                <tr><td colspan="10" class="text-center text-muted py-4">Aucune facture fournisseur à payer pour ce filtre.</td></tr>
            <?php endif; ?>
            <?php foreach ($factures as $facture): ?>
                <?php $etat = $etatLabels[$facture['etat_echeance'] ?? 'a_venir'] ?? $etatLabels['a_venir']; ?>
                <tr>
                    <td>
                        <strong><?= htmlspecialchars($formatDate($facture['date_echeance'] ?? null)) ?></strong>
                        <?php if (isset($facture['jours_ecart'])): ?>
                            <br><span class="text-muted"><?= (int)$facture['jours_ecart'] ?> jour(s)</span>
                        <?php endif; ?>
                    </td>
                    <td><span class="badge <?= htmlspecialchars($etat['class']) ?>"><?= htmlspecialchars($etat['label']) ?></span></td>
                    <td>
                        <strong><?= htmlspecialchars($facture['numero_interne']) ?></strong><br>
                        <span class="text-muted"><?= htmlspecialchars($facture['numero_facture_fournisseur']) ?></span>
                    </td>
                    <td><?= htmlspecialchars($facture['fournisseur_nom']) ?></td>
                    <td><?= htmlspecialchars($facture['commande_numero'] ?: '-') ?></td>
                    <td class="text-end"><?= $formatMoney($facture['montant_ttc']) ?></td>
                    <td class="text-end"><?= $formatMoney($facture['montant_regle']) ?></td>
                    <td class="text-end"><strong><?= $formatMoney($facture['reste_du']) ?></strong></td>
                    <td><?= htmlspecialchars($statusLabels[$facture['statut']] ?? $facture['statut']) ?></td>
                    <td class="text-end">
                        <div class="d-flex justify-content-end gap-1">
                            <a href="index.php?page=factures_fournisseurs_show&id=<?= (int)$facture['id'] ?>" class="btn btn-sm btn-outline-primary">Ouvrir</a>
                            <a href="index.php?page=factures_fournisseurs_reglement&id=<?= (int)$facture['id'] ?>" class="btn btn-sm btn-success">Régler</a>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
