<?php
$query = http_build_query(array_filter($filters ?? [], static fn($v) => $v !== '' && $v !== 0 && $v !== 'tous'));
$totalActif = array_sum(array_map(static fn($e) => (int)$e['actif'] === 1 ? (float)$e['montant'] : 0.0, $encaissements));
$totalAnnule = array_sum(array_map(static fn($e) => (int)$e['actif'] === 0 ? (float)$e['montant'] : 0.0, $encaissements));
?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <div><h1 class="darlink-title mb-1"><i class="bi bi-journal-check me-2"></i>Journal des encaissements</h1><p class="text-muted mb-0"><?= count($encaissements) ?> mouvement(s) selon les filtres</p></div>
    <a href="index.php?page=encaissements_create" class="btn darlink-btn-primary"><i class="bi bi-plus-lg me-1"></i> Nouvel encaissement</a>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-3"><div class="darlink-stat"><span>Total actif filtré</span><strong class="text-success"><?= number_format($totalActif, 2, ',', ' ') ?> MAD</strong></div></div>
    <div class="col-md-3"><div class="darlink-stat"><span>Montants annulés</span><strong class="text-danger"><?= number_format($totalAnnule, 2, ',', ' ') ?> MAD</strong></div></div>
    <div class="col-md-3"><div class="darlink-stat"><span>Factures à encaisser</span><strong class="text-danger"><?= count($factures) ?></strong></div></div>
    <div class="col-md-3"><div class="darlink-stat"><span>Mouvements affichés</span><strong><?= count($encaissements) ?></strong></div></div>
</div>

<form method="get" action="index.php" class="darlink-card p-3 mb-4">
    <input type="hidden" name="page" value="encaissements">
    <div class="row g-3 align-items-end">
        <div class="col-lg-2"><label class="form-label">Du</label><input type="date" name="date_from" value="<?= htmlspecialchars($filters['date_from']) ?>" class="form-control"></div>
        <div class="col-lg-2"><label class="form-label">Au</label><input type="date" name="date_to" value="<?= htmlspecialchars($filters['date_to']) ?>" class="form-control"></div>
        <div class="col-lg-2"><label class="form-label">Client</label><select name="client_id" id="encaissements-client-filter" class="form-select"><option value="0">Tous</option><?php foreach ($clients as $client): ?><option value="<?= (int)$client['id'] ?>" <?= (int)$filters['client_id'] === (int)$client['id'] ? 'selected' : '' ?>><?= htmlspecialchars($client['raison_sociale']) ?></option><?php endforeach; ?></select></div>
        <div class="col-lg-2"><label class="form-label">Facture</label><input name="facture" value="<?= htmlspecialchars($filters['facture']) ?>" class="form-control" placeholder="N° facture"></div>
        <div class="col-lg-2"><label class="form-label">Mode</label><select name="mode" class="form-select"><option value="">Tous</option><?php foreach ($modesReglement as $mode): $label = $mode['libelle'] ?? ''; ?><option value="<?= htmlspecialchars($label) ?>" <?= $filters['mode'] === $label ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option><?php endforeach; ?></select></div>
        <div class="col-lg-2"><label class="form-label">Statut</label><select name="statut" class="form-select"><option value="tous" <?= $filters['statut']==='tous'?'selected':'' ?>>Tous</option><option value="actifs" <?= $filters['statut']==='actifs'?'selected':'' ?>>Actifs</option><option value="annules" <?= $filters['statut']==='annules'?'selected':'' ?>>Annulés</option></select></div>
        <div class="col-12 d-flex flex-wrap gap-2">
            <button class="btn darlink-btn-primary"><i class="bi bi-funnel me-1"></i>Filtrer</button>
            <a href="index.php?page=encaissements" class="btn btn-outline-secondary">Réinitialiser</a>
            <a href="index.php?page=encaissements_export<?= $query ? '&amp;'.htmlspecialchars($query) : '' ?>" class="btn btn-outline-success"><i class="bi bi-file-earmark-spreadsheet me-1"></i>Exporter CSV</a>
            <button type="button" onclick="window.print()" class="btn btn-outline-dark"><i class="bi bi-printer me-1"></i>Imprimer</button>
            <a id="encaissements-statement-link"
               href="<?= (int)$filters['client_id'] > 0 ? 'index.php?page=encaissements_statement&amp;client_id='.(int)$filters['client_id'].($filters['date_from'] ? '&amp;date_from='.urlencode($filters['date_from']) : '').($filters['date_to'] ? '&amp;date_to='.urlencode($filters['date_to']) : '') : '#' ?>"
               data-date-from="<?= htmlspecialchars($filters['date_from']) ?>"
               data-date-to="<?= htmlspecialchars($filters['date_to']) ?>"
               class="btn btn-outline-primary <?= (int)$filters['client_id'] > 0 ? '' : 'disabled' ?>"
               aria-disabled="<?= (int)$filters['client_id'] > 0 ? 'false' : 'true' ?>"
               title="<?= (int)$filters['client_id'] > 0 ? 'Ouvrir le relevé du client sélectionné' : 'Sélectionnez d’abord un client' ?>">
                <i class="bi bi-person-lines-fill me-1"></i>Relevé client
            </a>
        </div>
    </div>
</form>

<?php if ($modeTotals): ?><div class="darlink-card p-3 mb-4"><strong>Totaux actifs par mode :</strong><?php foreach ($modeTotals as $mode => $total): ?><span class="badge text-bg-light border ms-2"><?= htmlspecialchars($mode) ?> : <?= number_format($total, 2, ',', ' ') ?> MAD</span><?php endforeach; ?></div><?php endif; ?>

<div class="darlink-card darlink-table-card">
    <div class="table-responsive darlink-table-wrapper"><table id="encaissements-sortable" class="table align-middle darlink-table darlink-table-modern"><thead><tr><th data-sort-type="date"><button type="button" class="darlink-sort-button">Date <span class="sort-indicator" aria-hidden="true">↕</span></button></th><th data-sort-type="text"><button type="button" class="darlink-sort-button">Facture <span class="sort-indicator" aria-hidden="true">↕</span></button></th><th data-sort-type="text"><button type="button" class="darlink-sort-button">Client <span class="sort-indicator" aria-hidden="true">↕</span></button></th><th data-sort-type="text"><button type="button" class="darlink-sort-button">Mode <span class="sort-indicator" aria-hidden="true">↕</span></button></th><th data-sort-type="text"><button type="button" class="darlink-sort-button">Référence <span class="sort-indicator" aria-hidden="true">↕</span></button></th><th data-sort-type="text"><button type="button" class="darlink-sort-button">Statut <span class="sort-indicator" aria-hidden="true">↕</span></button></th><th data-sort-type="number" class="text-end"><button type="button" class="darlink-sort-button ms-auto">Montant <span class="sort-indicator" aria-hidden="true">↕</span></button></th><th class="text-end no-print">Actions</th></tr></thead><tbody>
    <?php if (!$encaissements): ?><tr><td colspan="8" class="text-center text-muted py-5">Aucun encaissement ne correspond aux filtres.</td></tr><?php endif; ?>
    <?php foreach ($encaissements as $e): ?><tr class="<?= (int)$e['actif']===0 ? 'table-light text-muted' : '' ?>">
        <td data-sort-value="<?= htmlspecialchars($e['date_encaissement']) ?>"><?= htmlspecialchars($e['date_encaissement']) ?></td><td data-sort-value="<?= htmlspecialchars($e['facture_numero']) ?>"><strong><?= htmlspecialchars($e['facture_numero']) ?></strong></td><td data-sort-value="<?= htmlspecialchars($e['client_nom']) ?>"><?= htmlspecialchars($e['client_nom']) ?></td><td data-sort-value="<?= htmlspecialchars($e['mode_reglement']) ?>"><?= htmlspecialchars($e['mode_reglement']) ?></td><td data-sort-value="<?= htmlspecialchars($e['reference_reglement'] ?? '') ?>"><?= htmlspecialchars($e['reference_reglement'] ?? '-') ?></td>
        <td data-sort-value="<?= (int)$e['actif']===1 ? 'Actif' : 'Annulé' ?>"><?php if ((int)$e['actif']===1): ?><span class="badge text-bg-success">Actif</span><?php else: ?><span class="badge text-bg-secondary">Annulé</span><?php endif; ?></td>
        <td data-sort-value="<?= (float)$e['montant'] ?>" class="text-end fw-semibold"><?= number_format((float)$e['montant'], 2, ',', ' ') ?> MAD</td><td class="text-end text-nowrap no-print"><a class="btn btn-sm btn-outline-secondary" href="index.php?page=encaissements_statement&amp;client_id=<?= (int)$e['client_id'] ?>"><i class="bi bi-person-lines-fill"></i> Relevé</a> <a class="btn btn-sm btn-outline-primary" href="index.php?page=encaissements_receipt&amp;id=<?= (int)$e['id'] ?>"><i class="bi bi-receipt"></i> Reçu</a><?php if ((int)$e['actif']===1): ?> <a class="btn btn-sm btn-outline-warning" href="index.php?page=encaissements_edit&amp;id=<?= (int)$e['id'] ?>">Modifier</a> <form method="post" action="index.php?page=encaissements_cancel" class="d-inline" onsubmit="return confirm('Annuler uniquement ce règlement ? La facture restera active et son reste dû sera recalculé.');"><input type="hidden" name="encaissement_id" value="<?= (int)$e['id'] ?>"><input type="hidden" name="return_to" value="encaissements"><button type="submit" class="btn btn-sm btn-outline-danger">Annuler le règlement</button></form><?php endif; ?></td>
    </tr><?php endforeach; ?></tbody></table></div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
    var clientSelect = document.getElementById('encaissements-client-filter');
    var statementLink = document.getElementById('encaissements-statement-link');
    if (!clientSelect || !statementLink) return;

    function refreshStatementLink() {
        var clientId = parseInt(clientSelect.value || '0', 10);
        if (clientId <= 0) {
            statementLink.href = '#';
            statementLink.classList.add('disabled');
            statementLink.setAttribute('aria-disabled', 'true');
            statementLink.title = 'Sélectionnez d’abord un client';
            return;
        }
        var url = 'index.php?page=encaissements_statement&client_id=' + encodeURIComponent(clientId);
        if (statementLink.dataset.dateFrom) url += '&date_from=' + encodeURIComponent(statementLink.dataset.dateFrom);
        if (statementLink.dataset.dateTo) url += '&date_to=' + encodeURIComponent(statementLink.dataset.dateTo);
        statementLink.href = url;
        statementLink.classList.remove('disabled');
        statementLink.setAttribute('aria-disabled', 'false');
        statementLink.title = 'Ouvrir le relevé du client sélectionné';
    }

    clientSelect.addEventListener('change', refreshStatementLink);
    refreshStatementLink();

    var table = document.getElementById('encaissements-sortable');
    if (!table || !table.tBodies.length) return;
    var headers = table.querySelectorAll('thead th[data-sort-type]');
    headers.forEach(function (header, columnIndex) {
        var button = header.querySelector('.darlink-sort-button');
        if (!button) return;
        button.addEventListener('click', function () {
            var direction = header.dataset.sortDirection === 'asc' ? 'desc' : 'asc';
            headers.forEach(function (other) {
                delete other.dataset.sortDirection;
                var indicator = other.querySelector('.sort-indicator');
                if (indicator) indicator.textContent = '↕';
                var otherButton = other.querySelector('.darlink-sort-button');
                if (otherButton) otherButton.removeAttribute('aria-sort');
            });
            header.dataset.sortDirection = direction;
            button.setAttribute('aria-sort', direction === 'asc' ? 'ascending' : 'descending');
            header.querySelector('.sort-indicator').textContent = direction === 'asc' ? '▲' : '▼';
            var rows = Array.from(table.tBodies[0].rows).filter(function (row) {
                return row.cells.length === table.tHead.rows[0].cells.length;
            });
            rows.sort(function (a, b) {
                var aValue = a.cells[columnIndex].dataset.sortValue || a.cells[columnIndex].textContent.trim();
                var bValue = b.cells[columnIndex].dataset.sortValue || b.cells[columnIndex].textContent.trim();
                var comparison;
                if (header.dataset.sortType === 'number') {
                    comparison = (parseFloat(aValue) || 0) - (parseFloat(bValue) || 0);
                } else if (header.dataset.sortType === 'date') {
                    comparison = new Date(aValue).getTime() - new Date(bValue).getTime();
                } else {
                    comparison = aValue.localeCompare(bValue, 'fr', {numeric: true, sensitivity: 'base'});
                }
                return direction === 'asc' ? comparison : -comparison;
            });
            rows.forEach(function (row) { table.tBodies[0].appendChild(row); });
        });
    });
});
</script>
<style>.darlink-sort-button{display:flex;align-items:center;gap:.35rem;width:100%;padding:0;border:0;background:transparent;color:inherit;font:inherit;font-weight:600;text-align:left;white-space:nowrap}.darlink-sort-button:hover{color:var(--bs-primary)}.sort-indicator{font-size:.72rem;opacity:.65}@media print{.darlink-sidebar,.darlink-topbar,.no-print,form,.btn{display:none!important}.darlink-sort-button{display:block}.sort-indicator{display:none}.darlink-main{margin:0!important}.darlink-card{box-shadow:none!important}}</style>
