<?php
$formatMoney = static fn($value): string => number_format((float)$value, 2, ',', ' ') . ' MAD';

$statusInfo = static function (array $facture): array {
    $total = (float)($facture['total_ttc'] ?? 0);
    $regle = (float)($facture['montant_regle'] ?? 0);
    $reste = (float)($facture['reste_du'] ?? max(0, $total - $regle));

    if ($reste <= 0.00001 && $total > 0) {
        return ['label' => 'Réglée', 'class' => 'darlink-badge-success', 'filter' => 'réglée'];
    }
    if ($regle > 0) {
        return ['label' => 'Partiellement réglée', 'class' => 'darlink-badge-warning', 'filter' => 'partiellement réglée'];
    }
    return ['label' => 'En cours', 'class' => 'darlink-badge-info', 'filter' => 'en cours'];
};
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">
            <i class="bi bi-receipt me-2"></i>Factures
        </h1>
        <p class="text-muted mb-0"><?= count($factures) ?> facture(s) enregistrée(s)</p>
    </div>

    <div class="d-flex gap-2">
        <a href="index.php?page=documents_create&type=FACTURE" class="btn darlink-btn-primary">
            <i class="bi bi-plus-lg me-1"></i> Facture directe
        </a>
        <a href="index.php?page=documents_sources&source_type=BL&target_type=FACTURE" class="btn btn-outline-primary">
            Depuis un BL
        </a>
    </div>
</div>

<div class="darlink-card darlink-table-card">
    <div class="darlink-table-toolbar">
        <div class="darlink-table-toolbar-left">
            <div class="darlink-table-search">
                <i class="bi bi-search"></i>
                <input type="text" id="factureSearch" placeholder="Rechercher une facture...">
            </div>

            <select id="factureStatusFilter" class="darlink-table-filter">
                <option value="">Tous les statuts</option>
                <option value="en cours">En cours</option>
                <option value="partiellement réglée">Partiellement réglée</option>
                <option value="réglée">Réglée</option>
            </select>

            <input type="date" id="factureDateFrom" class="darlink-table-filter" title="Date début">
            <input type="date" id="factureDateTo" class="darlink-table-filter" title="Date fin">
        </div>

        <div class="darlink-table-toolbar-right">
            <button type="button" class="darlink-toolbar-btn" onclick="location.reload();">
                <i class="bi bi-arrow-clockwise"></i> Actualiser
            </button>
        </div>
    </div>

    <div class="table-responsive darlink-table-wrapper">
        <table class="table align-middle darlink-table darlink-table-modern" id="facturesTable">
            <thead>
            <tr>
                <th class="darlink-sortable" data-column="0">Numéro <span class="sort-indicator">↕</span></th>
                <th class="darlink-sortable" data-column="1">Client <span class="sort-indicator">↕</span></th>
                <th class="darlink-sortable" data-column="2">BL <span class="sort-indicator">↕</span></th>
                <th class="darlink-sortable" data-column="3">Date <span class="sort-indicator">↕</span></th>
                <th class="darlink-sortable" data-column="4">Échéance <span class="sort-indicator">↕</span></th>
                <th class="darlink-sortable" data-column="5">Statut <span class="sort-indicator">↕</span></th>
                <th class="text-end darlink-sortable" data-column="6">Total TTC <span class="sort-indicator">↕</span></th>
                <th class="text-end darlink-sortable" data-column="7">Réglé <span class="sort-indicator">↕</span></th>
                <th class="text-end darlink-sortable" data-column="8">Reste <span class="sort-indicator">↕</span></th>
                <th class="text-end">Actions</th>
            </tr>
            </thead>

            <tbody>
            <?php if (empty($factures)): ?>
                <tr>
                    <td colspan="10" class="text-center text-muted py-5">
                        Aucune facture pour le moment.
                    </td>
                </tr>
            <?php endif; ?>

            <?php foreach ($factures as $facture): ?>
                <?php
                    $status = $statusInfo($facture);
                    $reste = (float)($facture['reste_du'] ?? 0);
                    $regle = (float)($facture['montant_regle'] ?? 0);
                    $documentId = (int)($facture['document_id'] ?? 0);
                    $canEdit = $documentId > 0 && $reste > 0.005;
                    $showUrl = $documentId > 0
                        ? 'index.php?page=documents_show&id=' . $documentId
                        : 'index.php?page=factures_show&id=' . (int)$facture['id'];
                ?>

                <tr data-edit-url="<?= htmlspecialchars($showUrl) ?>"
                    data-status="<?= htmlspecialchars($status['filter']) ?>"
                    data-date="<?= htmlspecialchars((string)$facture['date_facture']) ?>">
                    <td>
                        <strong class="darlink-table-code">
                            <?= htmlspecialchars((string)$facture['numero']) ?>
                        </strong>
                    </td>

                    <td class="fw-semibold">
                        <?= htmlspecialchars((string)$facture['client_nom']) ?>
                    </td>

                    <td><?= htmlspecialchars((string)($facture['bl_numero'] ?? '-')) ?></td>

                    <td><?= htmlspecialchars((string)$facture['date_facture']) ?></td>

                    <td><?= htmlspecialchars((string)($facture['date_echeance'] ?? '-')) ?></td>

                    <td>
                        <span class="darlink-badge <?= htmlspecialchars($status['class']) ?>">
                            <?= htmlspecialchars($status['label']) ?>
                        </span>
                    </td>

                    <td class="text-end fw-semibold">
                        <?= $formatMoney($facture['total_ttc']) ?>
                    </td>

                    <td class="text-end text-success">
                        <?= $formatMoney($facture['montant_regle'] ?? 0) ?>
                    </td>

                    <td class="text-end <?= $reste > 0 ? 'text-danger' : 'text-success' ?> fw-semibold">
                        <?= $formatMoney($reste) ?>
                    </td>

                    <td class="text-end darlink-actions">
                        <a class="darlink-icon-btn darlink-icon-btn-view"
                           href="<?= htmlspecialchars($showUrl) ?>"
                           title="Consulter">
                            <i class="bi bi-eye"></i>
                        </a>

                        <?php if ($canEdit): ?>
                            <a class="darlink-icon-btn darlink-icon-btn-edit"
                               href="index.php?page=documents_edit&id=<?= $documentId ?>"
                               title="Modifier">
                                <i class="bi bi-pencil"></i>
                            </a>
                        <?php else: ?>
                            <button type="button"
                                    class="darlink-icon-btn"
                                    title="Modification verrouillée"
                                    disabled>
                                <i class="bi bi-lock"></i>
                            </button>
                        <?php endif; ?>

                        <?php if ($reste > 0): ?>
                            <a class="darlink-icon-btn darlink-icon-btn-order"
                               href="index.php?page=encaissements_create&facture_id=<?= (int)$facture['id'] ?>"
                               title="Encaisser">
                                <i class="bi bi-cash-coin"></i>
                            </a>
                        <?php else: ?>
                            <button type="button"
                                    class="darlink-icon-btn"
                                    title="Facture réglée"
                                    disabled>
                                <i class="bi bi-cash-coin"></i>
                            </button>
                        <?php endif; ?>

                        <?php if ($documentId > 0): ?>
                            <a class="darlink-icon-btn darlink-icon-btn-edit"
                               href="index.php?page=avoirs_create&facture_id=<?= $documentId ?>"
                               title="Créer un avoir">
                                <i class="bi bi-receipt-cutoff"></i>
                            </a>
                        <?php else: ?>
                            <button type="button"
                                    class="darlink-icon-btn"
                                    title="Avoir indisponible"
                                    disabled>
                                <i class="bi bi-receipt-cutoff"></i>
                            </button>
                        <?php endif; ?>

                        <a class="darlink-icon-btn darlink-icon-btn-edit"
                           target="_blank"
                           href="index.php?page=factures_pdf&id=<?= (int)$facture['id'] ?>"
                           title="PDF">
                            <i class="bi bi-file-earmark-pdf"></i>
                        </a>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <div class="p-3 border-top bg-light">
        <p class="text-muted small mb-0">
            Les factures réglées ou partiellement réglées sont protégées : les montants ne peuvent plus être modifiés.
        </p>
    </div>
</div>

<script>
function filterFactures(){
    const search = (document.getElementById('factureSearch')?.value || '').toLowerCase();
    const status = (document.getElementById('factureStatusFilter')?.value || '').toLowerCase();
    const from = document.getElementById('factureDateFrom')?.value || '';
    const to = document.getElementById('factureDateTo')?.value || '';

    document.querySelectorAll('#facturesTable tbody tr').forEach(row => {
        if(!row.dataset.status){ return; }

        let visible = row.innerText.toLowerCase().includes(search);

        if(status && (row.dataset.status || '').toLowerCase() !== status) visible = false;
        if(from && (row.dataset.date || '') < from) visible = false;
        if(to && (row.dataset.date || '') > to) visible = false;

        row.style.display = visible ? '' : 'none';
    });
}

['factureSearch','factureStatusFilter','factureDateFrom','factureDateTo'].forEach(id => {
    document.getElementById(id)?.addEventListener('input', filterFactures);
    document.getElementById(id)?.addEventListener('change', filterFactures);
});
</script>