<?php
$money = static fn($value): string => number_format((float)$value, 2, ',', ' ') . ' DH';
$qty = static fn($value): string => number_format((float)$value, 0, ',', ' ');
$stateLabels = [
    'attente_reception' => ['Réception attendue', 'warning'],
    'a_facturer' => ['À facturer', 'primary'],
    'avec_ecart' => ['Écart à contrôler', 'danger'],
    'finalise' => ['Finalisé', 'success'],
];
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Finalisation du cycle fournisseurs</h1>
        <p class="text-muted mb-0">Rapprochement Commande / Réceptions / Facture.</p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=commandes_fournisseurs_dashboard" class="btn btn-primary">Tableau de bord achats</a>
        <a href="index.php?page=factures_fournisseurs" class="btn btn-outline-primary">Factures fournisseurs</a>
    </div>
</div>

<div class="row g-3 mb-4">
    <?php foreach ([
        ['Commandes affichées', $stats['total'], 'secondary'],
        ['Réceptions attendues', $stats['attente_reception'], 'warning'],
        ['À facturer', $stats['a_facturer'], 'primary'],
        ['Écarts', $stats['avec_ecart'], 'danger'],
        ['Cycles finalisés', $stats['finalises'], 'success'],
    ] as [$label, $value, $color]): ?>
        <div class="col">
            <div class="darlink-card p-3 h-100 border-start border-4 border-<?= $color ?>">
                <div class="text-muted small"><?= htmlspecialchars($label) ?></div>
                <div class="h3 mb-0"><?= (int)$value ?></div>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<div class="darlink-card p-4 mb-4">
    <form method="get" class="row g-3 align-items-end">
        <input type="hidden" name="page" value="commandes_fournisseurs_finalisation">
        <div class="col-md-4">
            <label class="form-label">Recherche</label>
            <input class="form-control" name="q" value="<?= htmlspecialchars($filters['q']) ?>" placeholder="Commande, fournisseur, facture…">
        </div>
        <div class="col-md-3">
            <label class="form-label">Fournisseur</label>
            <select class="form-select" name="fournisseur_id">
                <option value="0">Tous les fournisseurs</option>
                <?php foreach ($fournisseurs as $fournisseur): ?>
                    <option value="<?= (int)$fournisseur['id'] ?>" <?= (int)$filters['fournisseur_id'] === (int)$fournisseur['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($fournisseur['raison_sociale']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label">État du cycle</label>
            <select class="form-select" name="etat">
                <option value="">Tous les états</option>
                <?php foreach ($stateLabels as $value => [$label]): ?>
                    <option value="<?= $value ?>" <?= $filters['etat'] === $value ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-2 d-flex gap-2">
            <button class="btn btn-primary flex-fill">Filtrer</button>
            <a class="btn btn-outline-secondary" href="index.php?page=commandes_fournisseurs_finalisation">Effacer</a>
        </div>
    </form>
</div>

<div class="darlink-card p-4">
    <div class="table-responsive">
        <table class="table table-hover align-middle darlink-table finalisation-fournisseurs-table">
            <colgroup>
                <col>
                <col>
                <col>
                <col class="col-qty">
                <col class="col-qty">
                <col class="col-qty">
                <col class="col-money">
                <col class="col-money">
                <col class="col-money">
                <col class="col-money">
                <col>
            </colgroup>
            <thead>
            <tr>
                <th>Commande</th>
                <th>Fournisseur</th>
                <th>État</th>
                <th class="text-end"><span class="d-inline-block lh-sm">Qté<br>commandée</span></th>
                <th class="text-end">Qté reçue</th>
                <th class="text-end">Reste</th>
                <th class="text-end"><span class="d-inline-block lh-sm">Commande<br>TTC</span></th>
                <th class="text-end"><span class="d-inline-block lh-sm">Réception<br>TTC</span></th>
                <th class="text-end">Facture TTC</th>
                <th class="text-end">Écart</th>
                <th data-no-sort="true">Actions</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($rows as $row): ?>
                <?php [$label, $color] = $stateLabels[$row['etat_cycle']]; ?>
                <tr>
                    <td data-sort-value="<?= htmlspecialchars($row['date_commande']) ?>">
                        <strong><?= htmlspecialchars($row['numero']) ?></strong><br>
                        <small class="text-muted"><?= date('d/m/Y', strtotime($row['date_commande'])) ?></small>
                    </td>
                    <td><?= htmlspecialchars($row['fournisseur_nom']) ?></td>
                    <td><span class="badge text-bg-<?= $color ?>"><?= htmlspecialchars($label) ?></span></td>
                    <td class="text-end" data-sort-value="<?= (float)$row['quantite_commandee'] ?>"><?= $qty($row['quantite_commandee']) ?></td>
                    <td class="text-end" data-sort-value="<?= (float)$row['quantite_recue'] ?>"><?= $qty($row['quantite_recue']) ?></td>
                    <td class="text-end" data-sort-value="<?= (float)$row['quantite_restante'] ?>"><?= $qty($row['quantite_restante']) ?></td>
                    <td class="text-end" data-sort-value="<?= (float)$row['montant_commande_ttc'] ?>"><?= $money($row['montant_commande_ttc']) ?></td>
                    <td class="text-end" data-sort-value="<?= (float)$row['montant_recu_ttc'] ?>"><?= $money($row['montant_recu_ttc']) ?></td>
                    <td class="text-end" data-sort-value="<?= (float)$row['montant_facture_ttc'] ?>">
                        <?= (int)$row['nb_factures'] > 0 ? $money($row['montant_facture_ttc']) : '—' ?>
                    </td>
                    <td class="text-end <?= abs((float)$row['ecart_facture_commande']) > 0.01 ? 'text-danger fw-bold' : '' ?>" data-sort-value="<?= (float)$row['ecart_facture_commande'] ?>">
                        <?= (int)$row['nb_factures'] > 0 ? $money($row['ecart_facture_commande']) : '—' ?>
                    </td>
                    <td>
                        <div class="d-flex flex-wrap gap-1">
                            <a class="btn btn-sm btn-outline-secondary" href="index.php?page=commandes_fournisseurs_show&id=<?= (int)$row['id'] ?>">Commande</a>
                            <?php if ($row['etat_cycle'] === 'attente_reception'): ?>
                                <a class="btn btn-sm btn-success" href="index.php?page=commandes_fournisseurs_receive&id=<?= (int)$row['id'] ?>">Réceptionner</a>
                            <?php elseif ($row['etat_cycle'] === 'a_facturer'): ?>
                                <form method="get" action="index.php" class="d-inline">
                                    <input type="hidden" name="page" value="factures_fournisseurs_create">
                                    <input type="hidden" name="commande_id" value="<?= (int)$row['id'] ?>">
                                    <button
                                        type="submit"
                                        class="btn btn-sm btn-primary text-nowrap"
                                        title="Enregistrer la facture fournisseur"
                                        aria-label="Enregistrer la facture fournisseur"
                                    >Enregistrer la facture</button>
                                </form>
                            <?php elseif (!empty($row['facture_id'])): ?>
                                <a class="btn btn-sm btn-outline-primary" href="index.php?page=factures_fournisseurs_show&id=<?= (int)$row['facture_id'] ?>">Facture</a>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$rows): ?>
                <tr><td colspan="11" class="text-center text-muted py-4">Aucun cycle fournisseur ne correspond aux filtres.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<style>
.finalisation-fournisseurs-table {
    min-width: 1120px;
    table-layout: auto;
}
.finalisation-fournisseurs-table .col-qty {
    width: 6.5rem;
}
.finalisation-fournisseurs-table .col-money {
    width: 7.5rem;
}
.finalisation-fournisseurs-table th,
.finalisation-fournisseurs-table td {
    padding-left: .45rem;
    padding-right: .45rem;
}
.finalisation-fournisseurs-table th.text-end,
.finalisation-fournisseurs-table td.text-end {
    white-space: nowrap;
}
</style>
