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

$typeLabels = [
    'DEVIS' => 'Devis',
    'BL' => 'BL',
    'FACTURE' => 'Facture',
    'AVOIR' => 'Avoir',
];

$typeBadgeClasses = [
    'DEVIS' => 'darlink-badge-primary',
    'BL' => 'darlink-badge-info',
    'FACTURE' => 'darlink-badge-success',
    'AVOIR' => 'darlink-badge-warning',
];
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">
            <i class="bi bi-folder2-open me-2"></i>Documents commerciaux
        </h1>
        <p class="text-muted mb-0">Vue unifiée des devis, BL, factures et avoirs.</p>
    </div>

    <div class="btn-group flex-wrap">
        <a href="index.php?page=documents_create&type=DEVIS" class="btn darlink-btn-primary">
            <i class="bi bi-plus-lg me-1"></i> Devis
        </a>

        <div class="btn-group">
            <button type="button" class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">
                + BL
            </button>
            <ul class="dropdown-menu dropdown-menu-end">
                <li><a class="dropdown-item" href="index.php?page=documents_create&type=BL">Créer un BL vierge</a></li>
                <li><a class="dropdown-item" href="index.php?page=documents_sources&source_type=DEVIS&target_type=BL">Créer depuis un devis</a></li>
            </ul>
        </div>

        <div class="btn-group">
            <button type="button" class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">
                + Facture
            </button>
            <ul class="dropdown-menu dropdown-menu-end">
                <li><a class="dropdown-item" href="index.php?page=documents_create&type=FACTURE">Créer une facture directe</a></li>
                <li><a class="dropdown-item" href="index.php?page=documents_sources&source_type=DEVIS&target_type=FACTURE">Créer depuis un devis</a></li>
                <li><a class="dropdown-item" href="index.php?page=documents_sources&source_type=BL&target_type=FACTURE">Créer depuis un BL</a></li>
            </ul>
        </div>

        <a href="index.php?page=documents_create&type=AVOIR" class="btn btn-outline-secondary">
            + Avoir
        </a>
    </div>
</div>

<?php if (!$tablesReady): ?>
    <div class="alert alert-warning">
        Les tables <strong>documents</strong> et <strong>documents_lignes</strong> ne sont pas encore installées.
        Importez <code>database/migrations/009_document_manager.sql</code>.
    </div>
<?php endif; ?>

<div class="row g-3 mb-4">
    <?php foreach (['DEVIS', 'BL', 'FACTURE', 'AVOIR'] as $type): ?>
        <div class="col-md-3">
            <div class="darlink-stat">
                <span><?= htmlspecialchars($typeLabels[$type]) ?></span>
                <strong><?= (int)($counts[$type] ?? 0) ?></strong>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<div class="darlink-card darlink-table-card">
    <form method="get" class="darlink-table-toolbar">
        <input type="hidden" name="page" value="documents">

        <div class="darlink-table-toolbar-left">
            <div class="darlink-table-search">
                <i class="bi bi-search"></i>
                <input type="text"
                       name="q"
                       value="<?= htmlspecialchars($filters['q'] ?? '') ?>"
                       placeholder="Rechercher un document...">
            </div>

            <select name="type" class="darlink-table-filter">
                <option value="">Tous</option>
                <?php foreach ($typeLabels as $value => $label): ?>
                    <option value="<?= htmlspecialchars($value) ?>" <?= ($filters['type'] ?? '') === $value ? 'selected' : '' ?>>
                        <?= htmlspecialchars($label) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="darlink-table-toolbar-right">
            <button type="submit" class="darlink-toolbar-btn">
                <i class="bi bi-funnel"></i> Filtrer
            </button>

            <a href="index.php?page=documents" class="darlink-toolbar-btn">
                <i class="bi bi-arrow-counterclockwise"></i> Réinitialiser
            </a>
        </div>
    </form>

    <div class="table-responsive darlink-table-wrapper">
        <table class="table align-middle darlink-table darlink-table-modern" id="documentsTable">
            <thead>
            <tr>
                <th class="darlink-sortable" data-column="0">Type <span class="sort-indicator">↕</span></th>
                <th class="darlink-sortable" data-column="1">Numéro <span class="sort-indicator">↕</span></th>
                <th class="darlink-sortable" data-column="2">Client <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">Source <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">Actions</th>
            </tr>
            </thead>

            <tbody>
            <?php if (empty($documents)): ?>
                <tr>
                    <td colspan="8" class="text-center text-muted py-5">
                        Aucun document trouvé.
                    </td>
                </tr>
            <?php endif; ?>

            <?php foreach ($documents as $document): ?>
                <?php
                    $legacyUrl = $documentManager->legacyUrl($document);
                    $actionUrl = $legacyUrl;
                    $actionIcon = 'bi-box-arrow-up-right';
                    $actionTitle = match ((string)($document['source_table'] ?? '')) {
                        'devis' => 'Consulter devis',
                        'bons_livraison' => 'Consulter BL',
                        'factures' => 'Consulter facture',
                        default => 'Consulter',
                    };
                    $actionBtnClass = 'darlink-icon-btn-edit';

                    if (($document['type_document'] ?? '') === 'FACTURE'
                        && (string)($document['source_table'] ?? '') === 'factures'
                        && (int)($document['source_id'] ?? 0) > 0) {
                        $actionUrl = 'index.php?page=encaissements_create&facture_id=' . (int)$document['source_id'];
                        $actionIcon = 'bi-cash-coin';
                        $actionTitle = 'Encaisser';
                        $actionBtnClass = 'darlink-icon-btn-order';
                    }

                    $typeDocument = (string)($document['type_document'] ?? '');
                    $badgeClass = $typeBadgeClasses[$typeDocument] ?? 'darlink-badge-light';
                ?>

                <tr data-edit-url="index.php?page=documents_show&id=<?= (int)$document['id'] ?>">
                    <td>
                        <span class="darlink-badge <?= htmlspecialchars($badgeClass) ?>">
                            <?= htmlspecialchars($typeLabels[$typeDocument] ?? $typeDocument) ?>
                        </span>
                    </td>

                    <td>
                        <strong class="darlink-table-code">
                            <?= htmlspecialchars($document['numero']) ?>
                        </strong>
                    </td>

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

                    <td>
                        <?= htmlspecialchars(date('d/m/Y', strtotime((string)$document['date_document']))) ?>
                    </td>

                    <td>
                        <?= !empty($document['parent_numero'])
                            ? htmlspecialchars(($typeLabels[$document['parent_type']] ?? $document['parent_type']) . ' ' . $document['parent_numero'])
                            : '<span class="text-muted">-</span>' ?>
                    </td>

                    <td>
                        <span class="darlink-badge darlink-badge-light">
                            <?= htmlspecialchars((($document['type_document'] ?? '') === 'FACTURE' && ($document['statut'] ?? '') === 'émise') ? 'En cours' : ($document['statut'] ?? '-')) ?>
                        </span>
                    </td>

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

                    <td class="text-end darlink-actions">
                        <a class="darlink-icon-btn darlink-icon-btn-view"
                           href="index.php?page=documents_show&id=<?= (int)$document['id'] ?>"
                           title="Voir">
                            <i class="bi bi-eye"></i>
                        </a>

                        <?php if ($actionUrl): ?>
                            <a class="darlink-icon-btn <?= htmlspecialchars($actionBtnClass) ?>"
                               href="<?= htmlspecialchars($actionUrl) ?>"
                               title="<?= htmlspecialchars($actionTitle) ?>">
                                <i class="bi <?= htmlspecialchars($actionIcon) ?>"></i>
                            </a>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>