<?php
$total = array_sum(array_map(static fn($e)=>(int)$e['actif']===1?(float)$e['montant']:0.0,$encaissements));
$formatDateFr = static function ($date): string {
    $date = trim((string)$date);
    if ($date === '') {
        return '';
    }

    $timestamp = strtotime($date);
    return $timestamp === false ? $date : date('d/m/Y', $timestamp);
};
?>
<div class="d-flex justify-content-between mb-4 no-print"><a href="index.php?page=encaissements&amp;client_id=<?= (int)$client['id'] ?>" class="btn btn-outline-secondary">← Journal</a><button onclick="window.print()" class="btn darlink-btn-primary"><i class="bi bi-printer me-1"></i>Imprimer le relevé</button></div>
<div class="darlink-card p-4">
<div class="d-flex justify-content-between border-bottom pb-3 mb-4"><div><h1 class="h3 mb-1">Relevé client</h1><strong><?= htmlspecialchars($client['raison_sociale']) ?></strong><div class="text-muted"><?= htmlspecialchars(trim(($client['code_client']??'').' · '.($client['adresse']??'').' '.($client['code_postal']??'').' '.($client['ville']??''))) ?></div></div><div class="text-end"><div>Édité le <?= date('d/m/Y') ?></div><div class="text-muted"><?= $filters['date_from'] ? 'Du '.htmlspecialchars($formatDateFr($filters['date_from'])) : 'Depuis l’origine' ?><?= $filters['date_to'] ? ' au '.htmlspecialchars($formatDateFr($filters['date_to'])) : '' ?></div></div></div>
<div class="row g-3 mb-4"><div class="col-md-3"><div class="border rounded p-3"><small>Total facturé</small><div class="h5 mb-0"><?= number_format((float)$client['total_facture'],2,',',' ') ?> MAD</div></div></div><div class="col-md-3"><div class="border rounded p-3"><small>Total réglé global</small><div class="h5 text-success mb-0"><?= number_format((float)$client['total_regle'],2,',',' ') ?> MAD</div></div></div><div class="col-md-3"><div class="border rounded p-3"><small>Reste dû</small><div class="h5 text-danger mb-0"><?= number_format((float)$client['reste_du'],2,',',' ') ?> MAD</div></div></div><div class="col-md-3"><div class="border rounded p-3"><small>Encaissé sur période</small><div class="h5 mb-0"><?= number_format($total,2,',',' ') ?> MAD</div></div></div></div>
<table id="statement-sortable" class="table align-middle"><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">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></tr></thead><tbody><?php if(!$encaissements):?><tr><td colspan="6" class="text-center text-muted py-4">Aucun mouvement sur cette période.</td></tr><?php endif;?><?php foreach($encaissements as $e):?><tr><td data-sort-value="<?=htmlspecialchars($e['date_encaissement'])?>"><?=htmlspecialchars($formatDateFr($e['date_encaissement']))?></td><td data-sort-value="<?=htmlspecialchars($e['facture_numero'])?>"><?=htmlspecialchars($e['facture_numero'])?></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é' ?>"><?= (int)$e['actif']===1?'Actif':'Annulé' ?></td><td data-sort-value="<?=(float)$e['montant']?>" class="text-end"><?=number_format((float)$e['montant'],2,',',' ')?> MAD</td></tr><?php endforeach;?></tbody><tfoot><tr><th colspan="5" class="text-end">Total actif de la période</th><th class="text-end"><?=number_format($total,2,',',' ')?> MAD</th></tr></tfoot></table>
<?php if($modeTotals):?><div class="mt-3"><strong>Ventilation :</strong><?php foreach($modeTotals as $mode=>$amount):?><span class="ms-3"><?=htmlspecialchars($mode)?> : <?=number_format($amount,2,',',' ')?> MAD</span><?php endforeach;?></div><?php endif;?></div>
<script>
document.addEventListener('DOMContentLoaded', function () {
    var table = document.getElementById('statement-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');
        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 === 6; });
            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{display:none!important}.darlink-sort-button{display:block}.sort-indicator{display:none}.darlink-main{margin:0!important}.darlink-card{box-shadow:none!important;border:0!important}}</style>
